clang-format core

This commit is contained in:
clang-format 2018-06-22 22:58:39 +02:00 committed by Hielke Morsink
parent 6f2e84e593
commit 3a4a11f738
40 changed files with 929 additions and 917 deletions

View File

@ -9,11 +9,12 @@
#pragma once #pragma once
#include <initializer_list>
#include "../common.h" #include "../common.h"
#include "Memory.hpp" #include "Memory.hpp"
#include "String.hpp" #include "String.hpp"
#include <initializer_list>
namespace Collections namespace Collections
{ {
template<typename TCollection, typename TItem> template<typename TCollection, typename TItem>
@ -50,8 +51,7 @@ namespace Collections
return SIZE_MAX; return SIZE_MAX;
} }
template<typename TCollection, typename TPred> template<typename TCollection, typename TPred> static size_t IndexOf(TCollection& collection, TPred predicate)
static size_t IndexOf(TCollection &collection, TPred predicate)
{ {
size_t index = 0; size_t index = 0;
for (auto item : collection) for (auto item : collection)
@ -67,28 +67,19 @@ namespace Collections
#pragma region String helpers #pragma region String helpers
template<typename TCollection> template<typename TCollection> static bool Contains(TCollection& collection, const char* item, bool ignoreCase = false)
static bool Contains(TCollection &collection, const char * item, bool ignoreCase = false)
{ {
return Contains(collection, item, return Contains(
[ignoreCase](const char * a, const char * b) collection, item, [ignoreCase](const char* a, const char* b) { return String::Equals(a, b, ignoreCase); });
{
return String::Equals(a, b, ignoreCase);
});
} }
template<typename TCollection> template<typename TCollection> static size_t IndexOf(TCollection& collection, const char* item, bool ignoreCase = false)
static size_t IndexOf(TCollection &collection, const char * item, bool ignoreCase = false)
{ {
return IndexOf(collection, item, return IndexOf(
[ignoreCase](const char * a, const char * b) collection, item, [ignoreCase](const char* a, const char* b) { return String::Equals(a, b, ignoreCase); });
{
return String::Equals(a, b, ignoreCase);
});
} }
template<typename TCollection> template<typename TCollection> static typename TCollection::value_type* ToArray(const TCollection& collection)
static typename TCollection::value_type * ToArray(const TCollection &collection)
{ {
size_t count = collection.size(); size_t count = collection.size();
if (count == 0) if (count == 0)

View File

@ -7,12 +7,13 @@
* OpenRCT2 is licensed under the GNU General Public License version 3. * OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/ *****************************************************************************/
#include "Console.hpp"
#include "../platform/platform.h"
#include <cstdio> #include <cstdio>
#include <string> #include <string>
#include "Console.hpp"
#include "../platform/platform.h"
namespace Console namespace Console
{ {
void Write(char c) void Write(char c)

View File

@ -10,11 +10,12 @@
#ifndef DISABLE_NETWORK #ifndef DISABLE_NETWORK
#include "Crypt.h" #include "Crypt.h"
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <stdexcept> #include <stdexcept>
#include <string> #include <string>
#include <vector> #include <vector>
#include <openssl/evp.h>
#include <openssl/pem.h>
using namespace Crypt; using namespace Crypt;
@ -36,8 +37,7 @@ static void OpenSSLInitialise()
} }
} }
template<typename TBase> template<typename TBase> class OpenSSLHashAlgorithm final : public TBase
class OpenSSLHashAlgorithm final : public TBase
{ {
private: private:
const EVP_MD* _type; const EVP_MD* _type;
@ -111,7 +111,10 @@ public:
class OpenSSLRsaKey final : public RsaKey class OpenSSLRsaKey final : public RsaKey
{ {
public: public:
EVP_PKEY * GetEvpKey() const { return _evpKey; } EVP_PKEY* GetEvpKey() const
{
return _evpKey;
}
~OpenSSLRsaKey() ~OpenSSLRsaKey()
{ {
@ -163,9 +166,15 @@ public:
SetKey(pem, false); 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: private:
EVP_PKEY* _evpKey{}; EVP_PKEY* _evpKey{};
@ -179,15 +188,12 @@ private:
{ {
throw std::runtime_error("BIO_new_mem_buf failed"); throw std::runtime_error("BIO_new_mem_buf failed");
} }
auto rsa = isPrivate ? auto rsa = isPrivate ? PEM_read_bio_RSAPrivateKey(bio, nullptr, nullptr, nullptr)
PEM_read_bio_RSAPrivateKey(bio, nullptr, nullptr, nullptr) : : PEM_read_bio_RSAPublicKey(bio, nullptr, nullptr, nullptr);
PEM_read_bio_RSAPublicKey(bio, nullptr, nullptr, nullptr);
if (rsa == nullptr) if (rsa == nullptr)
{ {
BIO_free_all(bio); BIO_free_all(bio);
auto msg = isPrivate ? auto msg = isPrivate ? "PEM_read_bio_RSAPrivateKey failed" : "PEM_read_bio_RSAPublicKey failed";
"PEM_read_bio_RSAPrivateKey failed" :
"PEM_read_bio_RSAPublicKey failed";
throw std::runtime_error(msg); throw std::runtime_error(msg);
} }
BIO_free_all(bio); BIO_free_all(bio);
@ -224,9 +230,8 @@ private:
throw std::runtime_error("BIO_new failed"); throw std::runtime_error("BIO_new failed");
} }
auto status = isPrivate ? auto status = isPrivate ? PEM_write_bio_RSAPrivateKey(bio, rsa, nullptr, nullptr, 0, nullptr, nullptr)
PEM_write_bio_RSAPrivateKey(bio, rsa, nullptr, nullptr, 0, nullptr, nullptr) : : PEM_write_bio_RSAPublicKey(bio, rsa);
PEM_write_bio_RSAPublicKey(bio, rsa);
if (status != 1) if (status != 1)
{ {
BIO_free_all(bio); BIO_free_all(bio);
@ -343,6 +348,6 @@ namespace Crypt
OpenSSLInitialise(); OpenSSLInitialise();
return std::make_unique<OpenSSLRsaKey>(); return std::make_unique<OpenSSLRsaKey>();
} }
} } // namespace Crypt
#endif // DISABLE_NETWORK #endif // DISABLE_NETWORK

View File

@ -16,8 +16,7 @@
namespace Crypt namespace Crypt
{ {
template<size_t TLength> template<size_t TLength> class HashAlgorithm
class HashAlgorithm
{ {
public: public:
typedef std::array<uint8_t, TLength> Result; typedef std::array<uint8_t, TLength> Result;
@ -58,15 +57,11 @@ namespace Crypt
inline Sha1Algorithm::Result SHA1(const void* data, size_t dataLen) inline Sha1Algorithm::Result SHA1(const void* data, size_t dataLen)
{ {
return CreateSHA1() return CreateSHA1()->Update(data, dataLen)->Finish();
->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() return CreateSHA256()->Update(data, dataLen)->Finish();
->Update(data, dataLen)
->Finish();
}
} }
} // namespace Crypt

View File

@ -9,9 +9,10 @@
#pragma once #pragma once
#include <type_traits>
#include "DataSerialiserTraits.h" #include "DataSerialiserTraits.h"
#include <type_traits>
class DataSerialiser class DataSerialiser
{ {
private: private:
@ -20,12 +21,14 @@ private:
bool _isSaving; bool _isSaving;
public: public:
DataSerialiser(bool isSaving) : _isSaving(isSaving) DataSerialiser(bool isSaving)
: _isSaving(isSaving)
{ {
_activeStream = &_stream; _activeStream = &_stream;
} }
DataSerialiser(bool isSaving, MemoryStream& stream) : _isSaving(isSaving) DataSerialiser(bool isSaving, MemoryStream& stream)
: _isSaving(isSaving)
{ {
_activeStream = &stream; _activeStream = &stream;
} }
@ -45,8 +48,7 @@ public:
return _stream; return _stream;
} }
template<typename T> template<typename T> DataSerialiser& operator<<(T& data)
DataSerialiser& operator<<(T& data)
{ {
if (_isSaving) if (_isSaving)
DataSerializerTraits<T>::encode(_activeStream, data); DataSerializerTraits<T>::encode(_activeStream, data);

View File

@ -12,14 +12,13 @@
#include "Endianness.h" #include "Endianness.h"
#include "MemoryStream.h" #include "MemoryStream.h"
template<typename T> template<typename T> struct DataSerializerTraits
struct DataSerializerTraits { {
static void encode(IStream* stream, const T& v) = delete; static void encode(IStream* stream, const T& v) = delete;
static void decode(IStream* stream, T& val) = delete; static void decode(IStream* stream, T& val) = delete;
}; };
template<typename T> template<typename T> struct DataSerializerTraitsIntegral
struct DataSerializerTraitsIntegral
{ {
static void encode(IStream* stream, const T& val) static void encode(IStream* stream, const T& val)
{ {
@ -34,29 +33,35 @@ struct DataSerializerTraitsIntegral
} }
}; };
template<> template<> struct DataSerializerTraits<bool> : public DataSerializerTraitsIntegral<bool>
struct DataSerializerTraits<bool> : public DataSerializerTraitsIntegral<bool> {}; {
};
template<> template<> struct DataSerializerTraits<uint8_t> : public DataSerializerTraitsIntegral<uint8_t>
struct DataSerializerTraits<uint8_t> : public DataSerializerTraitsIntegral<uint8_t> {}; {
};
template<> template<> struct DataSerializerTraits<int8_t> : public DataSerializerTraitsIntegral<int8_t>
struct DataSerializerTraits<int8_t> : public DataSerializerTraitsIntegral<int8_t> {}; {
};
template<> template<> struct DataSerializerTraits<uint16_t> : public DataSerializerTraitsIntegral<uint16_t>
struct DataSerializerTraits<uint16_t> : public DataSerializerTraitsIntegral<uint16_t> {}; {
};
template<> template<> struct DataSerializerTraits<int16_t> : public DataSerializerTraitsIntegral<int16_t>
struct DataSerializerTraits<int16_t> : public DataSerializerTraitsIntegral<int16_t> {}; {
};
template<> template<> struct DataSerializerTraits<uint32_t> : public DataSerializerTraitsIntegral<uint32_t>
struct DataSerializerTraits<uint32_t> : public DataSerializerTraitsIntegral<uint32_t> {}; {
};
template<> template<> struct DataSerializerTraits<int32_t> : public DataSerializerTraitsIntegral<int32_t>
struct DataSerializerTraits<int32_t> : public DataSerializerTraitsIntegral<int32_t> {}; {
};
template<> template<> struct DataSerializerTraits<std::string>
struct DataSerializerTraits<std::string>
{ {
static void encode(IStream* stream, const std::string& str) static void encode(IStream* stream, const std::string& str)
{ {

View File

@ -11,11 +11,11 @@
#include "../common.h" #include "../common.h"
template <size_t size> template<size_t size> struct ByteSwapT
struct ByteSwapT { }; {
};
template <> template<> struct ByteSwapT<1>
struct ByteSwapT<1>
{ {
static uint8_t SwapBE(uint8_t value) static uint8_t SwapBE(uint8_t value)
{ {
@ -23,8 +23,7 @@ struct ByteSwapT<1>
} }
}; };
template <> template<> struct ByteSwapT<2>
struct ByteSwapT<2>
{ {
static uint16_t SwapBE(uint16_t value) static uint16_t SwapBE(uint16_t value)
{ {
@ -32,20 +31,15 @@ struct ByteSwapT<2>
} }
}; };
template <> template<> struct ByteSwapT<4>
struct ByteSwapT<4>
{ {
static uint32_t SwapBE(uint32_t value) static uint32_t SwapBE(uint32_t value)
{ {
return (uint32_t)(((value << 24) | return (uint32_t)(((value << 24) | ((value << 8) & 0x00FF0000) | ((value >> 8) & 0x0000FF00) | (value >> 24)));
((value << 8) & 0x00FF0000) |
((value >> 8) & 0x0000FF00) |
(value >> 24)));
} }
}; };
template <typename T> template<typename T> static T ByteSwapBE(const T& value)
static T ByteSwapBE(const T& value)
{ {
return ByteSwapT<sizeof(T)>::SwapBE(value); return ByteSwapT<sizeof(T)>::SwapBE(value);
} }

View File

@ -14,13 +14,13 @@
#include <sys/stat.h> #include <sys/stat.h>
#endif #endif
#include <fstream> #include "../platform/platform.h"
#include "../util/Util.h"
#include "File.h" #include "File.h"
#include "FileStream.hpp" #include "FileStream.hpp"
#include "String.hpp" #include "String.hpp"
#include "../util/Util.h"
#include "../platform/platform.h" #include <fstream>
namespace File namespace File
{ {
@ -137,7 +137,9 @@ namespace File
} }
free(pathW); free(pathW);
#else #else
struct stat statInfo{}; struct stat statInfo
{
};
if (stat(path.c_str(), &statInfo) == 0) if (stat(path.c_str(), &statInfo) == 0)
{ {
lastModified = statInfo.st_mtime; lastModified = statInfo.st_mtime;
@ -159,4 +161,3 @@ bool writeentirefile(const utf8 * path, const void * buffer, size_t length)
return false; return false;
} }
} }

View File

@ -9,10 +9,11 @@
#pragma once #pragma once
#include "../common.h"
#include <string> #include <string>
#include <string_view> #include <string_view>
#include <vector> #include <vector>
#include "../common.h"
namespace File namespace File
{ {

View File

@ -9,11 +9,6 @@
#pragma once #pragma once
#include <chrono>
#include <string>
#include <tuple>
#include <vector>
#include <list>
#include "../common.h" #include "../common.h"
#include "Console.hpp" #include "Console.hpp"
#include "File.h" #include "File.h"
@ -22,8 +17,13 @@
#include "JobPool.hpp" #include "JobPool.hpp"
#include "Path.hpp" #include "Path.hpp"
template<typename TItem> #include <chrono>
class FileIndex #include <list>
#include <string>
#include <tuple>
#include <vector>
template<typename TItem> class FileIndex
{ {
private: private:
struct DirectoryStats struct DirectoryStats
@ -40,8 +40,8 @@ private:
std::vector<std::string> const Files; std::vector<std::string> const Files;
ScanResult(DirectoryStats stats, std::vector<std::string> files) ScanResult(DirectoryStats stats, std::vector<std::string> files)
: Stats(stats), : Stats(stats)
Files(files) , Files(files)
{ {
} }
}; };
@ -79,18 +79,19 @@ public:
* @param pattern The search pattern for indexing files. * @param pattern The search pattern for indexing files.
* @param paths A list of search directories. * @param paths A list of search directories.
*/ */
FileIndex(std::string name, FileIndex(
std::string name,
uint32_t magicNumber, uint32_t magicNumber,
uint8_t version, uint8_t version,
std::string indexPath, std::string indexPath,
std::string pattern, std::string pattern,
std::vector<std::string> paths) : std::vector<std::string> paths)
_name(name), : _name(name)
_magicNumber(magicNumber), , _magicNumber(magicNumber)
_version(version), , _version(version)
_indexPath(indexPath), , _indexPath(indexPath)
_pattern(pattern), , _pattern(pattern)
SearchPaths(paths) , SearchPaths(paths)
{ {
} }
@ -162,9 +163,8 @@ private:
stats.TotalFiles++; stats.TotalFiles++;
stats.TotalFileSize += fileInfo->Size; stats.TotalFileSize += fileInfo->Size;
stats.FileDateModifiedChecksum ^= stats.FileDateModifiedChecksum
(uint32_t)(fileInfo->LastModified >> 32) ^ ^= (uint32_t)(fileInfo->LastModified >> 32) ^ (uint32_t)(fileInfo->LastModified & 0xFFFFFFFF);
(uint32_t)(fileInfo->LastModified & 0xFFFFFFFF);
stats.FileDateModifiedChecksum = ror32(stats.FileDateModifiedChecksum, 5); stats.FileDateModifiedChecksum = ror32(stats.FileDateModifiedChecksum, 5);
stats.PathChecksum += GetPathChecksum(path); stats.PathChecksum += GetPathChecksum(path);
} }
@ -173,7 +173,8 @@ private:
return ScanResult(stats, files); return ScanResult(stats, files);
} }
void BuildRange(int32_t language, void BuildRange(
int32_t language,
const ScanResult& scanResult, const ScanResult& scanResult,
size_t rangeStart, size_t rangeStart,
size_t rangeEnd, size_t rangeEnd,
@ -221,9 +222,7 @@ private:
std::atomic<size_t> processed = ATOMIC_VAR_INIT(0); std::atomic<size_t> processed = ATOMIC_VAR_INIT(0);
auto reportProgress = auto reportProgress = [&]() {
[&]()
{
const size_t completed = processed; const size_t completed = processed;
Console::WriteFormat("File %5d of %d, done %3d%%\r", completed, totalCount, completed * 100 / totalCount); Console::WriteFormat("File %5d of %d, done %3d%%\r", completed, totalCount, completed * 100 / totalCount);
}; };
@ -237,7 +236,8 @@ private:
auto& items = containers.emplace_back(); auto& items = containers.emplace_back();
jobPool.AddTask(std::bind(&FileIndex<TItem>::BuildRange, jobPool.AddTask(std::bind(
&FileIndex<TItem>::BuildRange,
this, this,
language, language,
std::cref(scanResult), std::cref(scanResult),
@ -280,15 +280,11 @@ private:
// Read header, check if we need to re-scan // Read header, check if we need to re-scan
auto header = fs.ReadValue<FileIndexHeader>(); auto header = fs.ReadValue<FileIndexHeader>();
if (header.HeaderSize == sizeof(FileIndexHeader) && if (header.HeaderSize == sizeof(FileIndexHeader) && header.MagicNumber == _magicNumber
header.MagicNumber == _magicNumber && && header.VersionA == FILE_INDEX_VERSION && header.VersionB == _version && header.LanguageId == language
header.VersionA == FILE_INDEX_VERSION && && header.Stats.TotalFiles == stats.TotalFiles && header.Stats.TotalFileSize == stats.TotalFileSize
header.VersionB == _version && && header.Stats.FileDateModifiedChecksum == stats.FileDateModifiedChecksum
header.LanguageId == language && && header.Stats.PathChecksum == stats.PathChecksum)
header.Stats.TotalFiles == stats.TotalFiles &&
header.Stats.TotalFileSize == stats.TotalFileSize &&
header.Stats.FileDateModifiedChecksum == stats.FileDateModifiedChecksum &&
header.Stats.PathChecksum == stats.PathChecksum)
{ {
items.reserve(header.NumItems); items.reserve(header.NumItems);
// Directory is the same, just read the saved items // Directory is the same, just read the saved items

View File

@ -16,23 +16,24 @@
#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
#include <dirent.h> #include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h> #include <unistd.h>
#elif defined(_WIN32) #elif defined(_WIN32)
// Windows needs this for widechar <-> utf8 conversion utils // Windows needs this for widechar <-> utf8 conversion utils
#include "../localisation/Language.h" #include "../localisation/Language.h"
#endif #endif
#include <memory>
#include <stack>
#include <string>
#include <vector>
#include "FileScanner.h" #include "FileScanner.h"
#include "Memory.hpp" #include "Memory.hpp"
#include "Path.hpp" #include "Path.hpp"
#include "String.hpp" #include "String.hpp"
#include <memory>
#include <stack>
#include <string>
#include <vector>
enum class DIRECTORY_CHILD_TYPE enum class DIRECTORY_CHILD_TYPE
{ {
DC_DIRECTORY, DC_DIRECTORY,
@ -207,8 +208,7 @@ private:
start = ch + 1; start = ch + 1;
} }
ch++; ch++;
} } while (c != '\0');
while (c != '\0');
patterns.shrink_to_fit(); patterns.shrink_to_fit();
return patterns; return patterns;
@ -236,14 +236,12 @@ public:
{ {
do do
{ {
if (lstrcmpW(findData.cFileName, L".") != 0 && if (lstrcmpW(findData.cFileName, L".") != 0 && lstrcmpW(findData.cFileName, L"..") != 0)
lstrcmpW(findData.cFileName, L"..") != 0)
{ {
DirectoryChild child = CreateChild(&findData); DirectoryChild child = CreateChild(&findData);
children.push_back(child); children.push_back(child);
} }
} } while (FindNextFileW(hFile, &findData));
while (FindNextFileW(hFile, &findData));
FindClose(hFile); FindClose(hFile);
} }
@ -267,7 +265,8 @@ private:
{ {
result.Type = DIRECTORY_CHILD_TYPE::DC_FILE; result.Type = DIRECTORY_CHILD_TYPE::DC_FILE;
result.Size = ((uint64_t)child->nFileSizeHigh << 32ULL) | (uint64_t)child->nFileSizeLow; 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; return result;
} }
@ -294,8 +293,7 @@ public:
for (int32_t i = 0; i < count; i++) for (int32_t i = 0; i < count; i++)
{ {
const struct dirent* node = namelist[i]; const struct dirent* node = namelist[i];
if (!String::Equals(node->d_name, ".") && if (!String::Equals(node->d_name, ".") && !String::Equals(node->d_name, ".."))
!String::Equals(node->d_name, ".."))
{ {
DirectoryChild child = CreateChild(path.c_str(), node); DirectoryChild child = CreateChild(path.c_str(), node);
children.push_back(child); children.push_back(child);
@ -330,7 +328,9 @@ private:
String::Set(path, pathSize, directory); String::Set(path, pathSize, directory);
Path::Append(path, pathSize, node->d_name); Path::Append(path, pathSize, node->d_name);
struct stat statInfo{}; struct stat statInfo
{
};
int32_t statRes = stat(path, &statInfo); int32_t statRes = stat(path, &statInfo);
if (statRes != -1) if (statRes != -1)
{ {
@ -370,9 +370,8 @@ void Path::QueryDirectory(QueryDirectoryResult * result, const std::string &patt
result->TotalFiles++; result->TotalFiles++;
result->TotalFileSize += fileInfo->Size; result->TotalFileSize += fileInfo->Size;
result->FileDateModifiedChecksum ^= result->FileDateModifiedChecksum
(uint32_t)(fileInfo->LastModified >> 32) ^ ^= (uint32_t)(fileInfo->LastModified >> 32) ^ (uint32_t)(fileInfo->LastModified & 0xFFFFFFFF);
(uint32_t)(fileInfo->LastModified & 0xFFFFFFFF);
result->FileDateModifiedChecksum = ror32(result->FileDateModifiedChecksum, 5); result->FileDateModifiedChecksum = ror32(result->FileDateModifiedChecksum, 5);
result->PathChecksum += GetPathChecksum(path); result->PathChecksum += GetPathChecksum(path);
} }
@ -422,7 +421,8 @@ static bool MatchWildcard(const utf8 * fileName, const utf8 * pattern)
{ {
while (*fileName != '\0') while (*fileName != '\0')
{ {
switch (*pattern) { switch (*pattern)
{
case '?': case '?':
if (*fileName == '.') if (*fileName == '.')
{ {
@ -433,8 +433,7 @@ static bool MatchWildcard(const utf8 * fileName, const utf8 * pattern)
do do
{ {
pattern++; pattern++;
} } while (*pattern == '*');
while (*pattern == '*');
if (*pattern == '\0') if (*pattern == '\0')
{ {
return false; return false;

View File

@ -9,9 +9,10 @@
#pragma once #pragma once
#include "../common.h"
#include <string> #include <string>
#include <vector> #include <vector>
#include "../common.h"
struct FileInfo struct FileInfo
{ {

View File

@ -10,12 +10,11 @@
#pragma once #pragma once
#include "../common.h" #include "../common.h"
#include "../localisation/Language.h"
#include "IStream.hpp" #include "IStream.hpp"
#include "Math.hpp" #include "Math.hpp"
#include "String.hpp" #include "String.hpp"
#include "../localisation/Language.h"
enum enum
{ {
FILE_MODE_OPEN, FILE_MODE_OPEN,
@ -37,15 +36,16 @@ private:
uint64_t _fileSize = 0; uint64_t _fileSize = 0;
public: public:
FileStream(const std::string &path, int32_t fileMode) : FileStream(const std::string& path, int32_t fileMode)
FileStream(path.c_str(), fileMode) : FileStream(path.c_str(), fileMode)
{ {
} }
FileStream(const utf8* path, int32_t fileMode) FileStream(const utf8* path, int32_t fileMode)
{ {
const char* mode; const char* mode;
switch (fileMode) { switch (fileMode)
{
case FILE_MODE_OPEN: case FILE_MODE_OPEN:
mode = "rb"; mode = "rb";
_canRead = true; _canRead = true;
@ -98,10 +98,19 @@ public:
} }
} }
bool CanRead() const override { return _canRead; } bool CanRead() const override
bool CanWrite() const override { return _canWrite; } {
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 uint64_t GetPosition() const override
{ {
#if defined(_MSC_VER) #if defined(_MSC_VER)
@ -121,7 +130,8 @@ public:
void Seek(int64_t offset, int32_t origin) override void Seek(int64_t offset, int32_t origin) override
{ {
#if defined(_MSC_VER) #if defined(_MSC_VER)
switch (origin) { switch (origin)
{
case STREAM_SEEK_BEGIN: case STREAM_SEEK_BEGIN:
_fseeki64(_file, offset, SEEK_SET); _fseeki64(_file, offset, SEEK_SET);
break; break;
@ -133,7 +143,8 @@ public:
break; break;
} }
#elif (defined(__APPLE__) && defined(__MACH__)) || defined(__ANDROID__) || defined(__OpenBSD__) || defined(__FreeBSD__) #elif (defined(__APPLE__) && defined(__MACH__)) || defined(__ANDROID__) || defined(__OpenBSD__) || defined(__FreeBSD__)
switch (origin) { switch (origin)
{
case STREAM_SEEK_BEGIN: case STREAM_SEEK_BEGIN:
fseeko(_file, offset, SEEK_SET); fseeko(_file, offset, SEEK_SET);
break; break;
@ -145,7 +156,8 @@ public:
break; break;
} }
#else #else
switch (origin) { switch (origin)
{
case STREAM_SEEK_BEGIN: case STREAM_SEEK_BEGIN:
fseeko64(_file, offset, SEEK_SET); fseeko64(_file, offset, SEEK_SET);
break; break;

View File

@ -70,7 +70,8 @@ namespace Guard
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(ASSERTION_MESSAGE);
Console::Error::WriteLine("Version: %s", gVersionInfoFull); Console::Error::WriteLine("Version: %s", gVersionInfoFull);
@ -87,7 +88,8 @@ namespace Guard
Debug::Break(); Debug::Break();
#endif #endif
switch (_assertBehaviour) { switch (_assertBehaviour)
{
case ASSERT_BEHAVIOUR::ABORT: case ASSERT_BEHAVIOUR::ABORT:
abort(); abort();
default: default:

View File

@ -15,7 +15,11 @@
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 enum class ASSERT_BEHAVIOUR
{ {
@ -37,8 +41,7 @@ namespace Guard
void Fail(const char* message = nullptr, ...); void Fail(const char* message = nullptr, ...);
void Fail_VA(const char* message, va_list args); void Fail_VA(const char* message, va_list args);
template<typename T> template<typename T> static void ArgumentNotNull(T* argument, const char* message = nullptr, ...)
static void ArgumentNotNull(T * argument, const char * message = nullptr, ...)
{ {
va_list args; va_list args;
va_start(args, message); va_start(args, message);
@ -46,8 +49,7 @@ namespace Guard
va_end(args); va_end(args);
} }
template<typename T> template<typename T> static void ArgumentNotNull(const std::shared_ptr<T>& argument, const char* message = nullptr, ...)
static void ArgumentNotNull(const std::shared_ptr<T>& argument, const char * message = nullptr, ...)
{ {
va_list args; va_list args;
va_start(args, message); va_start(args, message);
@ -55,8 +57,7 @@ namespace Guard
va_end(args); va_end(args);
} }
template<typename T> template<typename T> static void ArgumentInRange(T argument, T min, T max, const char* message = nullptr, ...)
static void ArgumentInRange(T argument, T min, T max, const char * message = nullptr, ...)
{ {
va_list args; va_list args;
va_start(args, message); va_start(args, message);

View File

@ -7,11 +7,13 @@
* OpenRCT2 is licensed under the GNU General Public License version 3. * OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/ *****************************************************************************/
#include <vector>
#include "IStream.hpp" #include "IStream.hpp"
#include "Memory.hpp" #include "Memory.hpp"
#include "String.hpp" #include "String.hpp"
#include <vector>
utf8* IStream::ReadString() utf8* IStream::ReadString()
{ {
std::vector<utf8> result; std::vector<utf8> result;

View File

@ -9,14 +9,16 @@
#pragma once #pragma once
#include "../common.h"
#include "Memory.hpp"
#include <istream> #include <istream>
#include <stdexcept> #include <stdexcept>
#include <string> #include <string>
#include <vector> #include <vector>
#include "../common.h"
#include "Memory.hpp"
enum { enum
{
STREAM_SEEK_BEGIN, STREAM_SEEK_BEGIN,
STREAM_SEEK_CURRENT, STREAM_SEEK_CURRENT,
STREAM_SEEK_END STREAM_SEEK_END
@ -30,7 +32,9 @@ interface IStream
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
// Interface methods // Interface methods
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
virtual ~IStream() { } virtual ~IStream()
{
}
virtual bool CanRead() const abstract; virtual bool CanRead() const abstract;
virtual bool CanWrite() const abstract; virtual bool CanWrite() const abstract;
@ -52,8 +56,7 @@ interface IStream
/** /**
* Reads the size of the given type from the stream directly into the given address. * Reads the size of the given type from the stream directly into the given address.
*/ */
template<typename T> template<typename T> void Read(T * value)
void Read(T * value)
{ {
Read(value, sizeof(T)); 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. * Writes the size of the given type to the stream directly from the given address.
*/ */
template<typename T> template<typename T> void Write(const T* value)
void Write(const T * value)
{ {
Write(value, sizeof(T)); 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) * Reads the given type from the stream. Use this only for small types (e.g. int8_t, int64_t, double)
*/ */
template<typename T> template<typename T> T ReadValue()
T ReadValue()
{ {
T buffer; T buffer;
Read(&buffer); Read(&buffer);
@ -81,22 +82,19 @@ interface IStream
/** /**
* Writes the given type to the stream. Use this only for small types (e.g. int8_t, int64_t, double) * Writes the given type to the stream. Use this only for small types (e.g. int8_t, int64_t, double)
*/ */
template<typename T> template<typename T> void WriteValue(const T value)
void WriteValue(const T value)
{ {
Write(&value); Write(&value);
} }
template<typename T> template<typename T> T* ReadArray(size_t count)
T * ReadArray(size_t count)
{ {
T* buffer = Memory::AllocateArray<T>(count); T* buffer = Memory::AllocateArray<T>(count);
Read(buffer, sizeof(T) * count); Read(buffer, sizeof(T) * count);
return buffer; return buffer;
} }
template<typename T> template<typename T> void WriteArray(T * buffer, size_t count)
void WriteArray(T * buffer, size_t count)
{ {
Write(buffer, sizeof(T) * count); Write(buffer, sizeof(T) * count);
} }
@ -110,11 +108,13 @@ interface IStream
class IOException : public std::runtime_error class IOException : public std::runtime_error
{ {
public: public:
explicit IOException(const std::string &message) : std::runtime_error(message) { } explicit IOException(const std::string& message)
: std::runtime_error(message)
{
}
}; };
template<typename T> template<typename T> class ivstream : public std::istream
class ivstream : public std::istream
{ {
private: private:
class vector_streambuf : public std::basic_streambuf<char, std::char_traits<char>> class vector_streambuf : public std::basic_streambuf<char, std::char_traits<char>>
@ -130,8 +130,8 @@ private:
public: public:
ivstream(const std::vector<T>& vec) ivstream(const std::vector<T>& vec)
: std::istream(&_streambuf), : std::istream(&_streambuf)
_streambuf(vec) , _streambuf(vec)
{ {
} }
}; };

View File

@ -9,17 +9,19 @@
#pragma warning(disable : 4611) // interaction between '_setjmp' and C++ object destruction is non-portable #pragma warning(disable : 4611) // interaction between '_setjmp' and C++ object destruction is non-portable
#include <algorithm>
#include <fstream>
#include <stdexcept>
#include <unordered_map>
#include <png.h>
#include "IStream.hpp"
#include "Guard.hpp"
#include "Imaging.h" #include "Imaging.h"
#include "../drawing/Drawing.h"
#include "Guard.hpp"
#include "IStream.hpp"
#include "Memory.hpp" #include "Memory.hpp"
#include "String.hpp" #include "String.hpp"
#include "../drawing/Drawing.h"
#include <algorithm>
#include <fstream>
#include <png.h>
#include <stdexcept>
#include <unordered_map>
namespace Imaging namespace Imaging
{ {
@ -348,4 +350,4 @@ namespace Imaging
throw std::runtime_error(EXCEPTION_IMAGE_FORMAT_UNKNOWN); throw std::runtime_error(EXCEPTION_IMAGE_FORMAT_UNKNOWN);
} }
} }
} } // namespace Imaging

View File

@ -9,13 +9,14 @@
#pragma once #pragma once
#include "../common.h"
#include "../drawing/Drawing.h"
#include <functional> #include <functional>
#include <istream> #include <istream>
#include <memory> #include <memory>
#include <string_view> #include <string_view>
#include <vector> #include <vector>
#include "../common.h"
#include "../drawing/Drawing.h"
struct rct_drawpixelinfo; struct rct_drawpixelinfo;
struct rct_palette; struct rct_palette;
@ -60,4 +61,4 @@ namespace Imaging
void WriteToFile(const std::string_view& path, const Image& image, IMAGE_FORMAT format = IMAGE_FORMAT::AUTOMATIC); void WriteToFile(const std::string_view& path, const Image& image, IMAGE_FORMAT format = IMAGE_FORMAT::AUTOMATIC);
void SetReader(IMAGE_FORMAT format, ImageReaderFunc impl); void SetReader(IMAGE_FORMAT format, ImageReaderFunc impl);
} } // namespace Imaging

View File

@ -27,8 +27,8 @@ private:
const std::function<void()> CompletionFn; const std::function<void()> CompletionFn;
TaskData(std::function<void()> workFn, std::function<void()> completionFn) TaskData(std::function<void()> workFn, std::function<void()> completionFn)
: WorkFn(workFn), : WorkFn(workFn)
CompletionFn(completionFn) , CompletionFn(completionFn)
{ {
} }
}; };
@ -86,11 +86,7 @@ public:
while (true) while (true)
{ {
// Wait for the queue to become empty or having completed tasks. // Wait for the queue to become empty or having completed tasks.
_condComplete.wait(lock, [this]() _condComplete.wait(lock, [this]() { return (_pending.empty() && _processing == 0) || !_completed.empty(); });
{
return (_pending.empty() && _processing == 0) ||
!_completed.empty();
});
// Dispatch all completion callbacks if there are any. // Dispatch all completion callbacks if there are any.
while (!_completed.empty()) 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 everything is empty and no more work has to be done we can stop waiting.
if (_completed.empty() && if (_completed.empty() && _pending.empty() && _processing == 0)
_pending.empty() &&
_processing == 0)
{ {
break; break;
} }
@ -139,11 +133,7 @@ private:
do do
{ {
// Wait for work or cancelation. // Wait for work or cancelation.
_condPending.wait(lock, _condPending.wait(lock, [this]() { return _shouldStop || !_pending.empty(); });
[this]()
{
return _shouldStop || !_pending.empty();
});
if (!_pending.empty()) if (!_pending.empty())
{ {
@ -163,7 +153,6 @@ private:
_processing--; _processing--;
_condComplete.notify_one(); _condComplete.notify_one();
} }
} } while (!_shouldStop);
while(!_shouldStop);
} }
}; };

View File

@ -7,8 +7,9 @@
* OpenRCT2 is licensed under the GNU General Public License version 3. * OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/ *****************************************************************************/
#include "FileStream.hpp"
#include "Json.hpp" #include "Json.hpp"
#include "FileStream.hpp"
#include "Memory.hpp" #include "Memory.hpp"
#include "String.hpp" #include "String.hpp"

View File

@ -9,11 +9,11 @@
#pragma once #pragma once
#include "../common.h"
#include <jansson.h>
#include <stdexcept> #include <stdexcept>
#include <string> #include <string>
#include <jansson.h>
#include "../common.h"
namespace Json namespace Json
{ {
@ -24,7 +24,7 @@ namespace Json
void WriteToFile(const utf8* path, const json_t* json, size_t flags = 0); 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 class JsonException final : public std::runtime_error
{ {
@ -32,9 +32,13 @@ private:
json_error_t _jsonError = {}; json_error_t _jsonError = {};
public: 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; _jsonError = *jsonError;
} }

View File

@ -16,17 +16,17 @@
*/ */
namespace Math namespace Math
{ {
template<typename T> template<typename T> static T Clamp(T low, T x, T high)
static T Clamp(T low, T x, T high)
{ {
return (std::min)((std::max)(low, x), high); return (std::min)((std::max)(low, x), high);
} }
template<typename T> template<typename T> static T Sign(T x)
static T Sign(T x)
{ {
if (x < 0) return -1; if (x < 0)
if (x > 0) return 1; return -1;
if (x > 0)
return 1;
return 0; return 0;
} }
} // namespace Math } // namespace Math

View File

@ -9,43 +9,40 @@
#pragma once #pragma once
#include "../common.h"
#include "Guard.hpp"
#include <cstdlib> #include <cstdlib>
#include <cstring> #include <cstring>
#include <typeinfo> #include <typeinfo>
#include "../common.h"
#include "Guard.hpp"
/** /**
* Utility methods for memory management. Typically helpers and wrappers around the C standard library. * Utility methods for memory management. Typically helpers and wrappers around the C standard library.
*/ */
namespace Memory namespace Memory
{ {
template<typename T> template<typename T> static T* Allocate()
static T * Allocate()
{ {
T* result = (T*)malloc(sizeof(T)); T* result = (T*)malloc(sizeof(T));
Guard::ArgumentNotNull(result, "Failed to allocate %u bytes for %s", sizeof(T), typeid(T).name()); Guard::ArgumentNotNull(result, "Failed to allocate %u bytes for %s", sizeof(T), typeid(T).name());
return result; return result;
} }
template<typename T> template<typename T> static T* Allocate(size_t size)
static T * Allocate(size_t size)
{ {
T* result = (T*)malloc(size); T* result = (T*)malloc(size);
Guard::ArgumentNotNull(result, "Failed to allocate %u bytes for %s", size, typeid(T).name()); Guard::ArgumentNotNull(result, "Failed to allocate %u bytes for %s", size, typeid(T).name());
return result; return result;
} }
template<typename T> template<typename T> static T* AllocateArray(size_t count)
static T * AllocateArray(size_t count)
{ {
T* result = (T*)malloc(count * sizeof(T)); 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)); Guard::ArgumentNotNull(result, "Failed to allocate array of %u * %s (%u bytes)", count, typeid(T).name(), sizeof(T));
return result; return result;
} }
template<typename T> template<typename T> static T* Reallocate(T* ptr, size_t size)
static T * Reallocate(T * ptr, size_t size)
{ {
T* result; T* result;
if (ptr == nullptr) if (ptr == nullptr)
@ -60,8 +57,7 @@ namespace Memory
return result; return result;
} }
template<typename T> template<typename T> static T* ReallocateArray(T* ptr, size_t count)
static T * ReallocateArray(T * ptr, size_t count)
{ {
T* result; T* result;
if (ptr == nullptr) if (ptr == nullptr)
@ -72,18 +68,17 @@ namespace Memory
{ {
result = (T*)realloc((void*)ptr, count * sizeof(T)); 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; return result;
} }
template<typename T> template<typename T> static void Free(T* ptr)
static void Free(T * ptr)
{ {
free((void*)ptr); free((void*)ptr);
} }
template<typename T> template<typename T> static void FreeArray(T* ptr, size_t count)
static void FreeArray(T * ptr, size_t count)
{ {
for (size_t i = 0; i < count; i++) for (size_t i = 0; i < count; i++)
{ {

View File

@ -7,11 +7,13 @@
* OpenRCT2 is licensed under the GNU General Public License version 3. * OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/ *****************************************************************************/
#include <algorithm> #include "MemoryStream.h"
#include <cstring>
#include "Math.hpp" #include "Math.hpp"
#include "Memory.hpp" #include "Memory.hpp"
#include "MemoryStream.h"
#include <algorithm>
#include <cstring>
MemoryStream::MemoryStream(const MemoryStream& copy) MemoryStream::MemoryStream(const MemoryStream& copy)
{ {
@ -105,7 +107,8 @@ void MemoryStream::SetPosition(uint64_t position)
void MemoryStream::Seek(int64_t offset, int32_t origin) void MemoryStream::Seek(int64_t offset, int32_t origin)
{ {
uint64_t newPosition; uint64_t newPosition;
switch (origin) { switch (origin)
{
default: default:
case STREAM_SEEK_BEGIN: case STREAM_SEEK_BEGIN:
newPosition = offset; newPosition = offset;

View File

@ -17,7 +17,7 @@ namespace MEMORY_ACCESS
constexpr uint8_t READ = 1 << 0; constexpr uint8_t READ = 1 << 0;
constexpr uint8_t WRITE = 1 << 1; constexpr uint8_t WRITE = 1 << 1;
constexpr uint8_t OWNER = 1 << 2; 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. * A stream for reading and writing to a buffer in memory. By default this buffer can grow.

View File

@ -10,10 +10,10 @@
#pragma once #pragma once
#include "../common.h" #include "../common.h"
#include <cstddef> #include <cstddef>
template<typename T> template<typename T> struct Nullable
struct Nullable
{ {
public: public:
Nullable() Nullable()

View File

@ -12,16 +12,15 @@
#include <dirent.h> #include <dirent.h>
#endif #endif
#include "../localisation/Language.h"
#include "../platform/platform.h" #include "../platform/platform.h"
#include "../util/Util.h" #include "../util/Util.h"
#include "../localisation/Language.h"
#include "File.h" #include "File.h"
#include "Math.hpp" #include "Math.hpp"
#include "Memory.hpp" #include "Memory.hpp"
#include "Path.hpp" #include "Path.hpp"
#include "Util.hpp"
#include "String.hpp" #include "String.hpp"
#include "Util.hpp"
namespace Path namespace Path
{ {
@ -58,10 +57,7 @@ namespace Path
utf8* GetDirectory(utf8* buffer, size_t bufferSize, const utf8* path) utf8* GetDirectory(utf8* buffer, size_t bufferSize, const utf8* path)
{ {
auto lastPathSepIndex = std::max( auto lastPathSepIndex = std::max(String::LastIndexOf(path, *PATH_SEPARATOR), String::LastIndexOf(path, '/'));
String::LastIndexOf(path, *PATH_SEPARATOR),
String::LastIndexOf(path, '/')
);
if (lastPathSepIndex < 0) if (lastPathSepIndex < 0)
{ {
return String::Set(buffer, bufferSize, String::Empty); return String::Set(buffer, bufferSize, String::Empty);
@ -99,9 +95,7 @@ namespace Path
} }
} }
return lastPathSeparator == nullptr ? return lastPathSeparator == nullptr ? path : lastPathSeparator + 1;
path :
lastPathSeparator + 1;
} }
std::string GetFileNameWithoutExtension(const std::string& path) std::string GetFileNameWithoutExtension(const std::string& path)

View File

@ -9,16 +9,16 @@
#pragma once #pragma once
#include <string>
#include "../common.h" #include "../common.h"
#include <string>
namespace Path namespace Path
{ {
utf8* Append(utf8* buffer, size_t bufferSize, const utf8* src); utf8* Append(utf8* buffer, size_t bufferSize, const utf8* src);
std::string Combine(const std::string& a, const std::string& b); std::string Combine(const std::string& a, const std::string& b);
template<typename... Args> template<typename... Args> static std::string Combine(const std::string& a, const std::string& b, Args... args)
static std::string Combine(const std::string &a, const std::string &b, Args... args)
{ {
return Combine(a, Combine(b, args...)); return Combine(a, Combine(b, args...));
} }

View File

@ -28,15 +28,14 @@ namespace OpenRCT2
/** /**
* Class which can wrap a function in an IRegistration. * Class which can wrap a function in an IRegistration.
*/ */
template<typename T> template<typename T> struct CallbackRegistration : public IRegistration
struct CallbackRegistration : public IRegistration
{ {
private: private:
T _callback; T _callback;
public: public:
CallbackRegistration(T callback) : CallbackRegistration(T callback)
_callback(callback) : _callback(callback)
{ {
} }
@ -51,10 +50,9 @@ namespace OpenRCT2
* Creates a new IRegistration which when deleted, calls the given * Creates a new IRegistration which when deleted, calls the given
* function. * function.
*/ */
template<typename T> template<typename T> static IRegistration* Create(T unregisterCallback)
static IRegistration * Create(T unregisterCallback)
{ {
return new CallbackRegistration<T>(unregisterCallback); return new CallbackRegistration<T>(unregisterCallback);
} }
}; };
} } // namespace OpenRCT2

View File

@ -34,7 +34,6 @@
#include "../localisation/ConversionTables.h" #include "../localisation/ConversionTables.h"
#include "../localisation/Language.h" #include "../localisation/Language.h"
#include "../util/Util.h" #include "../util/Util.h"
#include "Math.hpp" #include "Math.hpp"
#include "Memory.hpp" #include "Memory.hpp"
#include "String.hpp" #include "String.hpp"
@ -44,8 +43,10 @@ namespace String
{ {
std::string ToStd(const utf8* str) std::string ToStd(const utf8* str)
{ {
if (str == nullptr) return std::string(); if (str == nullptr)
else return std::string(str); 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)
@ -140,9 +141,12 @@ namespace String
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 == b)
if (a == nullptr) a = ""; return 0;
if (b == nullptr) b = ""; if (a == nullptr)
a = "";
if (b == nullptr)
b = "";
if (ignoreCase) if (ignoreCase)
{ {
return _stricmp(a, b); return _stricmp(a, b);
@ -160,8 +164,10 @@ namespace String
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 == b)
if (a == nullptr || b == nullptr) return false; return true;
if (a == nullptr || b == nullptr)
return false;
if (ignoreCase) if (ignoreCase)
{ {
@ -271,7 +277,8 @@ namespace String
for (size_t i = 0; i < minSize; i++) for (size_t i = 0; i < minSize; i++)
{ {
*dst++ = *src; *dst++ = *src;
if (*src == '\0') break; if (*src == '\0')
break;
src++; src++;
} }
*dst = '\0'; *dst = '\0';
@ -365,7 +372,8 @@ namespace String
size_t i; size_t i;
for (i = 0; i < bufferSize; i++) for (i = 0; i < bufferSize; i++)
{ {
if (*dst == '\0') break; if (*dst == '\0')
break;
dst++; dst++;
} }
@ -438,8 +446,7 @@ namespace String
} }
results.push_back(value); results.push_back(value);
index = nextIndex + delimiter.size(); index = nextIndex + delimiter.size();
} } while (nextIndex != SIZE_MAX);
while (nextIndex != SIZE_MAX);
} }
return results; return results;
} }
@ -503,8 +510,7 @@ namespace String
ch = nextCh; ch = nextCh;
} }
if (firstNonWhitespace != nullptr && if (firstNonWhitespace != nullptr && firstNonWhitespace != str)
firstNonWhitespace != str)
{ {
// Take multibyte characters into account: use the last byte of the // Take multibyte characters into account: use the last byte of the
// current character. // current character.

View File

@ -9,11 +9,12 @@
#pragma once #pragma once
#include "../common.h"
#include <cstdarg> #include <cstdarg>
#include <cstddef> #include <cstddef>
#include <string> #include <string>
#include <vector> #include <vector>
#include "../common.h"
namespace CODE_PAGE namespace CODE_PAGE
{ {
@ -109,4 +110,4 @@ namespace String
* Returns an uppercased version of a UTF-8 string. * Returns an uppercased version of a UTF-8 string.
*/ */
std::string ToUpper(const std::string_view& src); std::string ToUpper(const std::string_view& src);
} } // namespace String

View File

@ -9,14 +9,14 @@
#pragma once #pragma once
#include <algorithm>
#include <string>
#include "../common.h" #include "../common.h"
#include "Math.hpp" #include "Math.hpp"
#include "Memory.hpp" #include "Memory.hpp"
#include "String.hpp" #include "String.hpp"
#include <algorithm>
#include <string>
/** /**
* Class for constructing strings efficiently. A buffer is automatically allocated and reallocated when characters or strings * 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. * are appended. Use GetString to copy the current state of the string builder to a new fire-and-forget string.
@ -148,19 +148,26 @@ public:
const utf8* GetBuffer() const const utf8* GetBuffer() const
{ {
// buffer may be null, so return an immutable empty string // buffer may be null, so return an immutable empty string
if (_buffer == nullptr) return ""; if (_buffer == nullptr)
return "";
return _buffer; return _buffer;
} }
/** /**
* Gets the amount of allocated memory for the string 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. * Gets the length of the current string.
*/ */
size_t GetLength() const { return _length; } size_t GetLength() const
{
return _length;
}
private: private:
utf8* _buffer = nullptr; utf8* _buffer = nullptr;
@ -169,7 +176,8 @@ private:
void EnsureCapacity(size_t capacity) void EnsureCapacity(size_t capacity)
{ {
if (_capacity > capacity) return; if (_capacity > capacity)
return;
_capacity = std::max((size_t)8, _capacity); _capacity = std::max((size_t)8, _capacity);
while (_capacity < capacity) while (_capacity < capacity)

View File

@ -37,7 +37,8 @@ public:
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); codepoint_t codepoint = String::GetNextCodepoint(_current);
*outCodepoint = codepoint; *outCodepoint = codepoint;
@ -46,7 +47,8 @@ public:
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); codepoint_t codepoint = String::GetNextCodepoint(_current, &_current);
*outCodepoint = codepoint; *outCodepoint = codepoint;

View File

@ -15,11 +15,10 @@
/** /**
* Common utility functions. * Common utility functions.
*/ */
namespace Util { namespace Util
{
// Based on http://www.g-truc.net/post-0708.html // Based on http://www.g-truc.net/post-0708.html
template <typename T, size_t N> template<typename T, size_t N> static constexpr size_t CountOf(T const (&)[N]) noexcept
static constexpr size_t CountOf(T const (&)[N]) noexcept
{ {
return N; return N;
} }

View File

@ -8,10 +8,12 @@
*****************************************************************************/ *****************************************************************************/
#ifndef __ANDROID__ #ifndef __ANDROID__
#include <zip.h>
#include "IStream.hpp"
#include "Zip.h" #include "Zip.h"
#include "IStream.hpp"
#include <zip.h>
class ZipArchive final : public IZipArchive class ZipArchive final : public IZipArchive
{ {
private: private:

View File

@ -9,17 +9,20 @@
#pragma once #pragma once
#include "../common.h"
#include <memory> #include <memory>
#include <string_view> #include <string_view>
#include <vector> #include <vector>
#include "../common.h"
/** /**
* Represents a zip file. * Represents a zip file.
*/ */
interface IZipArchive interface IZipArchive
{ {
virtual ~IZipArchive() { } virtual ~IZipArchive()
{
}
virtual size_t GetNumFiles() const abstract; virtual size_t GetNumFiles() const abstract;
virtual std::string GetFileName(size_t index) const abstract; virtual std::string GetFileName(size_t index) const abstract;
@ -47,4 +50,4 @@ namespace Zip
{ {
std::unique_ptr<IZipArchive> Open(const std::string_view& path, ZIP_ACCESS zipAccess); std::unique_ptr<IZipArchive> Open(const std::string_view& path, ZIP_ACCESS zipAccess);
std::unique_ptr<IZipArchive> TryOpen(const std::string_view& path, ZIP_ACCESS zipAccess); std::unique_ptr<IZipArchive> TryOpen(const std::string_view& path, ZIP_ACCESS zipAccess);
} } // namespace Zip

View File

@ -9,11 +9,12 @@
#ifdef __ANDROID__ #ifdef __ANDROID__
#include <SDL.h>
#include <jni.h>
#include "IStream.hpp" #include "IStream.hpp"
#include "Zip.h" #include "Zip.h"
#include <SDL.h>
#include <jni.h>
class ZipArchive final : public IZipArchive class ZipArchive final : public IZipArchive
{ {
private: private:
@ -66,8 +67,7 @@ public:
JNIEnv* env = (JNIEnv*)SDL_AndroidGetJNIEnv(); JNIEnv* env = (JNIEnv*)SDL_AndroidGetJNIEnv();
jclass zipClass = env->GetObjectClass(_zip); jclass zipClass = env->GetObjectClass(_zip);
jmethodID fileNameMethod = env->GetMethodID(zipClass, "getFileName", jmethodID fileNameMethod = env->GetMethodID(zipClass, "getFileName", "(I)Ljava/lang/String;");
"(I)Ljava/lang/String;");
jstring jniString = (jstring)env->CallObjectMethod(_zip, fileNameMethod, (jint)index); jstring jniString = (jstring)env->CallObjectMethod(_zip, fileNameMethod, (jint)index);
@ -147,18 +147,14 @@ namespace Zip
} }
return result; return result;
} }
} } // namespace Zip
extern "C" { extern "C" {
JNIEXPORT jlong JNICALL JNIEXPORT jlong JNICALL Java_website_openrct2_ZipArchive_allocBytes(JNIEnv* env, jclass, jbyteArray input, jint numBytes);
Java_website_openrct2_ZipArchive_allocBytes(JNIEnv *env, jclass, jbyteArray input,
jint numBytes);
} }
JNIEXPORT jlong JNICALL JNIEXPORT jlong JNICALL Java_website_openrct2_ZipArchive_allocBytes(JNIEnv* env, jclass, jbyteArray input, jint numBytes)
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<void>((size_t)numBytes); void* data = Memory::Allocate<void>((size_t)numBytes);