From 3a4a11f73853c4ada6af770feace938298323a98 Mon Sep 17 00:00:00 2001 From: clang-format Date: Fri, 22 Jun 2018 22:58:39 +0200 Subject: [PATCH] clang-format core --- src/openrct2/core/Collections.hpp | 43 ++--- src/openrct2/core/Console.cpp | 21 +-- src/openrct2/core/Console.hpp | 14 +- src/openrct2/core/Crypt.OpenSSL.cpp | 63 +++---- src/openrct2/core/Crypt.h | 25 ++- src/openrct2/core/DataSerialiser.h | 16 +- src/openrct2/core/DataSerialiserTraits.h | 71 ++++---- src/openrct2/core/Diagnostics.cpp | 4 +- src/openrct2/core/Endianness.h | 22 +-- src/openrct2/core/File.cpp | 41 ++--- src/openrct2/core/File.h | 17 +- src/openrct2/core/FileIndex.hpp | 126 +++++++------- src/openrct2/core/FileScanner.cpp | 201 +++++++++++------------ src/openrct2/core/FileScanner.h | 21 +-- src/openrct2/core/FileStream.hpp | 150 +++++++++-------- src/openrct2/core/Guard.cpp | 54 +++--- src/openrct2/core/Guard.hpp | 25 +-- src/openrct2/core/IStream.cpp | 12 +- src/openrct2/core/IStream.hpp | 70 ++++---- src/openrct2/core/Imaging.cpp | 38 +++-- src/openrct2/core/Imaging.h | 11 +- src/openrct2/core/JobPool.hpp | 23 +-- src/openrct2/core/Json.cpp | 17 +- src/openrct2/core/Json.hpp | 22 ++- src/openrct2/core/Math.hpp | 12 +- src/openrct2/core/Memory.hpp | 29 ++-- src/openrct2/core/MemoryStream.cpp | 59 +++---- src/openrct2/core/MemoryStream.h | 46 +++--- src/openrct2/core/Nullable.hpp | 10 +- src/openrct2/core/Path.cpp | 82 +++++---- src/openrct2/core/Path.hpp | 44 ++--- src/openrct2/core/Registration.hpp | 12 +- src/openrct2/core/String.cpp | 196 +++++++++++----------- src/openrct2/core/String.hpp | 101 ++++++------ src/openrct2/core/StringBuilder.hpp | 40 +++-- src/openrct2/core/StringReader.hpp | 24 +-- src/openrct2/core/Util.hpp | 13 +- src/openrct2/core/Zip.cpp | 10 +- src/openrct2/core/Zip.h | 9 +- src/openrct2/core/ZipAndroid.cpp | 52 +++--- 40 files changed, 929 insertions(+), 917 deletions(-) diff --git a/src/openrct2/core/Collections.hpp b/src/openrct2/core/Collections.hpp index 0f618669b0..54ef228c8b 100644 --- a/src/openrct2/core/Collections.hpp +++ b/src/openrct2/core/Collections.hpp @@ -9,21 +9,22 @@ #pragma once -#include #include "../common.h" #include "Memory.hpp" #include "String.hpp" +#include + namespace Collections { template - static void AddRange(TCollection &collection, std::initializer_list initializerList) + static void AddRange(TCollection& collection, std::initializer_list initializerList) { collection.insert(collection.end(), initializerList.begin(), initializerList.end()); } template - static bool Contains(TCollection &collection, TItem needle, TComparer comparer) + static bool Contains(TCollection& collection, TItem needle, TComparer comparer) { for (TItem item : collection) { @@ -36,7 +37,7 @@ namespace Collections } template - static size_t IndexOf(TCollection &collection, TItem needle, TComparer comparer) + static size_t IndexOf(TCollection& collection, TItem needle, TComparer comparer) { size_t index = 0; for (TItem item : collection) @@ -50,8 +51,7 @@ namespace Collections return SIZE_MAX; } - template - static size_t IndexOf(TCollection &collection, TPred predicate) + template static size_t IndexOf(TCollection& collection, TPred predicate) { size_t index = 0; for (auto item : collection) @@ -65,30 +65,21 @@ namespace Collections return SIZE_MAX; } - #pragma region String helpers +#pragma region String helpers - template - static bool Contains(TCollection &collection, const char * item, bool ignoreCase = false) + template static bool Contains(TCollection& collection, const char* item, bool ignoreCase = false) { - return Contains(collection, item, - [ignoreCase](const char * a, const char * b) - { - return String::Equals(a, b, ignoreCase); - }); + return Contains( + collection, item, [ignoreCase](const char* a, const char* b) { return String::Equals(a, b, ignoreCase); }); } - template - static size_t IndexOf(TCollection &collection, const char * item, bool ignoreCase = false) + template static size_t IndexOf(TCollection& collection, const char* item, bool ignoreCase = false) { - return IndexOf(collection, item, - [ignoreCase](const char * a, const char * b) - { - return String::Equals(a, b, ignoreCase); - }); + return IndexOf( + collection, item, [ignoreCase](const char* a, const char* b) { return String::Equals(a, b, ignoreCase); }); } - template - static typename TCollection::value_type * ToArray(const TCollection &collection) + template static typename TCollection::value_type* ToArray(const TCollection& collection) { size_t count = collection.size(); if (count == 0) @@ -96,9 +87,9 @@ namespace Collections return nullptr; } - auto * items = Memory::AllocateArray(count); + auto* items = Memory::AllocateArray(count); size_t i = 0; - for (const auto &item : collection) + for (const auto& item : collection) { items[i] = item; i++; @@ -106,5 +97,5 @@ namespace Collections return items; } - #pragma endregion +#pragma endregion } // namespace Collections diff --git a/src/openrct2/core/Console.cpp b/src/openrct2/core/Console.cpp index 67536c2b06..b91ffc9937 100644 --- a/src/openrct2/core/Console.cpp +++ b/src/openrct2/core/Console.cpp @@ -7,12 +7,13 @@ * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ +#include "Console.hpp" + +#include "../platform/platform.h" + #include #include -#include "Console.hpp" -#include "../platform/platform.h" - namespace Console { void Write(char c) @@ -20,7 +21,7 @@ namespace Console fputc(c, stdout); } - void Write(const utf8 * str) + void Write(const utf8* str) { fputs(str, stdout); } @@ -31,7 +32,7 @@ namespace Console Write(sz.c_str()); } - void WriteFormat(const utf8 * format, ...) + void WriteFormat(const utf8* format, ...) { va_list args; @@ -45,7 +46,7 @@ namespace Console puts(""); } - void WriteLine(const utf8 * format, ...) + void WriteLine(const utf8* format, ...) { va_list args; @@ -62,12 +63,12 @@ namespace Console fputc(c, stderr); } - void Write(const utf8 * str) + void Write(const utf8* str) { fputs(str, stderr); } - void WriteFormat(const utf8 * format, ...) + void WriteFormat(const utf8* format, ...) { va_list args; @@ -81,7 +82,7 @@ namespace Console fputs(PLATFORM_NEWLINE, stderr); } - void WriteLine(const utf8 * format, ...) + void WriteLine(const utf8* format, ...) { va_list args; va_start(args, format); @@ -89,7 +90,7 @@ namespace Console va_end(args); } - void WriteLine_VA(const utf8 * format, va_list args) + void WriteLine_VA(const utf8* format, va_list args) { auto formatLn = std::string(format) + "\n"; vfprintf(stdout, formatLn.c_str(), args); diff --git a/src/openrct2/core/Console.hpp b/src/openrct2/core/Console.hpp index 029ced1ab1..097f9ac75b 100644 --- a/src/openrct2/core/Console.hpp +++ b/src/openrct2/core/Console.hpp @@ -16,19 +16,19 @@ namespace Console { void Write(char c); - void Write(const utf8 * str); + void Write(const utf8* str); void WriteSpace(size_t count); - void WriteFormat(const utf8 * format, ...); + void WriteFormat(const utf8* format, ...); void WriteLine(); - void WriteLine(const utf8 * format, ...); + void WriteLine(const utf8* format, ...); namespace Error { void Write(char c); - void Write(const utf8 * str); - void WriteFormat(const utf8 * format, ...); + void Write(const utf8* str); + void WriteFormat(const utf8* format, ...); void WriteLine(); - void WriteLine(const utf8 * format, ...); - void WriteLine_VA(const utf8 * format, va_list args); + void WriteLine(const utf8* format, ...); + void WriteLine_VA(const utf8* format, va_list args); } // namespace Error } // namespace Console diff --git a/src/openrct2/core/Crypt.OpenSSL.cpp b/src/openrct2/core/Crypt.OpenSSL.cpp index 2d9e9bf737..8b421f7658 100644 --- a/src/openrct2/core/Crypt.OpenSSL.cpp +++ b/src/openrct2/core/Crypt.OpenSSL.cpp @@ -10,11 +10,12 @@ #ifndef DISABLE_NETWORK #include "Crypt.h" + +#include +#include #include #include #include -#include -#include using namespace Crypt; @@ -36,16 +37,15 @@ static void OpenSSLInitialise() } } -template -class OpenSSLHashAlgorithm final : public TBase +template class OpenSSLHashAlgorithm final : public TBase { private: - const EVP_MD * _type; - EVP_MD_CTX * _ctx{}; + const EVP_MD* _type; + EVP_MD_CTX* _ctx{}; bool _initialised{}; public: - OpenSSLHashAlgorithm(const EVP_MD * type) + OpenSSLHashAlgorithm(const EVP_MD* type) { _type = type; _ctx = EVP_MD_CTX_create(); @@ -60,7 +60,7 @@ public: EVP_MD_CTX_destroy(_ctx); } - TBase * Clear() override + TBase* Clear() override { if (EVP_DigestInit_ex(_ctx, _type, nullptr) <= 0) { @@ -70,7 +70,7 @@ public: return this; } - TBase * Update(const void * data, size_t dataLen) override + TBase* Update(const void* data, size_t dataLen) override { // Auto initialise if (!_initialised) @@ -111,7 +111,10 @@ public: class OpenSSLRsaKey final : public RsaKey { public: - EVP_PKEY * GetEvpKey() const { return _evpKey; } + EVP_PKEY* GetEvpKey() const + { + return _evpKey; + } ~OpenSSLRsaKey() { @@ -137,7 +140,7 @@ public: status = EVP_PKEY_keygen_init(ctx); OpenSSLThrowOnBadStatus("EVP_PKEY_keygen_init", status); - EVP_PKEY * key{}; + EVP_PKEY* key{}; status = EVP_PKEY_keygen(ctx, &key); OpenSSLThrowOnBadStatus("EVP_PKEY_keygen", status); @@ -163,31 +166,34 @@ public: SetKey(pem, false); } - std::string GetPrivate() override { return GetKey(true); } + std::string GetPrivate() override + { + return GetKey(true); + } - std::string GetPublic() override { return GetKey(false); } + std::string GetPublic() override + { + return GetKey(false); + } private: - EVP_PKEY * _evpKey{}; + EVP_PKEY* _evpKey{}; void SetKey(const std::string_view& pem, bool isPrivate) { // Read PEM data via BIO buffer // HACK first parameter is not const on MINGW for some reason - auto bio = BIO_new_mem_buf((void *)pem.data(), (int)pem.size()); + auto bio = BIO_new_mem_buf((void*)pem.data(), (int)pem.size()); if (bio == nullptr) { throw std::runtime_error("BIO_new_mem_buf failed"); } - auto rsa = isPrivate ? - PEM_read_bio_RSAPrivateKey(bio, nullptr, nullptr, nullptr) : - PEM_read_bio_RSAPublicKey(bio, nullptr, nullptr, nullptr); + auto rsa = isPrivate ? PEM_read_bio_RSAPrivateKey(bio, nullptr, nullptr, nullptr) + : PEM_read_bio_RSAPublicKey(bio, nullptr, nullptr, nullptr); if (rsa == nullptr) { BIO_free_all(bio); - auto msg = isPrivate ? - "PEM_read_bio_RSAPrivateKey failed" : - "PEM_read_bio_RSAPublicKey failed"; + auto msg = isPrivate ? "PEM_read_bio_RSAPrivateKey failed" : "PEM_read_bio_RSAPublicKey failed"; throw std::runtime_error(msg); } BIO_free_all(bio); @@ -224,9 +230,8 @@ private: throw std::runtime_error("BIO_new failed"); } - auto status = isPrivate ? - PEM_write_bio_RSAPrivateKey(bio, rsa, nullptr, nullptr, 0, nullptr, nullptr) : - PEM_write_bio_RSAPublicKey(bio, rsa); + auto status = isPrivate ? PEM_write_bio_RSAPrivateKey(bio, rsa, nullptr, nullptr, 0, nullptr, nullptr) + : PEM_write_bio_RSAPublicKey(bio, rsa); if (status != 1) { BIO_free_all(bio); @@ -246,10 +251,10 @@ private: class OpenSSLRsaAlgorithm final : public RsaAlgorithm { public: - std::vector SignData(const RsaKey& key, const void * data, size_t dataLen) override + std::vector SignData(const RsaKey& key, const void* data, size_t dataLen) override { auto evpKey = static_cast(key).GetEvpKey(); - EVP_MD_CTX * mdctx{}; + EVP_MD_CTX* mdctx{}; try { mdctx = EVP_MD_CTX_create(); @@ -284,10 +289,10 @@ public: } } - bool VerifyData(const RsaKey& key, const void * data, size_t dataLen, const void * sig, size_t sigLen) override + bool VerifyData(const RsaKey& key, const void* data, size_t dataLen, const void* sig, size_t sigLen) override { auto evpKey = static_cast(key).GetEvpKey(); - EVP_MD_CTX * mdctx{}; + EVP_MD_CTX* mdctx{}; try { mdctx = EVP_MD_CTX_create(); @@ -343,6 +348,6 @@ namespace Crypt OpenSSLInitialise(); return std::make_unique(); } -} +} // namespace Crypt #endif // DISABLE_NETWORK diff --git a/src/openrct2/core/Crypt.h b/src/openrct2/core/Crypt.h index e2402135ce..2cf3a44389 100644 --- a/src/openrct2/core/Crypt.h +++ b/src/openrct2/core/Crypt.h @@ -16,15 +16,14 @@ namespace Crypt { - template - class HashAlgorithm + template class HashAlgorithm { public: typedef std::array Result; virtual ~HashAlgorithm() = default; - virtual HashAlgorithm * Clear() = 0; - virtual HashAlgorithm * Update(const void * data, size_t dataLen) = 0; + virtual HashAlgorithm* Clear() = 0; + virtual HashAlgorithm* Update(const void* data, size_t dataLen) = 0; virtual Result Finish() = 0; }; @@ -43,8 +42,8 @@ namespace Crypt { public: virtual ~RsaAlgorithm() = default; - virtual std::vector SignData(const RsaKey& key, const void * data, size_t dataLen) = 0; - virtual bool VerifyData(const RsaKey& key, const void * data, size_t dataLen, const void * sig, size_t sigLen) = 0; + virtual std::vector SignData(const RsaKey& key, const void* data, size_t dataLen) = 0; + virtual bool VerifyData(const RsaKey& key, const void* data, size_t dataLen, const void* sig, size_t sigLen) = 0; }; using Sha1Algorithm = HashAlgorithm<20>; @@ -56,17 +55,13 @@ namespace Crypt std::unique_ptr CreateRSA(); std::unique_ptr CreateRSAKey(); - inline Sha1Algorithm::Result SHA1(const void * data, size_t dataLen) + inline Sha1Algorithm::Result SHA1(const void* data, size_t dataLen) { - return CreateSHA1() - ->Update(data, dataLen) - ->Finish(); + return CreateSHA1()->Update(data, dataLen)->Finish(); } - inline Sha256Algorithm::Result SHA256(const void * data, size_t dataLen) + inline Sha256Algorithm::Result SHA256(const void* data, size_t dataLen) { - return CreateSHA256() - ->Update(data, dataLen) - ->Finish(); + return CreateSHA256()->Update(data, dataLen)->Finish(); } -} +} // namespace Crypt diff --git a/src/openrct2/core/DataSerialiser.h b/src/openrct2/core/DataSerialiser.h index 02006a5ae3..3ad13cdae2 100644 --- a/src/openrct2/core/DataSerialiser.h +++ b/src/openrct2/core/DataSerialiser.h @@ -9,23 +9,26 @@ #pragma once -#include #include "DataSerialiserTraits.h" +#include + class DataSerialiser { private: MemoryStream _stream; - MemoryStream *_activeStream; + MemoryStream* _activeStream; bool _isSaving; public: - DataSerialiser(bool isSaving) : _isSaving(isSaving) + DataSerialiser(bool isSaving) + : _isSaving(isSaving) { _activeStream = &_stream; } - DataSerialiser(bool isSaving, MemoryStream& stream) : _isSaving(isSaving) + DataSerialiser(bool isSaving, MemoryStream& stream) + : _isSaving(isSaving) { _activeStream = &stream; } @@ -45,12 +48,11 @@ public: return _stream; } - template - DataSerialiser& operator<<(T& data) + template DataSerialiser& operator<<(T& data) { if (_isSaving) DataSerializerTraits::encode(_activeStream, data); - else + else DataSerializerTraits::decode(_activeStream, data); return *this; } diff --git a/src/openrct2/core/DataSerialiserTraits.h b/src/openrct2/core/DataSerialiserTraits.h index 0dad1264f4..b1510dd8e7 100644 --- a/src/openrct2/core/DataSerialiserTraits.h +++ b/src/openrct2/core/DataSerialiserTraits.h @@ -12,21 +12,20 @@ #include "Endianness.h" #include "MemoryStream.h" -template -struct DataSerializerTraits { - static void encode(IStream *stream, const T& v) = delete; - static void decode(IStream *stream, T& val) = delete; +template struct DataSerializerTraits +{ + static void encode(IStream* stream, const T& v) = delete; + static void decode(IStream* stream, T& val) = delete; }; -template -struct DataSerializerTraitsIntegral +template struct DataSerializerTraitsIntegral { - static void encode(IStream *stream, const T& val) + static void encode(IStream* stream, const T& val) { T temp = ByteSwapBE(val); stream->Write(&temp); } - static void decode(IStream *stream, T& val) + static void decode(IStream* stream, T& val) { T temp; stream->Read(&temp); @@ -34,38 +33,44 @@ struct DataSerializerTraitsIntegral } }; -template<> -struct DataSerializerTraits : public DataSerializerTraitsIntegral {}; - -template<> -struct DataSerializerTraits : public DataSerializerTraitsIntegral {}; - -template<> -struct DataSerializerTraits : public DataSerializerTraitsIntegral {}; - -template<> -struct DataSerializerTraits : public DataSerializerTraitsIntegral {}; - -template<> -struct DataSerializerTraits : public DataSerializerTraitsIntegral {}; - -template<> -struct DataSerializerTraits : public DataSerializerTraitsIntegral {}; - -template<> -struct DataSerializerTraits : public DataSerializerTraitsIntegral {}; - -template<> -struct DataSerializerTraits +template<> struct DataSerializerTraits : public DataSerializerTraitsIntegral { - static void encode(IStream *stream, const std::string& str) +}; + +template<> struct DataSerializerTraits : public DataSerializerTraitsIntegral +{ +}; + +template<> struct DataSerializerTraits : public DataSerializerTraitsIntegral +{ +}; + +template<> struct DataSerializerTraits : public DataSerializerTraitsIntegral +{ +}; + +template<> struct DataSerializerTraits : public DataSerializerTraitsIntegral +{ +}; + +template<> struct DataSerializerTraits : public DataSerializerTraitsIntegral +{ +}; + +template<> struct DataSerializerTraits : public DataSerializerTraitsIntegral +{ +}; + +template<> struct DataSerializerTraits +{ + static void encode(IStream* stream, const std::string& str) { uint16_t len = (uint16_t)str.size(); uint16_t swapped = ByteSwapBE(len); stream->Write(&swapped); stream->WriteArray(str.c_str(), len); } - static void decode(IStream *stream, std::string& res) + static void decode(IStream* stream, std::string& res) { uint16_t len; stream->Read(&len); diff --git a/src/openrct2/core/Diagnostics.cpp b/src/openrct2/core/Diagnostics.cpp index 0aa6483a3d..d50cfaa73e 100644 --- a/src/openrct2/core/Diagnostics.cpp +++ b/src/openrct2/core/Diagnostics.cpp @@ -8,8 +8,8 @@ *****************************************************************************/ #if defined(DEBUG) && defined(_WIN32) - #define WIN32_LEAN_AND_MEAN - #include +#define WIN32_LEAN_AND_MEAN +#include #endif #include "Diagnostics.hpp" diff --git a/src/openrct2/core/Endianness.h b/src/openrct2/core/Endianness.h index 2079b6b009..f0e642dfac 100644 --- a/src/openrct2/core/Endianness.h +++ b/src/openrct2/core/Endianness.h @@ -11,11 +11,11 @@ #include "../common.h" -template -struct ByteSwapT { }; +template struct ByteSwapT +{ +}; -template <> -struct ByteSwapT<1> +template<> struct ByteSwapT<1> { static uint8_t SwapBE(uint8_t value) { @@ -23,8 +23,7 @@ struct ByteSwapT<1> } }; -template <> -struct ByteSwapT<2> +template<> struct ByteSwapT<2> { static uint16_t SwapBE(uint16_t value) { @@ -32,20 +31,15 @@ struct ByteSwapT<2> } }; -template <> -struct ByteSwapT<4> +template<> struct ByteSwapT<4> { static uint32_t SwapBE(uint32_t value) { - return (uint32_t)(((value << 24) | - ((value << 8) & 0x00FF0000) | - ((value >> 8) & 0x0000FF00) | - (value >> 24))); + return (uint32_t)(((value << 24) | ((value << 8) & 0x00FF0000) | ((value >> 8) & 0x0000FF00) | (value >> 24))); } }; -template -static T ByteSwapBE(const T& value) +template static T ByteSwapBE(const T& value) { return ByteSwapT::SwapBE(value); } diff --git a/src/openrct2/core/File.cpp b/src/openrct2/core/File.cpp index ad03c888c9..37b75c01bf 100644 --- a/src/openrct2/core/File.cpp +++ b/src/openrct2/core/File.cpp @@ -8,38 +8,38 @@ *****************************************************************************/ #ifdef _WIN32 - #define WIN32_LEAN_AND_MEAN - #include +#define WIN32_LEAN_AND_MEAN +#include #else - #include +#include #endif -#include +#include "../platform/platform.h" +#include "../util/Util.h" #include "File.h" #include "FileStream.hpp" #include "String.hpp" -#include "../util/Util.h" -#include "../platform/platform.h" +#include namespace File { - bool Exists(const std::string &path) + bool Exists(const std::string& path) { return platform_file_exists(path.c_str()); } - bool Copy(const std::string &srcPath, const std::string &dstPath, bool overwrite) + bool Copy(const std::string& srcPath, const std::string& dstPath, bool overwrite) { return platform_file_copy(srcPath.c_str(), dstPath.c_str(), overwrite); } - bool Delete(const std::string &path) + bool Delete(const std::string& path) { return platform_file_delete(path.c_str()); } - bool Move(const std::string &srcPath, const std::string &dstPath) + bool Move(const std::string& srcPath, const std::string& dstPath) { return platform_file_move(srcPath.c_str(), dstPath.c_str()); } @@ -70,7 +70,7 @@ namespace File { result.resize(fsize); fs.seekg(0); - fs.read((char *)result.data(), result.size()); + fs.read((char*)result.data(), result.size()); fs.exceptions(fs.failbit); } return result; @@ -85,17 +85,17 @@ namespace File return result; } - void WriteAllBytes(const std::string &path, const void * buffer, size_t length) + void WriteAllBytes(const std::string& path, const void* buffer, size_t length) { auto fs = FileStream(path, FILE_MODE_WRITE); fs.Write(buffer, length); } - std::vector ReadAllLines(const std::string &path) + std::vector ReadAllLines(const std::string& path) { std::vector lines; auto data = ReadAllBytes(path); - auto lineStart = (const char *)data.data(); + auto lineStart = (const char*)data.data(); auto ch = lineStart; char lastC = 0; for (size_t i = 0; i < data.size(); i++) @@ -120,7 +120,7 @@ namespace File return lines; } - uint64_t GetLastModified(const std::string &path) + uint64_t GetLastModified(const std::string& path) { uint64_t lastModified = 0; #ifdef _WIN32 @@ -137,26 +137,27 @@ namespace File } free(pathW); #else - struct stat statInfo{}; + struct stat statInfo + { + }; if (stat(path.c_str(), &statInfo) == 0) { lastModified = statInfo.st_mtime; } #endif - return lastModified; + return lastModified; } } // namespace File -bool writeentirefile(const utf8 * path, const void * buffer, size_t length) +bool writeentirefile(const utf8* path, const void* buffer, size_t length) { try { File::WriteAllBytes(String::ToStd(path), buffer, length); return true; } - catch (const std::exception &) + catch (const std::exception&) { return false; } } - diff --git a/src/openrct2/core/File.h b/src/openrct2/core/File.h index dc6e869c66..cbb68b83fe 100644 --- a/src/openrct2/core/File.h +++ b/src/openrct2/core/File.h @@ -9,20 +9,21 @@ #pragma once +#include "../common.h" + #include #include #include -#include "../common.h" namespace File { - bool Exists(const std::string &path); - bool Copy(const std::string &srcPath, const std::string &dstPath, bool overwrite); - bool Delete(const std::string &path); - bool Move(const std::string &srcPath, const std::string &dstPath); + bool Exists(const std::string& path); + bool Copy(const std::string& srcPath, const std::string& dstPath, bool overwrite); + bool Delete(const std::string& path); + bool Move(const std::string& srcPath, const std::string& dstPath); std::vector ReadAllBytes(const std::string_view& path); std::string ReadAllText(const std::string_view& path); - void WriteAllBytes(const std::string &path, const void * buffer, size_t length); - std::vector ReadAllLines(const std::string &path); - uint64_t GetLastModified(const std::string &path); + void WriteAllBytes(const std::string& path, const void* buffer, size_t length); + std::vector ReadAllLines(const std::string& path); + uint64_t GetLastModified(const std::string& path); } // namespace File diff --git a/src/openrct2/core/FileIndex.hpp b/src/openrct2/core/FileIndex.hpp index 9c26f84f8b..6de7e9a698 100644 --- a/src/openrct2/core/FileIndex.hpp +++ b/src/openrct2/core/FileIndex.hpp @@ -9,11 +9,6 @@ #pragma once -#include -#include -#include -#include -#include #include "../common.h" #include "Console.hpp" #include "File.h" @@ -22,8 +17,13 @@ #include "JobPool.hpp" #include "Path.hpp" -template -class FileIndex +#include +#include +#include +#include +#include + +template class FileIndex { private: struct DirectoryStats @@ -40,21 +40,21 @@ private: std::vector const Files; ScanResult(DirectoryStats stats, std::vector files) - : Stats(stats), - Files(files) + : Stats(stats) + , Files(files) { } }; struct FileIndexHeader { - uint32_t HeaderSize = sizeof(FileIndexHeader); - uint32_t MagicNumber = 0; - uint8_t VersionA = 0; - uint8_t VersionB = 0; - uint16_t LanguageId = 0; - DirectoryStats Stats; - uint32_t NumItems = 0; + uint32_t HeaderSize = sizeof(FileIndexHeader); + uint32_t MagicNumber = 0; + uint8_t VersionA = 0; + uint8_t VersionB = 0; + uint16_t LanguageId = 0; + DirectoryStats Stats; + uint32_t NumItems = 0; }; // Index file format version which when incremented forces a rebuild @@ -79,18 +79,19 @@ public: * @param pattern The search pattern for indexing files. * @param paths A list of search directories. */ - FileIndex(std::string name, - uint32_t magicNumber, - uint8_t version, - std::string indexPath, - std::string pattern, - std::vector paths) : - _name(name), - _magicNumber(magicNumber), - _version(version), - _indexPath(indexPath), - _pattern(pattern), - SearchPaths(paths) + FileIndex( + std::string name, + uint32_t magicNumber, + uint8_t version, + std::string indexPath, + std::string pattern, + std::vector paths) + : _name(name) + , _magicNumber(magicNumber) + , _version(version) + , _indexPath(indexPath) + , _pattern(pattern) + , SearchPaths(paths) { } @@ -130,22 +131,22 @@ protected: * Loads the given file and creates the item representing the data to store in the index. * TODO Use std::optional when C++17 is available. */ - virtual std::tuple Create(int32_t language, const std::string &path) const abstract; + virtual std::tuple Create(int32_t language, const std::string& path) const abstract; /** * Serialises an index item to the given stream. */ - virtual void Serialise(IStream * stream, const TItem &item) const abstract; + virtual void Serialise(IStream* stream, const TItem& item) const abstract; /** * Deserialises an index item from the given stream. */ - virtual TItem Deserialise(IStream * stream) const abstract; + virtual TItem Deserialise(IStream* stream) const abstract; private: ScanResult Scan() const { - DirectoryStats stats {}; + DirectoryStats stats{}; std::vector files; for (const auto& directory : SearchPaths) { @@ -162,9 +163,8 @@ private: stats.TotalFiles++; stats.TotalFileSize += fileInfo->Size; - stats.FileDateModifiedChecksum ^= - (uint32_t)(fileInfo->LastModified >> 32) ^ - (uint32_t)(fileInfo->LastModified & 0xFFFFFFFF); + stats.FileDateModifiedChecksum + ^= (uint32_t)(fileInfo->LastModified >> 32) ^ (uint32_t)(fileInfo->LastModified & 0xFFFFFFFF); stats.FileDateModifiedChecksum = ror32(stats.FileDateModifiedChecksum, 5); stats.PathChecksum += GetPathChecksum(path); } @@ -173,13 +173,14 @@ private: return ScanResult(stats, files); } - void BuildRange(int32_t language, - const ScanResult &scanResult, - size_t rangeStart, - size_t rangeEnd, - std::vector& items, - std::atomic& processed, - std::mutex& printLock) const + void BuildRange( + int32_t language, + const ScanResult& scanResult, + size_t rangeStart, + size_t rangeEnd, + std::vector& items, + std::atomic& processed, + std::mutex& printLock) const { items.reserve(rangeEnd - rangeStart); for (size_t i = rangeStart; i < rangeEnd; i++) @@ -202,7 +203,7 @@ private: } } - std::vector Build(int32_t language, const ScanResult &scanResult) const + std::vector Build(int32_t language, const ScanResult& scanResult) const { std::vector allItems; Console::WriteLine("Building %s (%zu items)", _name.c_str(), scanResult.Files.size()); @@ -221,12 +222,10 @@ private: std::atomic processed = ATOMIC_VAR_INIT(0); - auto reportProgress = - [&]() - { - const size_t completed = processed; - Console::WriteFormat("File %5d of %d, done %3d%%\r", completed, totalCount, completed * 100 / totalCount); - }; + auto reportProgress = [&]() { + const size_t completed = processed; + Console::WriteFormat("File %5d of %d, done %3d%%\r", completed, totalCount, completed * 100 / totalCount); + }; for (size_t rangeStart = 0; rangeStart < totalCount; rangeStart += stepSize) { @@ -237,7 +236,8 @@ private: auto& items = containers.emplace_back(); - jobPool.AddTask(std::bind(&FileIndex::BuildRange, + jobPool.AddTask(std::bind( + &FileIndex::BuildRange, this, language, std::cref(scanResult), @@ -267,7 +267,7 @@ private: return allItems; } - std::tuple> ReadIndexFile(int32_t language, const DirectoryStats &stats) const + std::tuple> ReadIndexFile(int32_t language, const DirectoryStats& stats) const { bool loadedItems = false; std::vector items; @@ -280,15 +280,11 @@ private: // Read header, check if we need to re-scan auto header = fs.ReadValue(); - if (header.HeaderSize == sizeof(FileIndexHeader) && - header.MagicNumber == _magicNumber && - header.VersionA == FILE_INDEX_VERSION && - header.VersionB == _version && - header.LanguageId == language && - header.Stats.TotalFiles == stats.TotalFiles && - header.Stats.TotalFileSize == stats.TotalFileSize && - header.Stats.FileDateModifiedChecksum == stats.FileDateModifiedChecksum && - header.Stats.PathChecksum == stats.PathChecksum) + if (header.HeaderSize == sizeof(FileIndexHeader) && header.MagicNumber == _magicNumber + && header.VersionA == FILE_INDEX_VERSION && header.VersionB == _version && header.LanguageId == language + && header.Stats.TotalFiles == stats.TotalFiles && header.Stats.TotalFileSize == stats.TotalFileSize + && header.Stats.FileDateModifiedChecksum == stats.FileDateModifiedChecksum + && header.Stats.PathChecksum == stats.PathChecksum) { items.reserve(header.NumItems); // Directory is the same, just read the saved items @@ -304,7 +300,7 @@ private: Console::WriteLine("%s out of date", _name.c_str()); } } - catch (const std::exception &e) + catch (const std::exception& e) { Console::Error::WriteLine("Unable to load index: '%s'.", _indexPath.c_str()); Console::Error::WriteLine("%s", e.what()); @@ -313,7 +309,7 @@ private: return std::make_tuple(loadedItems, items); } - void WriteIndexFile(int32_t language, const DirectoryStats &stats, const std::vector &items) const + void WriteIndexFile(int32_t language, const DirectoryStats& stats, const std::vector& items) const { try { @@ -337,17 +333,17 @@ private: Serialise(&fs, item); } } - catch (const std::exception &e) + catch (const std::exception& e) { Console::Error::WriteLine("Unable to save index: '%s'.", _indexPath.c_str()); Console::Error::WriteLine("%s", e.what()); } } - static uint32_t GetPathChecksum(const std::string &path) + static uint32_t GetPathChecksum(const std::string& path) { uint32_t hash = 0xD8430DED; - for (const utf8 * ch = path.c_str(); *ch != '\0'; ch++) + for (const utf8* ch = path.c_str(); *ch != '\0'; ch++) { hash += (*ch); hash += (hash << 10); diff --git a/src/openrct2/core/FileScanner.cpp b/src/openrct2/core/FileScanner.cpp index c1ad7282c1..51961b1b46 100644 --- a/src/openrct2/core/FileScanner.cpp +++ b/src/openrct2/core/FileScanner.cpp @@ -10,28 +10,29 @@ #include "../common.h" #ifdef _WIN32 - #define WIN32_LEAN_AND_MEAN - #include +#define WIN32_LEAN_AND_MEAN +#include #endif #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) - #include - #include - #include - #include +#include +#include +#include +#include #elif defined(_WIN32) - // Windows needs this for widechar <-> utf8 conversion utils - #include "../localisation/Language.h" +// Windows needs this for widechar <-> utf8 conversion utils +#include "../localisation/Language.h" #endif +#include "FileScanner.h" +#include "Memory.hpp" +#include "Path.hpp" +#include "String.hpp" + #include #include #include #include -#include "FileScanner.h" -#include "Memory.hpp" -#include "Path.hpp" -#include "String.hpp" enum class DIRECTORY_CHILD_TYPE { @@ -45,38 +46,38 @@ struct DirectoryChild std::string Name; // Files only - uint64_t Size = 0; + uint64_t Size = 0; uint64_t LastModified = 0; }; -static uint32_t GetPathChecksum(const utf8 * path); -static bool MatchWildcard(const utf8 * fileName, const utf8 * pattern); +static uint32_t GetPathChecksum(const utf8* path); +static bool MatchWildcard(const utf8* fileName, const utf8* pattern); class FileScannerBase : public IFileScanner { private: struct DirectoryState { - std::string Path; + std::string Path; std::vector Listing; - int32_t Index = 0; + int32_t Index = 0; }; // Options - std::string _rootPath; - std::vector _patterns; - bool _recurse; + std::string _rootPath; + std::vector _patterns; + bool _recurse; // State - bool _started = false; - std::stack _directoryStack; + bool _started = false; + std::stack _directoryStack; // Current - FileInfo * _currentFileInfo; - utf8 * _currentPath; + FileInfo* _currentFileInfo; + utf8* _currentPath; public: - FileScannerBase(const std::string &pattern, bool recurse) + FileScannerBase(const std::string& pattern, bool recurse) { _rootPath = Path::GetDirectory(pattern); _recurse = recurse; @@ -94,17 +95,17 @@ public: Memory::Free(_currentFileInfo); } - const FileInfo * GetFileInfo() const override + const FileInfo* GetFileInfo() const override { return _currentFileInfo; } - const utf8 * GetPath() const override + const utf8* GetPath() const override { return _currentPath; } - const utf8 * GetPathRelative() const override + const utf8* GetPathRelative() const override { // +1 to remove the path separator return _currentPath + _rootPath.size() + 1; @@ -127,7 +128,7 @@ public: while (!_directoryStack.empty()) { - DirectoryState * state = &_directoryStack.top(); + DirectoryState* state = &_directoryStack.top(); state->Index++; if (state->Index >= (int32_t)state->Listing.size()) { @@ -135,7 +136,7 @@ public: } else { - const DirectoryChild * child = &state->Listing[state->Index]; + const DirectoryChild* child = &state->Listing[state->Index]; if (child->Type == DIRECTORY_CHILD_TYPE::DC_DIRECTORY) { if (_recurse) @@ -162,10 +163,10 @@ public: return false; } - virtual void GetDirectoryChildren(std::vector &children, const std::string &path) abstract; + virtual void GetDirectoryChildren(std::vector& children, const std::string& path) abstract; private: - void PushState(const std::string &directory) + void PushState(const std::string& directory) { DirectoryState newState; newState.Path = directory; @@ -174,9 +175,9 @@ private: _directoryStack.push(newState); } - bool PatternMatch(const std::string &fileName) + bool PatternMatch(const std::string& fileName) { - for (const auto &pattern : _patterns) + for (const auto& pattern : _patterns) { if (MatchWildcard(fileName.c_str(), pattern.c_str())) { @@ -186,12 +187,12 @@ private: return false; } - static std::vector GetPatterns(const std::string &delimitedPatterns) + static std::vector GetPatterns(const std::string& delimitedPatterns) { std::vector patterns; - const utf8 * start = delimitedPatterns.c_str(); - const utf8 * ch = start; + const utf8* start = delimitedPatterns.c_str(); + const utf8* ch = start; utf8 c; do { @@ -207,8 +208,7 @@ private: start = ch + 1; } ch++; - } - while (c != '\0'); + } while (c != '\0'); patterns.shrink_to_fit(); return patterns; @@ -220,15 +220,15 @@ private: class FileScannerWindows final : public FileScannerBase { public: - FileScannerWindows(const std::string &pattern, bool recurse) + FileScannerWindows(const std::string& pattern, bool recurse) : FileScannerBase(pattern, recurse) { } - void GetDirectoryChildren(std::vector &children, const std::string &path) override + void GetDirectoryChildren(std::vector& children, const std::string& path) override { std::string pattern = path + "\\*"; - wchar_t * wPattern = utf8_to_widechar(pattern.c_str()); + wchar_t* wPattern = utf8_to_widechar(pattern.c_str()); WIN32_FIND_DATAW findData; HANDLE hFile = FindFirstFileW(wPattern, &findData); @@ -236,14 +236,12 @@ public: { do { - if (lstrcmpW(findData.cFileName, L".") != 0 && - lstrcmpW(findData.cFileName, L"..") != 0) + if (lstrcmpW(findData.cFileName, L".") != 0 && lstrcmpW(findData.cFileName, L"..") != 0) { DirectoryChild child = CreateChild(&findData); children.push_back(child); } - } - while (FindNextFileW(hFile, &findData)); + } while (FindNextFileW(hFile, &findData)); FindClose(hFile); } @@ -251,11 +249,11 @@ public: } private: - static DirectoryChild CreateChild(const WIN32_FIND_DATAW * child) + static DirectoryChild CreateChild(const WIN32_FIND_DATAW* child) { DirectoryChild result; - utf8 * name = widechar_to_utf8(child->cFileName); + utf8* name = widechar_to_utf8(child->cFileName); result.Name = std::string(name); Memory::Free(name); @@ -267,7 +265,8 @@ private: { result.Type = DIRECTORY_CHILD_TYPE::DC_FILE; result.Size = ((uint64_t)child->nFileSizeHigh << 32ULL) | (uint64_t)child->nFileSizeLow; - result.LastModified = ((uint64_t)child->ftLastWriteTime.dwHighDateTime << 32ULL) | (uint64_t)child->ftLastWriteTime.dwLowDateTime; + result.LastModified + = ((uint64_t)child->ftLastWriteTime.dwHighDateTime << 32ULL) | (uint64_t)child->ftLastWriteTime.dwLowDateTime; } return result; } @@ -280,22 +279,21 @@ private: class FileScannerUnix final : public FileScannerBase { public: - FileScannerUnix(const std::string &pattern, bool recurse) + FileScannerUnix(const std::string& pattern, bool recurse) : FileScannerBase(pattern, recurse) { } - void GetDirectoryChildren(std::vector &children, const std::string &path) override + void GetDirectoryChildren(std::vector& children, const std::string& path) override { - struct dirent * * namelist; + struct dirent** namelist; int32_t count = scandir(path.c_str(), &namelist, FilterFunc, alphasort); if (count > 0) { for (int32_t i = 0; i < count; i++) { - const struct dirent * node = namelist[i]; - if (!String::Equals(node->d_name, ".") && - !String::Equals(node->d_name, "..")) + const struct dirent* node = namelist[i]; + if (!String::Equals(node->d_name, ".") && !String::Equals(node->d_name, "..")) { DirectoryChild child = CreateChild(path.c_str(), node); children.push_back(child); @@ -307,12 +305,12 @@ public: } private: - static int32_t FilterFunc(const struct dirent * d) + static int32_t FilterFunc(const struct dirent* d) { return 1; } - static DirectoryChild CreateChild(const utf8 * directory, const struct dirent * node) + static DirectoryChild CreateChild(const utf8* directory, const struct dirent* node) { DirectoryChild result; result.Name = std::string(node->d_name); @@ -326,11 +324,13 @@ private: // Get the full path of the file size_t pathSize = String::SizeOf(directory) + 1 + String::SizeOf(node->d_name) + 1; - utf8 * path = Memory::Allocate(pathSize); + utf8* path = Memory::Allocate(pathSize); String::Set(path, pathSize, directory); Path::Append(path, pathSize, node->d_name); - struct stat statInfo{}; + struct stat statInfo + { + }; int32_t statRes = stat(path, &statInfo); if (statRes != -1) { @@ -351,7 +351,7 @@ private: #endif // defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) -IFileScanner * Path::ScanDirectory(const std::string &pattern, bool recurse) +IFileScanner* Path::ScanDirectory(const std::string& pattern, bool recurse) { #ifdef _WIN32 return new FileScannerWindows(pattern, recurse); @@ -360,35 +360,34 @@ IFileScanner * Path::ScanDirectory(const std::string &pattern, bool recurse) #endif } -void Path::QueryDirectory(QueryDirectoryResult * result, const std::string &pattern) +void Path::QueryDirectory(QueryDirectoryResult* result, const std::string& pattern) { - IFileScanner * scanner = Path::ScanDirectory(pattern, true); + IFileScanner* scanner = Path::ScanDirectory(pattern, true); while (scanner->Next()) { - const FileInfo * fileInfo = scanner->GetFileInfo(); - const utf8 * path = scanner->GetPath(); + const FileInfo* fileInfo = scanner->GetFileInfo(); + const utf8* path = scanner->GetPath(); result->TotalFiles++; result->TotalFileSize += fileInfo->Size; - result->FileDateModifiedChecksum ^= - (uint32_t)(fileInfo->LastModified >> 32) ^ - (uint32_t)(fileInfo->LastModified & 0xFFFFFFFF); + result->FileDateModifiedChecksum + ^= (uint32_t)(fileInfo->LastModified >> 32) ^ (uint32_t)(fileInfo->LastModified & 0xFFFFFFFF); result->FileDateModifiedChecksum = ror32(result->FileDateModifiedChecksum, 5); result->PathChecksum += GetPathChecksum(path); } delete scanner; } -std::vector Path::GetDirectories(const std::string &path) +std::vector Path::GetDirectories(const std::string& path) { auto scanner = std::unique_ptr(ScanDirectory(path, false)); - auto baseScanner = static_cast(scanner.get()); + auto baseScanner = static_cast(scanner.get()); std::vector children; baseScanner->GetDirectoryChildren(children, path); std::vector subDirectories; - for (const auto &c : children) + for (const auto& c : children) { if (c.Type == DIRECTORY_CHILD_TYPE::DC_DIRECTORY) { @@ -398,10 +397,10 @@ std::vector Path::GetDirectories(const std::string &path) return subDirectories; } -static uint32_t GetPathChecksum(const utf8 * path) +static uint32_t GetPathChecksum(const utf8* path) { uint32_t hash = 0xD8430DED; - for (const utf8 * ch = path; *ch != '\0'; ch++) + for (const utf8* ch = path; *ch != '\0'; ch++) { hash += (*ch); hash += (hash << 10); @@ -418,41 +417,41 @@ static uint32_t GetPathChecksum(const utf8 * path) * specified. This will verify if a filename does indeed match the pattern we asked for. * @remarks Based on algorithm (http://xoomer.virgilio.it/acantato/dev/wildcard/wildmatch.html) */ -static bool MatchWildcard(const utf8 * fileName, const utf8 * pattern) +static bool MatchWildcard(const utf8* fileName, const utf8* pattern) { while (*fileName != '\0') { - switch (*pattern) { - case '?': - if (*fileName == '.') - { - return false; - } - break; - case '*': - do - { - pattern++; - } - while (*pattern == '*'); - if (*pattern == '\0') - { - return false; - } - while (*fileName != '\0') - { - if (MatchWildcard(fileName++, pattern)) + switch (*pattern) + { + case '?': + if (*fileName == '.') { - return true; + return false; + } + break; + case '*': + do + { + pattern++; + } while (*pattern == '*'); + if (*pattern == '\0') + { + return false; + } + while (*fileName != '\0') + { + if (MatchWildcard(fileName++, pattern)) + { + return true; + } } - } - return false; - default: - if (toupper(*fileName) != toupper(*pattern)) - { return false; - } - break; + default: + if (toupper(*fileName) != toupper(*pattern)) + { + return false; + } + break; } pattern++; fileName++; diff --git a/src/openrct2/core/FileScanner.h b/src/openrct2/core/FileScanner.h index fbacd59bb7..1e7b23ddf9 100644 --- a/src/openrct2/core/FileScanner.h +++ b/src/openrct2/core/FileScanner.h @@ -9,24 +9,25 @@ #pragma once +#include "../common.h" + #include #include -#include "../common.h" struct FileInfo { - const utf8 * Name; - uint64_t Size; - uint64_t LastModified; + const utf8* Name; + uint64_t Size; + uint64_t LastModified; }; interface IFileScanner { virtual ~IFileScanner() = default; - virtual const FileInfo * GetFileInfo() const abstract; - virtual const utf8 * GetPath() const abstract; - virtual const utf8 * GetPathRelative() const abstract; + virtual const FileInfo* GetFileInfo() const abstract; + virtual const utf8* GetPath() const abstract; + virtual const utf8* GetPathRelative() const abstract; virtual void Reset() abstract; virtual bool Next() abstract; @@ -49,14 +50,14 @@ namespace Path * @param recurse Whether to scan sub directories or not. * @returns A new FileScanner, this must be deleted when no longer needed. */ - IFileScanner * ScanDirectory(const std::string &pattern, bool recurse); + IFileScanner* ScanDirectory(const std::string& pattern, bool recurse); /** * Scans a directory and all sub directories * @param result The query result to modify. * @param pattern The path followed by a semi-colon delimited list of wildcard patterns. */ - void QueryDirectory(QueryDirectoryResult * result, const std::string &pattern); + void QueryDirectory(QueryDirectoryResult* result, const std::string& pattern); - std::vector GetDirectories(const std::string &path); + std::vector GetDirectories(const std::string& path); } // namespace Path diff --git a/src/openrct2/core/FileStream.hpp b/src/openrct2/core/FileStream.hpp index 37a0bb63fc..0bc50093dc 100644 --- a/src/openrct2/core/FileStream.hpp +++ b/src/openrct2/core/FileStream.hpp @@ -10,12 +10,11 @@ #pragma once #include "../common.h" +#include "../localisation/Language.h" #include "IStream.hpp" #include "Math.hpp" #include "String.hpp" -#include "../localisation/Language.h" - enum { FILE_MODE_OPEN, @@ -29,45 +28,46 @@ enum class FileStream final : public IStream { private: - FILE * _file = nullptr; - bool _ownsFilePtr = false; - bool _canRead = false; - bool _canWrite = false; - bool _disposed = false; - uint64_t _fileSize = 0; + FILE* _file = nullptr; + bool _ownsFilePtr = false; + bool _canRead = false; + bool _canWrite = false; + bool _disposed = false; + uint64_t _fileSize = 0; public: - FileStream(const std::string &path, int32_t fileMode) : - FileStream(path.c_str(), fileMode) + FileStream(const std::string& path, int32_t fileMode) + : FileStream(path.c_str(), fileMode) { } - FileStream(const utf8 * path, int32_t fileMode) + FileStream(const utf8* path, int32_t fileMode) { - const char * mode; - switch (fileMode) { - case FILE_MODE_OPEN: - mode = "rb"; - _canRead = true; - _canWrite = false; - break; - case FILE_MODE_WRITE: - mode = "w+b"; - _canRead = true; - _canWrite = true; - break; - case FILE_MODE_APPEND: - mode = "a"; - _canRead = false; - _canWrite = true; - break; - default: - throw; + const char* mode; + switch (fileMode) + { + case FILE_MODE_OPEN: + mode = "rb"; + _canRead = true; + _canWrite = false; + break; + case FILE_MODE_WRITE: + mode = "w+b"; + _canRead = true; + _canWrite = true; + break; + case FILE_MODE_APPEND: + mode = "a"; + _canRead = false; + _canWrite = true; + break; + default: + throw; } #ifdef _WIN32 - wchar_t * pathW = utf8_to_widechar(path); - wchar_t * modeW = utf8_to_widechar(mode); + wchar_t* pathW = utf8_to_widechar(path); + wchar_t* modeW = utf8_to_widechar(mode); _file = _wfopen(pathW, modeW); free(pathW); free(modeW); @@ -98,10 +98,19 @@ public: } } - bool CanRead() const override { return _canRead; } - bool CanWrite() const override { return _canWrite; } + bool CanRead() const override + { + return _canRead; + } + bool CanWrite() const override + { + return _canWrite; + } - uint64_t GetLength() const override { return _fileSize; } + uint64_t GetLength() const override + { + return _fileSize; + } uint64_t GetPosition() const override { #if defined(_MSC_VER) @@ -121,45 +130,48 @@ public: void Seek(int64_t offset, int32_t origin) override { #if defined(_MSC_VER) - switch (origin) { - case STREAM_SEEK_BEGIN: - _fseeki64(_file, offset, SEEK_SET); - break; - case STREAM_SEEK_CURRENT: - _fseeki64(_file, offset, SEEK_CUR); - break; - case STREAM_SEEK_END: - _fseeki64(_file, offset, SEEK_END); - break; + switch (origin) + { + case STREAM_SEEK_BEGIN: + _fseeki64(_file, offset, SEEK_SET); + break; + case STREAM_SEEK_CURRENT: + _fseeki64(_file, offset, SEEK_CUR); + break; + case STREAM_SEEK_END: + _fseeki64(_file, offset, SEEK_END); + break; } #elif (defined(__APPLE__) && defined(__MACH__)) || defined(__ANDROID__) || defined(__OpenBSD__) || defined(__FreeBSD__) - switch (origin) { - case STREAM_SEEK_BEGIN: - fseeko(_file, offset, SEEK_SET); - break; - case STREAM_SEEK_CURRENT: - fseeko(_file, offset, SEEK_CUR); - break; - case STREAM_SEEK_END: - fseeko(_file, offset, SEEK_END); - break; + switch (origin) + { + case STREAM_SEEK_BEGIN: + fseeko(_file, offset, SEEK_SET); + break; + case STREAM_SEEK_CURRENT: + fseeko(_file, offset, SEEK_CUR); + break; + case STREAM_SEEK_END: + fseeko(_file, offset, SEEK_END); + break; } #else - switch (origin) { - case STREAM_SEEK_BEGIN: - fseeko64(_file, offset, SEEK_SET); - break; - case STREAM_SEEK_CURRENT: - fseeko64(_file, offset, SEEK_CUR); - break; - case STREAM_SEEK_END: - fseeko64(_file, offset, SEEK_END); - break; - } + switch (origin) + { + case STREAM_SEEK_BEGIN: + fseeko64(_file, offset, SEEK_SET); + break; + case STREAM_SEEK_CURRENT: + fseeko64(_file, offset, SEEK_CUR); + break; + case STREAM_SEEK_END: + fseeko64(_file, offset, SEEK_END); + break; + } #endif } - void Read(void * buffer, uint64_t length) override + void Read(void* buffer, uint64_t length) override { uint64_t remainingBytes = GetLength() - GetPosition(); if (length <= remainingBytes) @@ -172,7 +184,7 @@ public: throw IOException("Attempted to read past end of file."); } - void Write(const void * buffer, uint64_t length) override + void Write(const void* buffer, uint64_t length) override { if (fwrite(buffer, (size_t)length, 1, _file) != 1) { @@ -183,7 +195,7 @@ public: _fileSize = std::max(_fileSize, position); } - uint64_t TryRead(void * buffer, uint64_t length) override + uint64_t TryRead(void* buffer, uint64_t length) override { size_t readBytes = fread(buffer, 1, (size_t)length, _file); return readBytes; diff --git a/src/openrct2/core/Guard.cpp b/src/openrct2/core/Guard.cpp index e047d91d9a..65b10f25dc 100644 --- a/src/openrct2/core/Guard.cpp +++ b/src/openrct2/core/Guard.cpp @@ -34,7 +34,7 @@ void openrct2_assert_fwd(bool expression, const char* message, ...) namespace Guard { - constexpr const utf8 * ASSERTION_MESSAGE = "An assertion failed, please report this to the OpenRCT2 developers."; + constexpr const utf8* ASSERTION_MESSAGE = "An assertion failed, please report this to the OpenRCT2 developers."; // The default behaviour when an assertion is raised. static ASSERT_BEHAVIOUR _assertBehaviour = @@ -46,7 +46,7 @@ namespace Guard ; #ifdef _WIN32 - static void GetAssertMessage(char * buffer, size_t bufferSize, const char * formattedMessage); + static void GetAssertMessage(char* buffer, size_t bufferSize, const char* formattedMessage); static void ForceCrash(); #endif @@ -60,7 +60,7 @@ namespace Guard _assertBehaviour = behaviour; } - void Assert(bool expression, const char * message, ...) + void Assert(bool expression, const char* message, ...) { va_list args; va_start(args, message); @@ -68,15 +68,16 @@ namespace Guard va_end(args); } - void Assert_VA(bool expression, const char * message, va_list args) + void Assert_VA(bool expression, const char* message, va_list args) { - if (expression) return; + if (expression) + return; Console::Error::WriteLine(ASSERTION_MESSAGE); Console::Error::WriteLine("Version: %s", gVersionInfoFull); // This is never freed, but acceptable considering we are about to crash out - utf8 * formattedMessage = nullptr; + utf8* formattedMessage = nullptr; if (message != nullptr) { formattedMessage = String::Format_VA(message, args); @@ -87,31 +88,32 @@ namespace Guard Debug::Break(); #endif - switch (_assertBehaviour) { - case ASSERT_BEHAVIOUR::ABORT: - abort(); - default: - case ASSERT_BEHAVIOUR::CASSERT: - assert(false); - break; -#ifdef _WIN32 - case ASSERT_BEHAVIOUR::MESSAGE_BOX: + switch (_assertBehaviour) { - // Show message box if we are not building for testing - char buffer[512]; - GetAssertMessage(buffer, sizeof(buffer), formattedMessage); - int32_t result = MessageBoxA(nullptr, buffer, OPENRCT2_NAME, MB_ABORTRETRYIGNORE | MB_ICONEXCLAMATION); - if (result == IDABORT) + case ASSERT_BEHAVIOUR::ABORT: + abort(); + default: + case ASSERT_BEHAVIOUR::CASSERT: + assert(false); + break; +#ifdef _WIN32 + case ASSERT_BEHAVIOUR::MESSAGE_BOX: { - ForceCrash(); + // Show message box if we are not building for testing + char buffer[512]; + GetAssertMessage(buffer, sizeof(buffer), formattedMessage); + int32_t result = MessageBoxA(nullptr, buffer, OPENRCT2_NAME, MB_ABORTRETRYIGNORE | MB_ICONEXCLAMATION); + if (result == IDABORT) + { + ForceCrash(); + } + break; } - break; - } #endif } } - void Fail(const char * message, ...) + void Fail(const char* message, ...) { va_list args; va_start(args, message); @@ -119,13 +121,13 @@ namespace Guard va_end(args); } - void Fail_VA(const char * message, va_list args) + void Fail_VA(const char* message, va_list args) { Assert_VA(false, message, args); } #ifdef _WIN32 - static void GetAssertMessage(char * buffer, size_t bufferSize, const char * formattedMessage) + static void GetAssertMessage(char* buffer, size_t bufferSize, const char* formattedMessage) { String::Set(buffer, bufferSize, ASSERTION_MESSAGE); String::Append(buffer, bufferSize, "\r\n\r\n"); diff --git a/src/openrct2/core/Guard.hpp b/src/openrct2/core/Guard.hpp index b5656abeae..83edf426d1 100644 --- a/src/openrct2/core/Guard.hpp +++ b/src/openrct2/core/Guard.hpp @@ -13,9 +13,13 @@ #include #include -void openrct2_assert_fwd(bool expression, const char * message, ...); +void openrct2_assert_fwd(bool expression, const char* message, ...); -#define openrct2_assert(expr, msg, ...) if(!(expr)) { openrct2_assert_fwd((expr), msg, ##__VA_ARGS__); } +#define openrct2_assert(expr, msg, ...) \ + if (!(expr)) \ + { \ + openrct2_assert_fwd((expr), msg, ##__VA_ARGS__); \ + } enum class ASSERT_BEHAVIOUR { @@ -32,13 +36,12 @@ namespace Guard ASSERT_BEHAVIOUR GetAssertBehaviour(); void SetAssertBehaviour(ASSERT_BEHAVIOUR behaviour); - void Assert(bool expression, const char * message = nullptr, ...); - void Assert_VA(bool expression, const char * message, va_list args); - void Fail(const char * message = nullptr, ...); - void Fail_VA(const char * message, va_list args); + void Assert(bool expression, const char* message = nullptr, ...); + void Assert_VA(bool expression, const char* message, va_list args); + void Fail(const char* message = nullptr, ...); + void Fail_VA(const char* message, va_list args); - template - static void ArgumentNotNull(T * argument, const char * message = nullptr, ...) + template static void ArgumentNotNull(T* argument, const char* message = nullptr, ...) { va_list args; va_start(args, message); @@ -46,8 +49,7 @@ namespace Guard va_end(args); } - template - static void ArgumentNotNull(const std::shared_ptr& argument, const char * message = nullptr, ...) + template static void ArgumentNotNull(const std::shared_ptr& argument, const char* message = nullptr, ...) { va_list args; va_start(args, message); @@ -55,8 +57,7 @@ namespace Guard va_end(args); } - template - static void ArgumentInRange(T argument, T min, T max, const char * message = nullptr, ...) + template static void ArgumentInRange(T argument, T min, T max, const char* message = nullptr, ...) { va_list args; va_start(args, message); diff --git a/src/openrct2/core/IStream.cpp b/src/openrct2/core/IStream.cpp index 23ae81c89e..60a4af6d94 100644 --- a/src/openrct2/core/IStream.cpp +++ b/src/openrct2/core/IStream.cpp @@ -7,12 +7,14 @@ * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ -#include #include "IStream.hpp" + #include "Memory.hpp" #include "String.hpp" -utf8 * IStream::ReadString() +#include + +utf8* IStream::ReadString() { std::vector result; @@ -23,7 +25,7 @@ utf8 * IStream::ReadString() } result.push_back(0); - utf8 * resultString = Memory::AllocateArray(result.size()); + utf8* resultString = Memory::AllocateArray(result.size()); std::copy(result.begin(), result.end(), resultString); return resultString; } @@ -39,7 +41,7 @@ std::string IStream::ReadStdString() return result; } -void IStream::WriteString(const utf8 * str) +void IStream::WriteString(const utf8* str) { if (str == nullptr) { @@ -52,7 +54,7 @@ void IStream::WriteString(const utf8 * str) } } -void IStream::WriteString(const std::string &str) +void IStream::WriteString(const std::string& str) { WriteString(str.c_str()); } diff --git a/src/openrct2/core/IStream.hpp b/src/openrct2/core/IStream.hpp index ec30493e4c..3ff0ea1e86 100644 --- a/src/openrct2/core/IStream.hpp +++ b/src/openrct2/core/IStream.hpp @@ -9,14 +9,16 @@ #pragma once +#include "../common.h" +#include "Memory.hpp" + #include #include #include #include -#include "../common.h" -#include "Memory.hpp" -enum { +enum +{ STREAM_SEEK_BEGIN, STREAM_SEEK_CURRENT, STREAM_SEEK_END @@ -30,20 +32,22 @@ interface IStream /////////////////////////////////////////////////////////////////////////// // Interface methods /////////////////////////////////////////////////////////////////////////// - virtual ~IStream() { } + virtual ~IStream() + { + } - virtual bool CanRead() const abstract; - virtual bool CanWrite() const abstract; + virtual bool CanRead() const abstract; + virtual bool CanWrite() const abstract; - virtual uint64_t GetLength() const abstract; - virtual uint64_t GetPosition() const abstract; - virtual void SetPosition(uint64_t position) abstract; - virtual void Seek(int64_t offset, int32_t origin) abstract; + virtual uint64_t GetLength() const abstract; + virtual uint64_t GetPosition() const abstract; + virtual void SetPosition(uint64_t position) abstract; + virtual void Seek(int64_t offset, int32_t origin) abstract; - virtual void Read(void * buffer, uint64_t length) abstract; - virtual void Write(const void * buffer, uint64_t length) abstract; + virtual void Read(void* buffer, uint64_t length) abstract; + virtual void Write(const void* buffer, uint64_t length) abstract; - virtual uint64_t TryRead(void * buffer, uint64_t length) abstract; + virtual uint64_t TryRead(void* buffer, uint64_t length) abstract; /////////////////////////////////////////////////////////////////////////// // Helper methods @@ -52,8 +56,7 @@ interface IStream /** * Reads the size of the given type from the stream directly into the given address. */ - template - void Read(T * value) + template void Read(T * value) { Read(value, sizeof(T)); } @@ -61,8 +64,7 @@ interface IStream /** * Writes the size of the given type to the stream directly from the given address. */ - template - void Write(const T * value) + template void Write(const T* value) { Write(value, sizeof(T)); } @@ -70,8 +72,7 @@ interface IStream /** * Reads the given type from the stream. Use this only for small types (e.g. int8_t, int64_t, double) */ - template - T ReadValue() + template T ReadValue() { T buffer; Read(&buffer); @@ -81,40 +82,39 @@ interface IStream /** * Writes the given type to the stream. Use this only for small types (e.g. int8_t, int64_t, double) */ - template - void WriteValue(const T value) + template void WriteValue(const T value) { Write(&value); } - template - T * ReadArray(size_t count) + template T* ReadArray(size_t count) { - T * buffer = Memory::AllocateArray(count); + T* buffer = Memory::AllocateArray(count); Read(buffer, sizeof(T) * count); return buffer; } - template - void WriteArray(T * buffer, size_t count) + template void WriteArray(T * buffer, size_t count) { Write(buffer, sizeof(T) * count); } - utf8 * ReadString(); + utf8* ReadString(); std::string ReadStdString(); - void WriteString(const utf8 * str); - void WriteString(const std::string &string); + void WriteString(const utf8* str); + void WriteString(const std::string& string); }; class IOException : public std::runtime_error { public: - explicit IOException(const std::string &message) : std::runtime_error(message) { } + explicit IOException(const std::string& message) + : std::runtime_error(message) + { + } }; -template -class ivstream : public std::istream +template class ivstream : public std::istream { private: class vector_streambuf : public std::basic_streambuf> @@ -122,7 +122,7 @@ private: public: explicit vector_streambuf(const std::vector& vec) { - this->setg((char *)vec.data(), (char *)vec.data(), (char *)(vec.data() + vec.size())); + this->setg((char*)vec.data(), (char*)vec.data(), (char*)(vec.data() + vec.size())); } }; @@ -130,8 +130,8 @@ private: public: ivstream(const std::vector& vec) - : std::istream(&_streambuf), - _streambuf(vec) + : std::istream(&_streambuf) + , _streambuf(vec) { } }; diff --git a/src/openrct2/core/Imaging.cpp b/src/openrct2/core/Imaging.cpp index 06504da9ab..322e9a44aa 100644 --- a/src/openrct2/core/Imaging.cpp +++ b/src/openrct2/core/Imaging.cpp @@ -9,17 +9,19 @@ #pragma warning(disable : 4611) // interaction between '_setjmp' and C++ object destruction is non-portable -#include -#include -#include -#include -#include -#include "IStream.hpp" -#include "Guard.hpp" #include "Imaging.h" + +#include "../drawing/Drawing.h" +#include "Guard.hpp" +#include "IStream.hpp" #include "Memory.hpp" #include "String.hpp" -#include "../drawing/Drawing.h" + +#include +#include +#include +#include +#include namespace Imaging { @@ -29,28 +31,28 @@ namespace Imaging static void PngReadData(png_structp png_ptr, png_bytep data, png_size_t length) { - auto istream = static_cast(png_get_io_ptr(png_ptr)); - istream->read((char *)data, length); + auto istream = static_cast(png_get_io_ptr(png_ptr)); + istream->read((char*)data, length); } static void PngWriteData(png_structp png_ptr, png_bytep data, png_size_t length) { - auto ostream = static_cast(png_get_io_ptr(png_ptr)); - ostream->write((const char *)data, length); + auto ostream = static_cast(png_get_io_ptr(png_ptr)); + ostream->write((const char*)data, length); } static void PngFlush(png_structp png_ptr) { - auto ostream = static_cast(png_get_io_ptr(png_ptr)); + auto ostream = static_cast(png_get_io_ptr(png_ptr)); ostream->flush(); } - static void PngWarning(png_structp, const char * b) + static void PngWarning(png_structp, const char* b) { log_warning(b); } - static void PngError(png_structp, const char * b) + static void PngError(png_structp, const char* b) { log_error(b); } @@ -152,7 +154,7 @@ namespace Imaging img.Stride = pngWidth * (expandTo32 ? 4 : 1); return img; } - catch (const std::exception &) + catch (const std::exception&) { png_destroy_read_struct(&png_ptr, &info_ptr, nullptr); throw; @@ -232,7 +234,7 @@ namespace Imaging auto pixels = image.Pixels.data(); for (uint32_t y = 0; y < image.Height; y++) { - png_write_row(png_ptr, (png_byte *)pixels); + png_write_row(png_ptr, (png_byte*)pixels); pixels += image.Stride; } @@ -348,4 +350,4 @@ namespace Imaging throw std::runtime_error(EXCEPTION_IMAGE_FORMAT_UNKNOWN); } } -} +} // namespace Imaging diff --git a/src/openrct2/core/Imaging.h b/src/openrct2/core/Imaging.h index 982b7f7ff2..3619281de9 100644 --- a/src/openrct2/core/Imaging.h +++ b/src/openrct2/core/Imaging.h @@ -9,13 +9,14 @@ #pragma once +#include "../common.h" +#include "../drawing/Drawing.h" + #include #include #include #include #include -#include "../common.h" -#include "../drawing/Drawing.h" struct rct_drawpixelinfo; struct rct_palette; @@ -31,10 +32,10 @@ struct PaletteBGRA enum class IMAGE_FORMAT { UNKNOWN, - AUTOMATIC, // Automatically detect from file extension + AUTOMATIC, // Automatically detect from file extension BITMAP, PNG, - PNG_32, // Force load to 32bpp buffer + PNG_32, // Force load to 32bpp buffer }; struct Image @@ -60,4 +61,4 @@ namespace Imaging void WriteToFile(const std::string_view& path, const Image& image, IMAGE_FORMAT format = IMAGE_FORMAT::AUTOMATIC); void SetReader(IMAGE_FORMAT format, ImageReaderFunc impl); -} +} // namespace Imaging diff --git a/src/openrct2/core/JobPool.hpp b/src/openrct2/core/JobPool.hpp index 27e44ac8cc..5b8b39ed25 100644 --- a/src/openrct2/core/JobPool.hpp +++ b/src/openrct2/core/JobPool.hpp @@ -27,8 +27,8 @@ private: const std::function CompletionFn; TaskData(std::function workFn, std::function completionFn) - : WorkFn(workFn), - CompletionFn(completionFn) + : WorkFn(workFn) + , CompletionFn(completionFn) { } }; @@ -86,11 +86,7 @@ public: while (true) { // Wait for the queue to become empty or having completed tasks. - _condComplete.wait(lock, [this]() - { - return (_pending.empty() && _processing == 0) || - !_completed.empty(); - }); + _condComplete.wait(lock, [this]() { return (_pending.empty() && _processing == 0) || !_completed.empty(); }); // Dispatch all completion callbacks if there are any. while (!_completed.empty()) @@ -118,9 +114,7 @@ public: } // If everything is empty and no more work has to be done we can stop waiting. - if (_completed.empty() && - _pending.empty() && - _processing == 0) + if (_completed.empty() && _pending.empty() && _processing == 0) { break; } @@ -139,11 +133,7 @@ private: do { // Wait for work or cancelation. - _condPending.wait(lock, - [this]() - { - return _shouldStop || !_pending.empty(); - }); + _condPending.wait(lock, [this]() { return _shouldStop || !_pending.empty(); }); if (!_pending.empty()) { @@ -163,7 +153,6 @@ private: _processing--; _condComplete.notify_one(); } - } - while(!_shouldStop); + } while (!_shouldStop); } }; diff --git a/src/openrct2/core/Json.cpp b/src/openrct2/core/Json.cpp index 5632366f2d..786f8990d1 100644 --- a/src/openrct2/core/Json.cpp +++ b/src/openrct2/core/Json.cpp @@ -7,16 +7,17 @@ * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ -#include "FileStream.hpp" #include "Json.hpp" + +#include "FileStream.hpp" #include "Memory.hpp" #include "String.hpp" namespace Json { - json_t * ReadFromFile(const utf8 * path, size_t maxSize) + json_t* ReadFromFile(const utf8* path, size_t maxSize) { - json_t * json = nullptr; + json_t* json = nullptr; auto fs = FileStream(path, FILE_MODE_OPEN); size_t fileLength = (size_t)fs.GetLength(); @@ -25,7 +26,7 @@ namespace Json throw IOException("Json file too large."); } - utf8 * fileData = Memory::Allocate(fileLength + 1); + utf8* fileData = Memory::Allocate(fileLength + 1); fs.Read(fileData, fileLength); fileData[fileLength] = '\0'; @@ -41,10 +42,10 @@ namespace Json return json; } - void WriteToFile(const utf8 * path, const json_t * json, size_t flags) + void WriteToFile(const utf8* path, const json_t* json, size_t flags) { // Serialise JSON - const char * jsonOutput = json_dumps(json, flags); + const char* jsonOutput = json_dumps(json, flags); // Write to file auto fs = FileStream(path, FILE_MODE_WRITE); @@ -52,9 +53,9 @@ namespace Json fs.Write(jsonOutput, jsonOutputSize); } - json_t * FromString(const std::string & raw) + json_t* FromString(const std::string& raw) { - json_t * root; + json_t* root; json_error_t error; root = json_loads(raw.c_str(), 0, &error); if (root == nullptr) diff --git a/src/openrct2/core/Json.hpp b/src/openrct2/core/Json.hpp index af44ddf8d3..d8be8d5fbb 100644 --- a/src/openrct2/core/Json.hpp +++ b/src/openrct2/core/Json.hpp @@ -9,22 +9,22 @@ #pragma once +#include "../common.h" + +#include #include #include -#include - -#include "../common.h" namespace Json { // Don't try to load JSON files that exceed 64 MiB constexpr uint64_t MAX_JSON_SIZE = 64 * 1024 * 1024; - json_t * ReadFromFile(const utf8 * path, size_t maxSize = MAX_JSON_SIZE); - void WriteToFile(const utf8 * path, const json_t * json, size_t flags = 0); + json_t* ReadFromFile(const utf8* path, size_t maxSize = MAX_JSON_SIZE); + void WriteToFile(const utf8* path, const json_t* json, size_t flags = 0); - json_t * FromString(const std::string & raw); -} + json_t* FromString(const std::string& raw); +} // namespace Json class JsonException final : public std::runtime_error { @@ -32,9 +32,13 @@ private: json_error_t _jsonError = {}; public: - explicit JsonException(const std::string &message) : std::runtime_error(message) { } + explicit JsonException(const std::string& message) + : std::runtime_error(message) + { + } - explicit JsonException(const json_error_t * jsonError) : JsonException(std::string(jsonError->text)) + explicit JsonException(const json_error_t* jsonError) + : JsonException(std::string(jsonError->text)) { _jsonError = *jsonError; } diff --git a/src/openrct2/core/Math.hpp b/src/openrct2/core/Math.hpp index 52eb72daf3..4c81bb3b3a 100644 --- a/src/openrct2/core/Math.hpp +++ b/src/openrct2/core/Math.hpp @@ -16,17 +16,17 @@ */ namespace Math { - template - static T Clamp(T low, T x, T high) + template static T Clamp(T low, T x, T high) { return (std::min)((std::max)(low, x), high); } - template - static T Sign(T x) + template static T Sign(T x) { - if (x < 0) return -1; - if (x > 0) return 1; + if (x < 0) + return -1; + if (x > 0) + return 1; return 0; } } // namespace Math diff --git a/src/openrct2/core/Memory.hpp b/src/openrct2/core/Memory.hpp index 946f057ae5..715fab7b46 100644 --- a/src/openrct2/core/Memory.hpp +++ b/src/openrct2/core/Memory.hpp @@ -9,43 +9,40 @@ #pragma once +#include "../common.h" +#include "Guard.hpp" + #include #include #include -#include "../common.h" -#include "Guard.hpp" /** * Utility methods for memory management. Typically helpers and wrappers around the C standard library. */ namespace Memory { - template - static T * Allocate() + template static T* Allocate() { T* result = (T*)malloc(sizeof(T)); Guard::ArgumentNotNull(result, "Failed to allocate %u bytes for %s", sizeof(T), typeid(T).name()); return result; } - template - static T * Allocate(size_t size) + template static T* Allocate(size_t size) { T* result = (T*)malloc(size); Guard::ArgumentNotNull(result, "Failed to allocate %u bytes for %s", size, typeid(T).name()); return result; } - template - static T * AllocateArray(size_t count) + template static T* AllocateArray(size_t count) { T* result = (T*)malloc(count * sizeof(T)); Guard::ArgumentNotNull(result, "Failed to allocate array of %u * %s (%u bytes)", count, typeid(T).name(), sizeof(T)); return result; } - template - static T * Reallocate(T * ptr, size_t size) + template static T* Reallocate(T* ptr, size_t size) { T* result; if (ptr == nullptr) @@ -60,8 +57,7 @@ namespace Memory return result; } - template - static T * ReallocateArray(T * ptr, size_t count) + template static T* ReallocateArray(T* ptr, size_t count) { T* result; if (ptr == nullptr) @@ -72,18 +68,17 @@ namespace Memory { result = (T*)realloc((void*)ptr, count * sizeof(T)); } - Guard::ArgumentNotNull(result, "Failed to reallocate array at %x (%s) to have %u entries", ptr, typeid(T).name(), count); + Guard::ArgumentNotNull( + result, "Failed to reallocate array at %x (%s) to have %u entries", ptr, typeid(T).name(), count); return result; } - template - static void Free(T * ptr) + template static void Free(T* ptr) { free((void*)ptr); } - template - static void FreeArray(T * ptr, size_t count) + template static void FreeArray(T* ptr, size_t count) { for (size_t i = 0; i < count; i++) { diff --git a/src/openrct2/core/MemoryStream.cpp b/src/openrct2/core/MemoryStream.cpp index 66228ecace..346264d7b2 100644 --- a/src/openrct2/core/MemoryStream.cpp +++ b/src/openrct2/core/MemoryStream.cpp @@ -7,13 +7,15 @@ * OpenRCT2 is licensed under the GNU General Public License version 3. *****************************************************************************/ -#include -#include -#include "Math.hpp" -#include "Memory.hpp" #include "MemoryStream.h" -MemoryStream::MemoryStream(const MemoryStream ©) +#include "Math.hpp" +#include "Memory.hpp" + +#include +#include + +MemoryStream::MemoryStream(const MemoryStream& copy) { _access = copy._access; _dataCapacity = copy._dataCapacity; @@ -34,7 +36,7 @@ MemoryStream::MemoryStream(size_t capacity) _position = _data; } -MemoryStream::MemoryStream(void * data, size_t dataSize, uint8_t access) +MemoryStream::MemoryStream(void* data, size_t dataSize, uint8_t access) { _access = access; _dataCapacity = dataSize; @@ -43,8 +45,8 @@ MemoryStream::MemoryStream(void * data, size_t dataSize, uint8_t access) _position = _data; } -MemoryStream::MemoryStream(const void * data, size_t dataSize) - : MemoryStream((void *)data, dataSize, MEMORY_ACCESS::READ) +MemoryStream::MemoryStream(const void* data, size_t dataSize) + : MemoryStream((void*)data, dataSize, MEMORY_ACCESS::READ) { } @@ -59,19 +61,19 @@ MemoryStream::~MemoryStream() _data = nullptr; } -const void * MemoryStream::GetData() const +const void* MemoryStream::GetData() const { return _data; } -void * MemoryStream::GetDataCopy() const +void* MemoryStream::GetDataCopy() const { auto result = Memory::Allocate(_dataSize); std::memcpy(result, _data, _dataSize); return result; } -void * MemoryStream::TakeData() +void* MemoryStream::TakeData() { _access &= ~MEMORY_ACCESS::OWNER; return _data; @@ -105,17 +107,18 @@ void MemoryStream::SetPosition(uint64_t position) void MemoryStream::Seek(int64_t offset, int32_t origin) { uint64_t newPosition; - switch (origin) { - default: - case STREAM_SEEK_BEGIN: - newPosition = offset; - break; - case STREAM_SEEK_CURRENT: - newPosition = GetPosition() + offset; - break; - case STREAM_SEEK_END: - newPosition = _dataSize + offset; - break; + switch (origin) + { + default: + case STREAM_SEEK_BEGIN: + newPosition = offset; + break; + case STREAM_SEEK_CURRENT: + newPosition = GetPosition() + offset; + break; + case STREAM_SEEK_END: + newPosition = _dataSize + offset; + break; } if (newPosition > _dataSize) @@ -125,7 +128,7 @@ void MemoryStream::Seek(int64_t offset, int32_t origin) _position = (void*)((uintptr_t)_data + (uintptr_t)newPosition); } -void MemoryStream::Read(void * buffer, uint64_t length) +void MemoryStream::Read(void* buffer, uint64_t length) { uint64_t position = GetPosition(); if (position + length > _dataSize) @@ -133,11 +136,11 @@ void MemoryStream::Read(void * buffer, uint64_t length) throw IOException("Attempted to read past end of stream."); } - std::copy_n((const uint8_t *)_position, length, (uint8_t *)buffer); + std::copy_n((const uint8_t*)_position, length, (uint8_t*)buffer); _position = (void*)((uintptr_t)_position + length); } -uint64_t MemoryStream::TryRead(void * buffer, uint64_t length) +uint64_t MemoryStream::TryRead(void* buffer, uint64_t length) { uint64_t remainingBytes = GetLength() - GetPosition(); uint64_t bytesToRead = std::min(length, remainingBytes); @@ -145,7 +148,7 @@ uint64_t MemoryStream::TryRead(void * buffer, uint64_t length) return bytesToRead; } -void MemoryStream::Write(const void * buffer, uint64_t length) +void MemoryStream::Write(const void* buffer, uint64_t length) { uint64_t position = GetPosition(); uint64_t nextPosition = position + length; @@ -161,7 +164,7 @@ void MemoryStream::Write(const void * buffer, uint64_t length) } } - std::copy_n((const uint8_t *)buffer, length, (uint8_t *)_position); + std::copy_n((const uint8_t*)buffer, length, (uint8_t*)_position); _position = (void*)((uintptr_t)_position + length); _dataSize = std::max(_dataSize, (size_t)nextPosition); } @@ -179,6 +182,6 @@ void MemoryStream::EnsureCapacity(size_t capacity) uint64_t position = GetPosition(); _dataCapacity = newCapacity; _data = Memory::Reallocate(_data, _dataCapacity); - _position = (void *)((uintptr_t)_data + (uintptr_t)position); + _position = (void*)((uintptr_t)_data + (uintptr_t)position); } } diff --git a/src/openrct2/core/MemoryStream.h b/src/openrct2/core/MemoryStream.h index f4405d2124..57dfc0988e 100644 --- a/src/openrct2/core/MemoryStream.h +++ b/src/openrct2/core/MemoryStream.h @@ -14,10 +14,10 @@ namespace MEMORY_ACCESS { - constexpr uint8_t READ = 1 << 0; - constexpr uint8_t WRITE = 1 << 1; - constexpr uint8_t OWNER = 1 << 2; -}; + constexpr uint8_t READ = 1 << 0; + constexpr uint8_t WRITE = 1 << 1; + constexpr uint8_t OWNER = 1 << 2; +}; // namespace MEMORY_ACCESS /** * A stream for reading and writing to a buffer in memory. By default this buffer can grow. @@ -25,39 +25,39 @@ namespace MEMORY_ACCESS class MemoryStream final : public IStream { private: - uint8_t _access = MEMORY_ACCESS::READ | MEMORY_ACCESS::WRITE | MEMORY_ACCESS::OWNER; + uint8_t _access = MEMORY_ACCESS::READ | MEMORY_ACCESS::WRITE | MEMORY_ACCESS::OWNER; size_t _dataCapacity = 0; - size_t _dataSize = 0; - void * _data = nullptr; - void * _position = nullptr; + size_t _dataSize = 0; + void* _data = nullptr; + void* _position = nullptr; public: MemoryStream() = default; - MemoryStream(const MemoryStream & copy); + MemoryStream(const MemoryStream& copy); explicit MemoryStream(size_t capacity); - MemoryStream(void * data, size_t dataSize, uint8_t access = MEMORY_ACCESS::READ); - MemoryStream(const void * data, size_t dataSize); + MemoryStream(void* data, size_t dataSize, uint8_t access = MEMORY_ACCESS::READ); + MemoryStream(const void* data, size_t dataSize); virtual ~MemoryStream(); - const void * GetData() const; - void * GetDataCopy() const; - void * TakeData(); + const void* GetData() const; + void* GetDataCopy() const; + void* TakeData(); /////////////////////////////////////////////////////////////////////////// // ISteam methods /////////////////////////////////////////////////////////////////////////// - bool CanRead() const override; - bool CanWrite() const override; + bool CanRead() const override; + bool CanWrite() const override; - uint64_t GetLength() const override; - uint64_t GetPosition() const override; - void SetPosition(uint64_t position) override; - void Seek(int64_t offset, int32_t origin) override; + uint64_t GetLength() const override; + uint64_t GetPosition() const override; + void SetPosition(uint64_t position) override; + void Seek(int64_t offset, int32_t origin) override; - void Read(void * buffer, uint64_t length) override; - void Write(const void * buffer, uint64_t length) override; + void Read(void* buffer, uint64_t length) override; + void Write(const void* buffer, uint64_t length) override; - uint64_t TryRead(void * buffer, uint64_t length) override; + uint64_t TryRead(void* buffer, uint64_t length) override; private: void EnsureCapacity(size_t capacity); diff --git a/src/openrct2/core/Nullable.hpp b/src/openrct2/core/Nullable.hpp index d1cb7c4667..2f94ec1fe8 100644 --- a/src/openrct2/core/Nullable.hpp +++ b/src/openrct2/core/Nullable.hpp @@ -10,10 +10,10 @@ #pragma once #include "../common.h" + #include -template -struct Nullable +template struct Nullable { public: Nullable() @@ -28,7 +28,7 @@ public: _hasValue = false; } - Nullable(const T &value) + Nullable(const T& value) { _value = value; _hasValue = true; @@ -50,6 +50,6 @@ public: } private: - T _value; - bool _hasValue; + T _value; + bool _hasValue; }; diff --git a/src/openrct2/core/Path.cpp b/src/openrct2/core/Path.cpp index af63ebd360..307bd4f5fa 100644 --- a/src/openrct2/core/Path.cpp +++ b/src/openrct2/core/Path.cpp @@ -9,28 +9,27 @@ #include #ifndef _WIN32 - #include +#include #endif +#include "../localisation/Language.h" #include "../platform/platform.h" #include "../util/Util.h" -#include "../localisation/Language.h" - #include "File.h" #include "Math.hpp" #include "Memory.hpp" #include "Path.hpp" -#include "Util.hpp" #include "String.hpp" +#include "Util.hpp" namespace Path { - utf8 * Append(utf8 * buffer, size_t bufferSize, const utf8 * src) + utf8* Append(utf8* buffer, size_t bufferSize, const utf8* src) { return safe_strcat_path(buffer, src, bufferSize); } - std::string Combine(const std::string &a, const std::string &b) + std::string Combine(const std::string& a, const std::string& b) { utf8 buffer[MAX_PATH]; String::Set(buffer, sizeof(buffer), a.c_str()); @@ -38,7 +37,7 @@ namespace Path return std::string(buffer); } - std::string GetDirectory(const std::string &path) + std::string GetDirectory(const std::string& path) { const utf8* directory = GetDirectory(path.c_str()); std::string result(directory); @@ -46,22 +45,19 @@ namespace Path return result; } - utf8 * GetDirectory(const utf8 * path) + utf8* GetDirectory(const utf8* path) { size_t maxSize = String::SizeOf(path) + 1; - utf8 * result = Memory::Allocate(maxSize); + utf8* result = Memory::Allocate(maxSize); GetDirectory(result, maxSize, path); size_t reducedSize = String::SizeOf(path) + 1; result = Memory::Reallocate(result, reducedSize); return result; } - utf8 * GetDirectory(utf8 * buffer, size_t bufferSize, const utf8 * path) + utf8* GetDirectory(utf8* buffer, size_t bufferSize, const utf8* path) { - auto lastPathSepIndex = std::max( - String::LastIndexOf(path, *PATH_SEPARATOR), - String::LastIndexOf(path, '/') - ); + auto lastPathSepIndex = std::max(String::LastIndexOf(path, *PATH_SEPARATOR), String::LastIndexOf(path, '/')); if (lastPathSepIndex < 0) { return String::Set(buffer, bufferSize, String::Empty); @@ -73,25 +69,25 @@ namespace Path return buffer; } - void CreateDirectory(const std::string &path) + void CreateDirectory(const std::string& path) { platform_ensure_directory_exists(path.c_str()); } - bool DirectoryExists(const std::string &path) + bool DirectoryExists(const std::string& path) { return platform_directory_exists(path.c_str()); } - std::string GetFileName(const std::string &path) + std::string GetFileName(const std::string& path) { return GetFileName(path.c_str()); } - const utf8 * GetFileName(const utf8 * path) + const utf8* GetFileName(const utf8* path) { - const utf8 * lastPathSeparator = nullptr; - for (const utf8 * ch = path; *ch != '\0'; ch++) + const utf8* lastPathSeparator = nullptr; + for (const utf8* ch = path; *ch != '\0'; ch++) { if (*ch == *PATH_SEPARATOR || *ch == '/') { @@ -99,35 +95,33 @@ namespace Path } } - return lastPathSeparator == nullptr ? - path : - lastPathSeparator + 1; + return lastPathSeparator == nullptr ? path : lastPathSeparator + 1; } - std::string GetFileNameWithoutExtension(const std::string &path) + std::string GetFileNameWithoutExtension(const std::string& path) { - utf8 * cstr = GetFileNameWithoutExtension(path.c_str()); + utf8* cstr = GetFileNameWithoutExtension(path.c_str()); std::string result = String::ToStd(cstr); Memory::Free(cstr); return result; } - utf8 * GetFileNameWithoutExtension(const utf8 * path) + utf8* GetFileNameWithoutExtension(const utf8* path) { size_t maxSize = String::SizeOf(path) + 1; - utf8 * result = Memory::Allocate(maxSize); + utf8* result = Memory::Allocate(maxSize); GetFileNameWithoutExtension(result, maxSize, path); size_t reducedSize = String::SizeOf(path) + 1; result = Memory::Reallocate(result, reducedSize); return result; } - utf8 * GetFileNameWithoutExtension(utf8 * buffer, size_t bufferSize, const utf8 * path) + utf8* GetFileNameWithoutExtension(utf8* buffer, size_t bufferSize, const utf8* path) { path = GetFileName(path); - const utf8 * lastDot = nullptr; - const utf8 * ch = path; + const utf8* lastDot = nullptr; + const utf8* ch = path; for (; *ch != '\0'; ch++) { if (*ch == '.') @@ -147,15 +141,15 @@ namespace Path return buffer; } - const std::string GetExtension(const std::string &path) + const std::string GetExtension(const std::string& path) { return GetExtension(path.c_str()); } - const utf8 * GetExtension(const utf8 * path) + const utf8* GetExtension(const utf8* path) { - const utf8 * lastDot = nullptr; - const utf8 * ch = GetFileName(path); + const utf8* lastDot = nullptr; + const utf8* ch = GetFileName(path); for (; *ch != '\0'; ch++) { if (*ch == '.') @@ -174,11 +168,11 @@ namespace Path return lastDot; } - utf8 * GetAbsolute(utf8 *buffer, size_t bufferSize, const utf8 * relativePath) + utf8* GetAbsolute(utf8* buffer, size_t bufferSize, const utf8* relativePath) { #ifdef _WIN32 - wchar_t * relativePathW = utf8_to_widechar(relativePath); - wchar_t absolutePathW[MAX_PATH]; + wchar_t* relativePathW = utf8_to_widechar(relativePath); + wchar_t absolutePathW[MAX_PATH]; DWORD length = GetFullPathNameW(relativePathW, (DWORD)Util::CountOf(absolutePathW), absolutePathW, nullptr); Memory::Free(relativePathW); if (length == 0) @@ -187,13 +181,13 @@ namespace Path } else { - utf8 * absolutePath = widechar_to_utf8(absolutePathW); + utf8* absolutePath = widechar_to_utf8(absolutePathW); String::Set(buffer, bufferSize, absolutePath); Memory::Free(absolutePath); return buffer; } #else - utf8 * absolutePath = realpath(relativePath, nullptr); + utf8* absolutePath = realpath(relativePath, nullptr); if (absolutePath == nullptr) { return String::Set(buffer, bufferSize, relativePath); @@ -207,18 +201,18 @@ namespace Path #endif } - std::string GetAbsolute(const std::string &relative) + std::string GetAbsolute(const std::string& relative) { utf8 absolute[MAX_PATH]; return GetAbsolute(absolute, sizeof(absolute), relative.c_str()); } - bool Equals(const std::string &a, const std::string &b) + bool Equals(const std::string& a, const std::string& b) { return String::Equals(a.c_str(), b.c_str()); } - bool Equals(const utf8 * a, const utf8 * b) + bool Equals(const utf8* a, const utf8* b) { bool ignoreCase = false; #ifdef _WIN32 @@ -227,7 +221,7 @@ namespace Path return String::Equals(a, b, ignoreCase); } - std::string ResolveCasing(const std::string &path) + std::string ResolveCasing(const std::string& path) { std::string result; if (File::Exists(path)) @@ -242,7 +236,7 @@ namespace Path std::string fileName = Path::GetFileName(path); std::string directory = Path::GetDirectory(path); - struct dirent * * files; + struct dirent** files; auto count = scandir(directory.c_str(), &files, nullptr, alphasort); if (count != -1) { diff --git a/src/openrct2/core/Path.hpp b/src/openrct2/core/Path.hpp index 08b313c224..fcc5addd33 100644 --- a/src/openrct2/core/Path.hpp +++ b/src/openrct2/core/Path.hpp @@ -9,36 +9,36 @@ #pragma once -#include #include "../common.h" +#include + namespace Path { - utf8 * Append(utf8 * buffer, size_t bufferSize, const utf8 * src); - std::string Combine(const std::string &a, const std::string &b); + utf8* Append(utf8* buffer, size_t bufferSize, const utf8* src); + std::string Combine(const std::string& a, const std::string& b); - template - static std::string Combine(const std::string &a, const std::string &b, Args... args) + template static std::string Combine(const std::string& a, const std::string& b, Args... args) { return Combine(a, Combine(b, args...)); } - std::string GetDirectory(const std::string &path); - utf8 * GetDirectory(const utf8 * path); - utf8 * GetDirectory(utf8 * buffer, size_t bufferSize, const utf8 * path); - void CreateDirectory(const std::string &path); - bool DirectoryExists(const std::string &path); - std::string GetFileName(const std::string &path); - const utf8 * GetFileName(const utf8 * path); - std::string GetFileNameWithoutExtension(const std::string &path); - utf8 * GetFileNameWithoutExtension(const utf8 * path); - utf8 * GetFileNameWithoutExtension(utf8 * buffer, size_t bufferSize, const utf8 * path); - const std::string GetExtension(const std::string &path); - const utf8 * GetExtension(const utf8 * path); - utf8 * GetAbsolute(utf8 * buffer, size_t bufferSize, const utf8 * relativePath); - std::string GetAbsolute(const std::string &relative); - bool Equals(const std::string &a, const std::string &b); - bool Equals(const utf8 * a, const utf8 * b); + std::string GetDirectory(const std::string& path); + utf8* GetDirectory(const utf8* path); + utf8* GetDirectory(utf8* buffer, size_t bufferSize, const utf8* path); + void CreateDirectory(const std::string& path); + bool DirectoryExists(const std::string& path); + std::string GetFileName(const std::string& path); + const utf8* GetFileName(const utf8* path); + std::string GetFileNameWithoutExtension(const std::string& path); + utf8* GetFileNameWithoutExtension(const utf8* path); + utf8* GetFileNameWithoutExtension(utf8* buffer, size_t bufferSize, const utf8* path); + const std::string GetExtension(const std::string& path); + const utf8* GetExtension(const utf8* path); + utf8* GetAbsolute(utf8* buffer, size_t bufferSize, const utf8* relativePath); + std::string GetAbsolute(const std::string& relative); + bool Equals(const std::string& a, const std::string& b); + bool Equals(const utf8* a, const utf8* b); /** * Checks if the given path is a file. If not, checks to see if @@ -46,5 +46,5 @@ namespace Path * one found based on a straight forward character sort. * Note: This will not resolve the case for Windows. */ - std::string ResolveCasing(const std::string &path); + std::string ResolveCasing(const std::string& path); } // namespace Path diff --git a/src/openrct2/core/Registration.hpp b/src/openrct2/core/Registration.hpp index 0cbef01c1d..4602023bdb 100644 --- a/src/openrct2/core/Registration.hpp +++ b/src/openrct2/core/Registration.hpp @@ -28,15 +28,14 @@ namespace OpenRCT2 /** * Class which can wrap a function in an IRegistration. */ - template - struct CallbackRegistration : public IRegistration + template struct CallbackRegistration : public IRegistration { private: T _callback; public: - CallbackRegistration(T callback) : - _callback(callback) + CallbackRegistration(T callback) + : _callback(callback) { } @@ -51,10 +50,9 @@ namespace OpenRCT2 * Creates a new IRegistration which when deleted, calls the given * function. */ - template - static IRegistration * Create(T unregisterCallback) + template static IRegistration* Create(T unregisterCallback) { return new CallbackRegistration(unregisterCallback); } }; -} +} // namespace OpenRCT2 diff --git a/src/openrct2/core/String.cpp b/src/openrct2/core/String.cpp index 216e5a8a47..1c0e903f2b 100644 --- a/src/openrct2/core/String.cpp +++ b/src/openrct2/core/String.cpp @@ -34,7 +34,6 @@ #include "../localisation/ConversionTables.h" #include "../localisation/Language.h" #include "../util/Util.h" - #include "Math.hpp" #include "Memory.hpp" #include "String.hpp" @@ -42,13 +41,15 @@ namespace String { - std::string ToStd(const utf8 * str) + std::string ToStd(const utf8* str) { - if (str == nullptr) return std::string(); - else return std::string(str); + if (str == nullptr) + return std::string(); + else + return std::string(str); } - std::string StdFormat_VA(const utf8 * format, va_list args) + std::string StdFormat_VA(const utf8* format, va_list args) { auto buffer = Format_VA(format, args); auto returnValue = ToStd(buffer); @@ -56,11 +57,11 @@ namespace String return returnValue; } - std::string StdFormat(const utf8 * format, ...) + std::string StdFormat(const utf8* format, ...) { va_list args; va_start(args, format); - const utf8 * buffer = Format_VA(format, args); + const utf8* buffer = Format_VA(format, args); va_end(args); std::string returnValue = ToStd(buffer); Memory::Free(buffer); @@ -79,11 +80,11 @@ namespace String // Which constructor to use depends on the size of wchar_t... // UTF-32 is the default on most POSIX systems; Windows uses UTF-16. // Unfortunately, we'll have to help the compiler here. -#if U_SIZEOF_WCHAR_T==4 - icu::UnicodeString str = icu::UnicodeString::fromUTF32((const UChar32*) src.data(), src.length()); -#elif U_SIZEOF_WCHAR_T==2 +#if U_SIZEOF_WCHAR_T == 4 + icu::UnicodeString str = icu::UnicodeString::fromUTF32((const UChar32*)src.data(), src.length()); +#elif U_SIZEOF_WCHAR_T == 2 std::wstring wstr = std::wstring(src); - icu::UnicodeString str = icu::UnicodeString((const wchar_t*) wstr.c_str()); + icu::UnicodeString str = icu::UnicodeString((const wchar_t*)wstr.c_str()); #else #error Unsupported U_SIZEOF_WCHAR_T size #endif @@ -109,16 +110,16 @@ namespace String // Which constructor to use depends on the size of wchar_t... // UTF-32 is the default on most POSIX systems; Windows uses UTF-16. // Unfortunately, we'll have to help the compiler here. -#if U_SIZEOF_WCHAR_T==4 - size_t length = (size_t) str.length(); +#if U_SIZEOF_WCHAR_T == 4 + size_t length = (size_t)str.length(); std::wstring result(length, '\0'); UErrorCode status = U_ZERO_ERROR; - str.toUTF32((UChar32*) &result[0], str.length(), status); + str.toUTF32((UChar32*)&result[0], str.length(), status); -#elif U_SIZEOF_WCHAR_T==2 +#elif U_SIZEOF_WCHAR_T == 2 const char16_t* buffer = str.getBuffer(); - std::wstring result = (wchar_t*) buffer; + std::wstring result = (wchar_t*)buffer; #else #error Unsupported U_SIZEOF_WCHAR_T size @@ -128,21 +129,24 @@ namespace String #endif } - bool IsNullOrEmpty(const utf8 * str) + bool IsNullOrEmpty(const utf8* str) { return str == nullptr || str[0] == '\0'; } - int32_t Compare(const std::string &a, const std::string &b, bool ignoreCase) + int32_t Compare(const std::string& a, const std::string& b, bool ignoreCase) { return Compare(a.c_str(), b.c_str(), ignoreCase); } - int32_t Compare(const utf8 * a, const utf8 * b, bool ignoreCase) + int32_t Compare(const utf8* a, const utf8* b, bool ignoreCase) { - if (a == b) return 0; - if (a == nullptr) a = ""; - if (b == nullptr) b = ""; + if (a == b) + return 0; + if (a == nullptr) + a = ""; + if (b == nullptr) + b = ""; if (ignoreCase) { return _stricmp(a, b); @@ -153,15 +157,17 @@ namespace String } } - bool Equals(const std::string &a, const std::string &b, bool ignoreCase) + bool Equals(const std::string& a, const std::string& b, bool ignoreCase) { return Equals(a.c_str(), b.c_str(), ignoreCase); } - bool Equals(const utf8 * a, const utf8 * b, bool ignoreCase) + bool Equals(const utf8* a, const utf8* b, bool ignoreCase) { - if (a == b) return true; - if (a == nullptr || b == nullptr) return false; + if (a == b) + return true; + if (a == nullptr || b == nullptr) + return false; if (ignoreCase) { @@ -173,7 +179,7 @@ namespace String } } - bool StartsWith(const utf8 * str, const utf8 * match, bool ignoreCase) + bool StartsWith(const utf8* str, const utf8* match, bool ignoreCase) { if (ignoreCase) { @@ -199,7 +205,7 @@ namespace String } } - bool StartsWith(const std::string &str, const std::string &match, bool ignoreCase) + bool StartsWith(const std::string& str, const std::string& match, bool ignoreCase) { return StartsWith(str.c_str(), match.c_str(), ignoreCase); } @@ -214,9 +220,9 @@ namespace String return false; } - size_t IndexOf(const utf8 * str, utf8 match, size_t startIndex) + size_t IndexOf(const utf8* str, utf8 match, size_t startIndex) { - const utf8 * ch = str + startIndex; + const utf8* ch = str + startIndex; for (; *ch != '\0'; ch++) { if (*ch == match) @@ -227,10 +233,10 @@ namespace String return SIZE_MAX; } - ptrdiff_t LastIndexOf(const utf8 * str, utf8 match) + ptrdiff_t LastIndexOf(const utf8* str, utf8 match) { - const utf8 * lastOccurance = nullptr; - const utf8 * ch = str; + const utf8* lastOccurance = nullptr; + const utf8* ch = str; for (; *ch != '\0'; ch++) { if (*ch == match) @@ -249,41 +255,42 @@ namespace String } } - size_t LengthOf(const utf8 * str) + size_t LengthOf(const utf8* str) { return utf8_length(str); } - size_t SizeOf(const utf8 * str) + size_t SizeOf(const utf8* str) { return strlen(str); } - utf8 * Set(utf8 * buffer, size_t bufferSize, const utf8 * src) + utf8* Set(utf8* buffer, size_t bufferSize, const utf8* src) { return safe_strcpy(buffer, src, bufferSize); } - utf8 * Set(utf8 * buffer, size_t bufferSize, const utf8 * src, size_t srcSize) + utf8* Set(utf8* buffer, size_t bufferSize, const utf8* src, size_t srcSize) { - utf8 * dst = buffer; + utf8* dst = buffer; size_t minSize = std::min(bufferSize - 1, srcSize); for (size_t i = 0; i < minSize; i++) { *dst++ = *src; - if (*src == '\0') break; + if (*src == '\0') + break; src++; } *dst = '\0'; return buffer; } - utf8 * Append(utf8 * buffer, size_t bufferSize, const utf8 * src) + utf8* Append(utf8* buffer, size_t bufferSize, const utf8* src) { return safe_strcat(buffer, src, bufferSize); } - utf8 * Format(utf8 * buffer, size_t bufferSize, const utf8 * format, ...) + utf8* Format(utf8* buffer, size_t bufferSize, const utf8* format, ...) { va_list args; @@ -297,16 +304,16 @@ namespace String return buffer; } - utf8 * Format(const utf8 * format, ...) + utf8* Format(const utf8* format, ...) { va_list args; va_start(args, format); - utf8 * result = Format_VA(format, args); + utf8* result = Format_VA(format, args); va_end(args); return result; } - utf8 * Format_VA(const utf8 * format, va_list args) + utf8* Format_VA(const utf8* format, va_list args) { va_list args1, args2; va_copy(args1, args); @@ -314,7 +321,7 @@ namespace String // Try to format to a initial buffer, enlarge if not big enough size_t bufferSize = 4096; - utf8 * buffer = Memory::Allocate(bufferSize); + utf8* buffer = Memory::Allocate(bufferSize); // Start with initial buffer int32_t len = vsnprintf(buffer, bufferSize, format, args); @@ -359,13 +366,14 @@ namespace String return buffer; } - utf8 * AppendFormat(utf8 * buffer, size_t bufferSize, const utf8 * format, ...) + utf8* AppendFormat(utf8* buffer, size_t bufferSize, const utf8* format, ...) { - utf8 * dst = buffer; + utf8* dst = buffer; size_t i; for (i = 0; i < bufferSize; i++) { - if (*dst == '\0') break; + if (*dst == '\0') + break; dst++; } @@ -383,14 +391,14 @@ namespace String return buffer; } - utf8 * Duplicate(const std::string &src) + utf8* Duplicate(const std::string& src) { return String::Duplicate(src.c_str()); } - utf8 * Duplicate(const utf8 * src) + utf8* Duplicate(const utf8* src) { - utf8 * result = nullptr; + utf8* result = nullptr; if (src != nullptr) { size_t srcSize = SizeOf(src) + 1; @@ -400,19 +408,19 @@ namespace String return result; } - utf8 * DiscardUse(utf8 * * ptr, utf8 * replacement) + utf8* DiscardUse(utf8** ptr, utf8* replacement) { Memory::Free(*ptr); *ptr = replacement; return replacement; } - utf8 * DiscardDuplicate(utf8 * * ptr, const utf8 * replacement) + utf8* DiscardDuplicate(utf8** ptr, const utf8* replacement) { return DiscardUse(ptr, String::Duplicate(replacement)); } - std::vector Split(const std::string &s, const std::string &delimiter) + std::vector Split(const std::string& s, const std::string& delimiter) { if (delimiter.empty()) { @@ -438,18 +446,17 @@ namespace String } results.push_back(value); index = nextIndex + delimiter.size(); - } - while (nextIndex != SIZE_MAX); + } while (nextIndex != SIZE_MAX); } return results; } - utf8 * SkipBOM(utf8 * buffer) + utf8* SkipBOM(utf8* buffer) { - return (utf8*)SkipBOM((const utf8 *)buffer); + return (utf8*)SkipBOM((const utf8*)buffer); } - const utf8 * SkipBOM(const utf8 * buffer) + const utf8* SkipBOM(const utf8* buffer) { if ((uint8_t)buffer[0] == 0xEF && (uint8_t)buffer[1] == 0xBB && (uint8_t)buffer[2] == 0xBF) { @@ -463,17 +470,17 @@ namespace String return utf8_get_codepoint_length(codepoint); } - codepoint_t GetNextCodepoint(utf8 * ptr, utf8 * * nextPtr) + codepoint_t GetNextCodepoint(utf8* ptr, utf8** nextPtr) { - return GetNextCodepoint((const utf8 *)ptr, (const utf8 * *)nextPtr); + return GetNextCodepoint((const utf8*)ptr, (const utf8**)nextPtr); } - codepoint_t GetNextCodepoint(const utf8 * ptr, const utf8 * * nextPtr) + codepoint_t GetNextCodepoint(const utf8* ptr, const utf8** nextPtr) { return utf8_get_next(ptr, nextPtr); } - utf8 * WriteCodepoint(utf8 * dst, codepoint_t codepoint) + utf8* WriteCodepoint(utf8* dst, codepoint_t codepoint) { return utf8_write_codepoint(dst, codepoint); } @@ -484,13 +491,13 @@ namespace String return iswspace((wchar_t)codepoint) || codepoint == 0x3000; } - utf8 * Trim(utf8 * str) + utf8* Trim(utf8* str) { - utf8 * firstNonWhitespace = nullptr; + utf8* firstNonWhitespace = nullptr; codepoint_t codepoint; - utf8 * ch = str; - utf8 * nextCh; + utf8* ch = str; + utf8* nextCh; while ((codepoint = GetNextCodepoint(ch, &nextCh)) != '\0') { if (codepoint <= WCHAR_MAX && !IsWhiteSpace(codepoint)) @@ -503,8 +510,7 @@ namespace String ch = nextCh; } - if (firstNonWhitespace != nullptr && - firstNonWhitespace != str) + if (firstNonWhitespace != nullptr && firstNonWhitespace != str) { // Take multibyte characters into account: use the last byte of the // current character. @@ -526,11 +532,11 @@ namespace String return str; } - const utf8 * TrimStart(const utf8 * str) + const utf8* TrimStart(const utf8* str) { codepoint_t codepoint; - const utf8 * ch = str; - const utf8 * nextCh; + const utf8* ch = str; + const utf8* nextCh; while ((codepoint = GetNextCodepoint(ch, &nextCh)) != '\0') { if (codepoint <= WCHAR_MAX && !IsWhiteSpace(codepoint)) @@ -543,24 +549,24 @@ namespace String return ch; } - utf8 * TrimStart(utf8 * buffer, size_t bufferSize, const utf8 * src) + utf8* TrimStart(utf8* buffer, size_t bufferSize, const utf8* src) { return String::Set(buffer, bufferSize, TrimStart(src)); } - std::string TrimStart(const std::string &s) + std::string TrimStart(const std::string& s) { - const utf8 * trimmed = TrimStart(s.c_str()); + const utf8* trimmed = TrimStart(s.c_str()); return std::string(trimmed); } - std::string Trim(const std::string &s) + std::string Trim(const std::string& s) { codepoint_t codepoint; - const utf8 * ch = s.c_str(); - const utf8 * nextCh; - const utf8 * startSubstr = nullptr; - const utf8 * endSubstr = nullptr; + const utf8* ch = s.c_str(); + const utf8* nextCh; + const utf8* startSubstr = nullptr; + const utf8* endSubstr = nullptr; while ((codepoint = GetNextCodepoint(ch, &nextCh)) != '\0') { bool isWhiteSpace = codepoint <= WCHAR_MAX && IsWhiteSpace(codepoint); @@ -593,26 +599,26 @@ namespace String { switch (codePage) { - case CODE_PAGE::CP_932: - return "windows-932"; + case CODE_PAGE::CP_932: + return "windows-932"; - case CODE_PAGE::CP_936: - return "GB2312"; + case CODE_PAGE::CP_936: + return "GB2312"; - case CODE_PAGE::CP_949: - return "windows-949"; + case CODE_PAGE::CP_949: + return "windows-949"; - case CODE_PAGE::CP_950: - return "big5"; + case CODE_PAGE::CP_950: + return "big5"; - case CODE_PAGE::CP_1252: - return "windows-1252"; + case CODE_PAGE::CP_1252: + return "windows-1252"; - case CODE_PAGE::CP_UTF8: - return "utf-8"; + case CODE_PAGE::CP_UTF8: + return "utf-8"; - default: - throw std::runtime_error("Unsupported code page: " + std::to_string(codePage)); + default: + throw std::runtime_error("Unsupported code page: " + std::to_string(codePage)); } } @@ -642,7 +648,7 @@ namespace String // Convert the lot. char* buffer_target = &buffer[0]; - ucnv_fromUnicode(conv, &buffer_target, buffer_limit, (const UChar**) &source, source_limit, nullptr, true, &status); + ucnv_fromUnicode(conv, &buffer_target, buffer_limit, (const UChar**)&source, source_limit, nullptr, true, &status); if (U_FAILURE(status)) { diff --git a/src/openrct2/core/String.hpp b/src/openrct2/core/String.hpp index 528e5b1350..502f24ba8b 100644 --- a/src/openrct2/core/String.hpp +++ b/src/openrct2/core/String.hpp @@ -9,96 +9,97 @@ #pragma once +#include "../common.h" + #include #include #include #include -#include "../common.h" namespace CODE_PAGE { // windows.h defines CP_UTF8 #undef CP_UTF8 - constexpr int32_t CP_932 = 932; // ANSI/OEM Japanese; Japanese (Shift-JIS) - constexpr int32_t CP_936 = 936; // ANSI/OEM Simplified Chinese (PRC, Singapore); Chinese Simplified (GB2312) - constexpr int32_t CP_949 = 949; // ANSI/OEM Korean (Unified Hangul Code) - constexpr int32_t CP_950 = 950; // ANSI/OEM Traditional Chinese (Taiwan; Hong Kong SAR, PRC); Chinese Traditional (Big5) - constexpr int32_t CP_1252 = 1252; // ANSI Latin 1; Western European (Windows) - constexpr int32_t CP_UTF8 = 65001; // Unicode (UTF-8) + constexpr int32_t CP_932 = 932; // ANSI/OEM Japanese; Japanese (Shift-JIS) + constexpr int32_t CP_936 = 936; // ANSI/OEM Simplified Chinese (PRC, Singapore); Chinese Simplified (GB2312) + constexpr int32_t CP_949 = 949; // ANSI/OEM Korean (Unified Hangul Code) + constexpr int32_t CP_950 = 950; // ANSI/OEM Traditional Chinese (Taiwan; Hong Kong SAR, PRC); Chinese Traditional (Big5) + constexpr int32_t CP_1252 = 1252; // ANSI Latin 1; Western European (Windows) + constexpr int32_t CP_UTF8 = 65001; // Unicode (UTF-8) } // namespace CODE_PAGE namespace String { - constexpr const utf8 * Empty = ""; + constexpr const utf8* Empty = ""; - std::string ToStd(const utf8 * str); - std::string StdFormat_VA(const utf8 * format, va_list args); - std::string StdFormat(const utf8 * format, ...); - std::string ToUtf8(const std::wstring_view& src); - std::wstring ToUtf16(const std::string_view& src); + std::string ToStd(const utf8* str); + std::string StdFormat_VA(const utf8* format, va_list args); + std::string StdFormat(const utf8* format, ...); + std::string ToUtf8(const std::wstring_view& src); + std::wstring ToUtf16(const std::string_view& src); - bool IsNullOrEmpty(const utf8 * str); - int32_t Compare(const std::string &a, const std::string &b, bool ignoreCase = false); - int32_t Compare(const utf8 * a, const utf8 * b, bool ignoreCase = false); - bool Equals(const std::string &a, const std::string &b, bool ignoreCase = false); - bool Equals(const utf8 * a, const utf8 * b, bool ignoreCase = false); - bool StartsWith(const utf8 * str, const utf8 * match, bool ignoreCase = false); - bool StartsWith(const std::string &str, const std::string &match, bool ignoreCase = false); - bool EndsWith(const std::string_view& str, const std::string_view& match, bool ignoreCase = false); - size_t IndexOf(const utf8 * str, utf8 match, size_t startIndex = 0); - ptrdiff_t LastIndexOf(const utf8 * str, utf8 match); + bool IsNullOrEmpty(const utf8* str); + int32_t Compare(const std::string& a, const std::string& b, bool ignoreCase = false); + int32_t Compare(const utf8* a, const utf8* b, bool ignoreCase = false); + bool Equals(const std::string& a, const std::string& b, bool ignoreCase = false); + bool Equals(const utf8* a, const utf8* b, bool ignoreCase = false); + bool StartsWith(const utf8* str, const utf8* match, bool ignoreCase = false); + bool StartsWith(const std::string& str, const std::string& match, bool ignoreCase = false); + bool EndsWith(const std::string_view& str, const std::string_view& match, bool ignoreCase = false); + size_t IndexOf(const utf8* str, utf8 match, size_t startIndex = 0); + ptrdiff_t LastIndexOf(const utf8* str, utf8 match); /** * Gets the length of the given string in codepoints. */ - size_t LengthOf(const utf8 * str); + size_t LengthOf(const utf8* str); /** * Gets the size of the given string in bytes excluding the null terminator. */ - size_t SizeOf(const utf8 * str); + size_t SizeOf(const utf8* str); - utf8 * Set(utf8 * buffer, size_t bufferSize, const utf8 * src); - utf8 * Set(utf8 * buffer, size_t bufferSize, const utf8 * src, size_t srcSize); - utf8 * Append(utf8 * buffer, size_t bufferSize, const utf8 * src); - utf8 * Format(utf8 * buffer, size_t bufferSize, const utf8 * format, ...); - utf8 * Format(const utf8 * format, ...); - utf8 * Format_VA(const utf8 * format, va_list args); - utf8 * AppendFormat(utf8 * buffer, size_t bufferSize, const utf8 * format, ...); - utf8 * Duplicate(const std::string &src); - utf8 * Duplicate(const utf8 * src); + utf8* Set(utf8* buffer, size_t bufferSize, const utf8* src); + utf8* Set(utf8* buffer, size_t bufferSize, const utf8* src, size_t srcSize); + utf8* Append(utf8* buffer, size_t bufferSize, const utf8* src); + utf8* Format(utf8* buffer, size_t bufferSize, const utf8* format, ...); + utf8* Format(const utf8* format, ...); + utf8* Format_VA(const utf8* format, va_list args); + utf8* AppendFormat(utf8* buffer, size_t bufferSize, const utf8* format, ...); + utf8* Duplicate(const std::string& src); + utf8* Duplicate(const utf8* src); /** * Helper method to free the string a string pointer points to and set it to a replacement string. */ - utf8 * DiscardUse(utf8 * * ptr, utf8 * replacement); + utf8* DiscardUse(utf8** ptr, utf8* replacement); /** * Helper method to free the string a string pointer points to and set it to a copy of a replacement string. */ - utf8 * DiscardDuplicate(utf8 * * ptr, const utf8 * replacement); + utf8* DiscardDuplicate(utf8** ptr, const utf8* replacement); /** * Splits the given string by a delimiter and returns the values as a new string array. * @returns the number of values. */ - std::vector Split(const std::string &s, const std::string &delimiter); + std::vector Split(const std::string& s, const std::string& delimiter); - utf8 * SkipBOM(utf8 * buffer); - const utf8 * SkipBOM(const utf8 * buffer); + utf8* SkipBOM(utf8* buffer); + const utf8* SkipBOM(const utf8* buffer); - size_t GetCodepointLength(codepoint_t codepoint); - codepoint_t GetNextCodepoint(utf8 * ptr, utf8 * * nextPtr = nullptr); - codepoint_t GetNextCodepoint(const utf8 * ptr, const utf8 * * nextPtr = nullptr); - utf8 * WriteCodepoint(utf8 * dst, codepoint_t codepoint); + size_t GetCodepointLength(codepoint_t codepoint); + codepoint_t GetNextCodepoint(utf8* ptr, utf8** nextPtr = nullptr); + codepoint_t GetNextCodepoint(const utf8* ptr, const utf8** nextPtr = nullptr); + utf8* WriteCodepoint(utf8* dst, codepoint_t codepoint); - bool IsWhiteSpace(codepoint_t codepoint); - utf8 * Trim(utf8 * str); - const utf8 * TrimStart(const utf8 * str); - utf8 * TrimStart(utf8 * buffer, size_t bufferSize, const utf8 * src); - std::string TrimStart(const std::string &s); - std::string Trim(const std::string &s); + bool IsWhiteSpace(codepoint_t codepoint); + utf8* Trim(utf8* str); + const utf8* TrimStart(const utf8* str); + utf8* TrimStart(utf8* buffer, size_t bufferSize, const utf8* src); + std::string TrimStart(const std::string& s); + std::string Trim(const std::string& s); /** * Converts a multi-byte string from one code page to another. @@ -109,4 +110,4 @@ namespace String * Returns an uppercased version of a UTF-8 string. */ std::string ToUpper(const std::string_view& src); -} +} // namespace String diff --git a/src/openrct2/core/StringBuilder.hpp b/src/openrct2/core/StringBuilder.hpp index b993f21820..c090e11484 100644 --- a/src/openrct2/core/StringBuilder.hpp +++ b/src/openrct2/core/StringBuilder.hpp @@ -9,14 +9,14 @@ #pragma once -#include -#include #include "../common.h" - #include "Math.hpp" #include "Memory.hpp" #include "String.hpp" +#include +#include + /** * Class for constructing strings efficiently. A buffer is automatically allocated and reallocated when characters or strings * are appended. Use GetString to copy the current state of the string builder to a new fire-and-forget string. @@ -55,7 +55,7 @@ public: /** * Appends the given string to the current string. */ - void Append(const utf8 * text) + void Append(const utf8* text) { size_t textLength = String::SizeOf(text); Append(text, textLength); @@ -67,7 +67,7 @@ public: * @param text Pointer to the UTF-8 text to append. * @param textLength Number of bytes to copy. (Can be used to append single bytes rather than codepoints) */ - void Append(const utf8 * text, size_t textLength) + void Append(const utf8* text, size_t textLength) { EnsureCapacity(_length + textLength + 1); std::copy_n(text, textLength, _buffer + _length); @@ -78,7 +78,7 @@ public: /** * Appends the string of a given StringBuilder to the current string. */ - void Append(const StringBuilder * sb) + void Append(const StringBuilder* sb) { Append(sb->GetBuffer(), sb->GetLength()); } @@ -108,9 +108,9 @@ public: /** * Resets the StringBuilder and returns the working buffer (resized to the string size). */ - utf8 * StealString() + utf8* StealString() { - utf8 * result = _buffer; + utf8* result = _buffer; result = Memory::ReallocateArray(result, _length + 1); result[_length] = 0; @@ -124,10 +124,10 @@ public: /** * Returns the current string buffer as a new fire-and-forget string. */ - utf8 * GetString() const + utf8* GetString() const { // If buffer is null, length should be 0 which will create a new one byte memory block containing a null terminator - utf8 * result = Memory::AllocateArray(_length + 1); + utf8* result = Memory::AllocateArray(_length + 1); std::copy_n(_buffer, _length, result); result[_length] = 0; return result; @@ -145,31 +145,39 @@ public: * Gets the current state of the StringBuilder. Warning: this represents the StringBuilder's current working buffer and will * be deallocated when the StringBuilder is destructed. */ - const utf8 * GetBuffer() const + const utf8* GetBuffer() const { // buffer may be null, so return an immutable empty string - if (_buffer == nullptr) return ""; + if (_buffer == nullptr) + return ""; return _buffer; } /** * Gets the amount of allocated memory for the string buffer. */ - size_t GetCapacity() const { return _capacity; } + size_t GetCapacity() const + { + return _capacity; + } /** * Gets the length of the current string. */ - size_t GetLength() const { return _length; } + size_t GetLength() const + { + return _length; + } private: - utf8 * _buffer = nullptr; + utf8* _buffer = nullptr; size_t _capacity = 0; size_t _length = 0; void EnsureCapacity(size_t capacity) { - if (_capacity > capacity) return; + if (_capacity > capacity) + return; _capacity = std::max((size_t)8, _capacity); while (_capacity < capacity) diff --git a/src/openrct2/core/StringReader.hpp b/src/openrct2/core/StringReader.hpp index 592ad3cb39..1189996632 100644 --- a/src/openrct2/core/StringReader.hpp +++ b/src/openrct2/core/StringReader.hpp @@ -18,16 +18,16 @@ interface IStringReader { virtual ~IStringReader() = default; - virtual bool TryPeek(codepoint_t * outCodepoint) abstract; - virtual bool TryRead(codepoint_t * outCodepoint) abstract; - virtual void Skip() abstract; - virtual bool CanRead() const abstract; + virtual bool TryPeek(codepoint_t * outCodepoint) abstract; + virtual bool TryRead(codepoint_t * outCodepoint) abstract; + virtual void Skip() abstract; + virtual bool CanRead() const abstract; }; class UTF8StringReader final : public IStringReader { public: - explicit UTF8StringReader(const utf8 * text) + explicit UTF8StringReader(const utf8* text) { text = String::SkipBOM(text); @@ -35,18 +35,20 @@ public: _current = text; } - bool TryPeek(codepoint_t * outCodepoint) override + bool TryPeek(codepoint_t* outCodepoint) override { - if (_current == nullptr) return false; + if (_current == nullptr) + return false; codepoint_t codepoint = String::GetNextCodepoint(_current); *outCodepoint = codepoint; return true; } - bool TryRead(codepoint_t * outCodepoint) override + bool TryRead(codepoint_t* outCodepoint) override { - if (_current == nullptr) return false; + if (_current == nullptr) + return false; codepoint_t codepoint = String::GetNextCodepoint(_current, &_current); *outCodepoint = codepoint; @@ -70,6 +72,6 @@ public: } private: - const utf8 *_text; - const utf8 *_current; + const utf8* _text; + const utf8* _current; }; diff --git a/src/openrct2/core/Util.hpp b/src/openrct2/core/Util.hpp index 34657bb6a0..b7a8047863 100644 --- a/src/openrct2/core/Util.hpp +++ b/src/openrct2/core/Util.hpp @@ -15,14 +15,13 @@ /** * Common utility functions. */ -namespace Util { - -// Based on http://www.g-truc.net/post-0708.html -template -static constexpr size_t CountOf(T const (&)[N]) noexcept +namespace Util { - return N; -} + // Based on http://www.g-truc.net/post-0708.html + template static constexpr size_t CountOf(T const (&)[N]) noexcept + { + return N; + } } // namespace Util diff --git a/src/openrct2/core/Zip.cpp b/src/openrct2/core/Zip.cpp index 0ef125461a..bb29f57bbb 100644 --- a/src/openrct2/core/Zip.cpp +++ b/src/openrct2/core/Zip.cpp @@ -8,14 +8,16 @@ *****************************************************************************/ #ifndef __ANDROID__ -#include -#include "IStream.hpp" #include "Zip.h" +#include "IStream.hpp" + +#include + class ZipArchive final : public IZipArchive { private: - zip_t * _zip; + zip_t* _zip; ZIP_ACCESS _access; std::vector> _writeBuffers; @@ -188,4 +190,4 @@ namespace Zip } } // namespace Zip -# endif +#endif diff --git a/src/openrct2/core/Zip.h b/src/openrct2/core/Zip.h index e423ab8f09..f2c762a104 100644 --- a/src/openrct2/core/Zip.h +++ b/src/openrct2/core/Zip.h @@ -9,17 +9,20 @@ #pragma once +#include "../common.h" + #include #include #include -#include "../common.h" /** * Represents a zip file. */ interface IZipArchive { - virtual ~IZipArchive() { } + virtual ~IZipArchive() + { + } virtual size_t GetNumFiles() const abstract; virtual std::string GetFileName(size_t index) const abstract; @@ -47,4 +50,4 @@ namespace Zip { std::unique_ptr Open(const std::string_view& path, ZIP_ACCESS zipAccess); std::unique_ptr TryOpen(const std::string_view& path, ZIP_ACCESS zipAccess); -} +} // namespace Zip diff --git a/src/openrct2/core/ZipAndroid.cpp b/src/openrct2/core/ZipAndroid.cpp index de8ad1020c..59826a03b6 100644 --- a/src/openrct2/core/ZipAndroid.cpp +++ b/src/openrct2/core/ZipAndroid.cpp @@ -9,11 +9,12 @@ #ifdef __ANDROID__ -#include -#include #include "IStream.hpp" #include "Zip.h" +#include +#include + class ZipArchive final : public IZipArchive { private: @@ -23,7 +24,7 @@ public: ZipArchive(const std::string_view& path, ZIP_ACCESS access) { // retrieve the JNI environment. - JNIEnv *env = (JNIEnv *) SDL_AndroidGetJNIEnv(); + JNIEnv* env = (JNIEnv*)SDL_AndroidGetJNIEnv(); jclass jniClass = env->FindClass("website/openrct2/ZipArchive"); jmethodID constructor = env->GetMethodID(jniClass, "", "(Ljava/lang/String;)V"); @@ -39,7 +40,7 @@ public: ~ZipArchive() override { // retrieve the JNI environment. - JNIEnv *env = (JNIEnv *) SDL_AndroidGetJNIEnv(); + JNIEnv* env = (JNIEnv*)SDL_AndroidGetJNIEnv(); jclass zipClass = env->GetObjectClass(_zip); jmethodID closeMethod = env->GetMethodID(zipClass, "close", "()V"); @@ -52,29 +53,28 @@ public: size_t GetNumFiles() const override { // retrieve the JNI environment. - JNIEnv *env = (JNIEnv *) SDL_AndroidGetJNIEnv(); + JNIEnv* env = (JNIEnv*)SDL_AndroidGetJNIEnv(); jclass zipClass = env->GetObjectClass(_zip); jmethodID fileCountMethod = env->GetMethodID(zipClass, "getNumFiles", "()I"); - return (size_t) env->CallIntMethod(_zip, fileCountMethod); + return (size_t)env->CallIntMethod(_zip, fileCountMethod); } std::string GetFileName(size_t index) const override { // retrieve the JNI environment. - JNIEnv *env = (JNIEnv *) SDL_AndroidGetJNIEnv(); + JNIEnv* env = (JNIEnv*)SDL_AndroidGetJNIEnv(); jclass zipClass = env->GetObjectClass(_zip); - jmethodID fileNameMethod = env->GetMethodID(zipClass, "getFileName", - "(I)Ljava/lang/String;"); + jmethodID fileNameMethod = env->GetMethodID(zipClass, "getFileName", "(I)Ljava/lang/String;"); - jstring jniString = (jstring) env->CallObjectMethod(_zip, fileNameMethod, (jint) index); + jstring jniString = (jstring)env->CallObjectMethod(_zip, fileNameMethod, (jint)index); - const char *jniChars = env->GetStringUTFChars(jniString, nullptr); + const char* jniChars = env->GetStringUTFChars(jniString, nullptr); - utf8 *string = (char *) malloc(strlen(jniChars) + 1); - memcpy((void *) string, jniChars, strlen(jniChars)); + utf8* string = (char*)malloc(strlen(jniChars) + 1); + memcpy((void*)string, jniChars, strlen(jniChars)); string[strlen(jniChars)] = 0x00; env->ReleaseStringUTFChars(jniString, jniChars); @@ -85,18 +85,18 @@ public: uint64_t GetFileSize(size_t index) const override { // retrieve the JNI environment. - JNIEnv *env = (JNIEnv *) SDL_AndroidGetJNIEnv(); + JNIEnv* env = (JNIEnv*)SDL_AndroidGetJNIEnv(); jclass zipClass = env->GetObjectClass(_zip); jmethodID fileSizeMethod = env->GetMethodID(zipClass, "getFileSize", "(I)J"); - return (size_t) env->CallLongMethod(_zip, fileSizeMethod, (jint) index); + return (size_t)env->CallLongMethod(_zip, fileSizeMethod, (jint)index); } std::vector GetFileData(const std::string_view& path) const override { // retrieve the JNI environment. - JNIEnv *env = (JNIEnv *) SDL_AndroidGetJNIEnv(); + JNIEnv* env = (JNIEnv*)SDL_AndroidGetJNIEnv(); jclass zipClass = env->GetObjectClass(_zip); jstring javaPath = env->NewStringUTF(path.data()); @@ -106,7 +106,7 @@ public: jmethodID fileMethod = env->GetMethodID(zipClass, "getFile", "(I)J"); jlong ptr = env->CallLongMethod(_zip, fileMethod, index); - auto dataPtr = reinterpret_cast(ptr); + auto dataPtr = reinterpret_cast(ptr); auto dataSize = this->GetFileSize(index); return std::vector(dataPtr, dataPtr + dataSize); @@ -147,26 +147,22 @@ namespace Zip } return result; } -} +} // namespace Zip extern "C" { -JNIEXPORT jlong JNICALL -Java_website_openrct2_ZipArchive_allocBytes(JNIEnv *env, jclass, jbyteArray input, - jint numBytes); +JNIEXPORT jlong JNICALL Java_website_openrct2_ZipArchive_allocBytes(JNIEnv* env, jclass, jbyteArray input, jint numBytes); } -JNIEXPORT jlong JNICALL -Java_website_openrct2_ZipArchive_allocBytes(JNIEnv *env, jclass, jbyteArray input, - jint numBytes) { +JNIEXPORT jlong JNICALL Java_website_openrct2_ZipArchive_allocBytes(JNIEnv* env, jclass, jbyteArray input, jint numBytes) +{ + jbyte* bufferPtr = env->GetByteArrayElements(input, nullptr); - jbyte *bufferPtr = env->GetByteArrayElements(input, nullptr); - - void *data = Memory::Allocate((size_t) numBytes); + void* data = Memory::Allocate((size_t)numBytes); memcpy(data, bufferPtr, numBytes); env->ReleaseByteArrayElements(input, bufferPtr, 0); - return (uintptr_t) data; + return (uintptr_t)data; } #endif // __ANDROID__