diff --git a/src/STDInclude.hpp b/src/STDInclude.hpp index e1d4a09b..e1f4d8cc 100644 --- a/src/STDInclude.hpp +++ b/src/STDInclude.hpp @@ -19,7 +19,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/Utils/Compression.cpp b/src/Utils/Compression.cpp index a12718f5..a26fd668 100644 --- a/src/Utils/Compression.cpp +++ b/src/Utils/Compression.cpp @@ -1,70 +1,67 @@ #include -namespace Utils +namespace Utils::Compression { - namespace Compression + std::string ZLib::Compress(const std::string& data) { - std::string ZLib::Compress(const std::string& data) + Memory::Allocator allocator; + unsigned long length = (data.size() * 2); + if (!length) length = 2; + + // Make sure the buffer is large enough + if (length < 100) length *= 10; + + char* buffer = allocator.allocateArray(length); + if (compress2(reinterpret_cast(buffer), &length, reinterpret_cast(const_cast(data.data())), data.size(), Z_BEST_COMPRESSION) != Z_OK) { - Memory::Allocator allocator; - unsigned long length = (data.size() * 2); - if (!length) length = 2; - - // Make sure the buffer is large enough - if (length < 100) length *= 10; - - char* buffer = allocator.allocateArray(length); - if (compress2(reinterpret_cast(buffer), &length, reinterpret_cast(const_cast(data.data())), data.size(), Z_BEST_COMPRESSION) != Z_OK) - { - return ""; - } - - return std::string(buffer, length); + return {}; } - std::string ZLib::Decompress(const std::string& data) + return std::string(buffer, length); + } + + std::string ZLib::Decompress(const std::string& data) + { + z_stream stream; + ZeroMemory(&stream, sizeof(stream)); + std::string buffer; + + if (inflateInit(&stream) != Z_OK) { - z_stream stream; - ZeroMemory(&stream, sizeof(stream)); - std::string buffer; + return {}; + } - if (inflateInit(&stream) != Z_OK) - { - return ""; - } + int ret; + Memory::Allocator allocator; - int ret; - Memory::Allocator allocator; + std::uint8_t* dest = allocator.allocateArray(CHUNK); + const char* dataPtr = data.data(); - uint8_t* dest = allocator.allocateArray(CHUNK); - const char* dataPtr = data.data(); + do + { + stream.avail_in = std::min(static_cast(CHUNK), data.size() - (dataPtr - data.data())); + stream.next_in = reinterpret_cast(dataPtr); + dataPtr += stream.avail_in; do { - stream.avail_in = std::min(static_cast(CHUNK), data.size() - (dataPtr - data.data())); - stream.next_in = reinterpret_cast(dataPtr); - dataPtr += stream.avail_in; + stream.avail_out = CHUNK; + stream.next_out = dest; - do + ret = inflate(&stream, Z_NO_FLUSH); + if (ret != Z_OK && ret != Z_STREAM_END) { - stream.avail_out = CHUNK; - stream.next_out = dest; + inflateEnd(&stream); + return {}; + } - ret = inflate(&stream, Z_NO_FLUSH); - if (ret != Z_OK && ret != Z_STREAM_END) - { - inflateEnd(&stream); - return ""; - } + buffer.append(reinterpret_cast(dest), CHUNK - stream.avail_out); - buffer.append(reinterpret_cast(dest), CHUNK - stream.avail_out); + } while (stream.avail_out == 0); - } while (stream.avail_out == 0); + } while (ret != Z_STREAM_END); - } while (ret != Z_STREAM_END); - - inflateEnd(&stream); - return buffer; - } + inflateEnd(&stream); + return buffer; } } diff --git a/src/Utils/Compression.hpp b/src/Utils/Compression.hpp index b5301c48..34915c0d 100644 --- a/src/Utils/Compression.hpp +++ b/src/Utils/Compression.hpp @@ -4,15 +4,12 @@ #define DEFLATE_ZLIB false #define DEFLATE_ZSTD true -namespace Utils +namespace Utils::Compression { - namespace Compression + class ZLib { - class ZLib - { - public: - static std::string Compress(const std::string& data); - static std::string Decompress(const std::string& data); - }; + public: + static std::string Compress(const std::string& data); + static std::string Decompress(const std::string& data); }; } diff --git a/src/Utils/Cryptography.cpp b/src/Utils/Cryptography.cpp index 958fe274..26eb3813 100644 --- a/src/Utils/Cryptography.cpp +++ b/src/Utils/Cryptography.cpp @@ -19,17 +19,17 @@ namespace Utils std::string Rand::GenerateChallenge() { std::string challenge; - challenge.append(Utils::String::VA("%X", Utils::Cryptography::Rand::GenerateInt())); - challenge.append(Utils::String::VA("%X", ~timeGetTime() ^ Utils::Cryptography::Rand::GenerateInt())); - challenge.append(Utils::String::VA("%X", Utils::Cryptography::Rand::GenerateInt())); + challenge.append(String::VA("%X", GenerateInt())); + challenge.append(String::VA("%X", ~timeGetTime() ^ GenerateInt())); + challenge.append(String::VA("%X", GenerateInt())); return challenge; } - uint32_t Rand::GenerateInt() + std::uint32_t Rand::GenerateInt() { - uint32_t number = 0; - fortuna_read(reinterpret_cast(&number), sizeof(number), &Rand::State); + std::uint32_t number = 0; + fortuna_read(reinterpret_cast(&number), sizeof(number), &Rand::State); return number; } @@ -46,7 +46,7 @@ namespace Utils ECC::Key ECC::GenerateKey(int bits) { - ECC::Key key; + Key key; ltc_mp = ltm_desc; register_prng(&sprng_desc); @@ -57,16 +57,16 @@ namespace Utils std::string ECC::SignMessage(Key key, const std::string& message) { - if (!key.isValid()) return ""; + if (!key.isValid()) return {}; - uint8_t buffer[512]; + std::uint8_t buffer[512]; DWORD length = sizeof(buffer); ltc_mp = ltm_desc; register_prng(&sprng_desc); - ecc_sign_hash(reinterpret_cast(message.data()), message.size(), buffer, &length, nullptr, find_prng("sprng"), key.getKeyPtr()); + ecc_sign_hash(reinterpret_cast(message.data()), message.size(), buffer, &length, nullptr, find_prng("sprng"), key.getKeyPtr()); - return std::string(reinterpret_cast(buffer), length); + return {reinterpret_cast(buffer), length}; } bool ECC::VerifyMessage(Key key, const std::string& message, const std::string& signature) @@ -76,7 +76,7 @@ namespace Utils ltc_mp = ltm_desc; int result = 0; - return (ecc_verify_hash(reinterpret_cast(signature.data()), signature.size(), reinterpret_cast(message.data()), message.size(), &result, key.getKeyPtr()) == CRYPT_OK && result != 0); + return (ecc_verify_hash(reinterpret_cast(signature.data()), signature.size(), reinterpret_cast(message.data()), message.size(), &result, key.getKeyPtr()) == CRYPT_OK && result != 0); } #pragma endregion @@ -85,7 +85,7 @@ namespace Utils RSA::Key RSA::GenerateKey(int bits) { - RSA::Key key; + Key key; register_prng(&sprng_desc); register_hash(&sha1_desc); @@ -97,11 +97,11 @@ namespace Utils return key; } - std::string RSA::SignMessage(RSA::Key key, const std::string& message) + std::string RSA::SignMessage(Key key, const std::string& message) { - if (!key.isValid()) return ""; + if (!key.isValid()) return {}; - uint8_t buffer[512]; + std::uint8_t buffer[512]; DWORD length = sizeof(buffer); register_prng(&sprng_desc); @@ -109,9 +109,9 @@ namespace Utils ltc_mp = ltm_desc; - rsa_sign_hash(reinterpret_cast(message.data()), message.size(), buffer, &length, NULL, find_prng("sprng"), find_hash("sha1"), 0, key.getKeyPtr()); + rsa_sign_hash(reinterpret_cast(message.data()), message.size(), buffer, &length, NULL, find_prng("sprng"), find_hash("sha1"), 0, key.getKeyPtr()); - return std::string(reinterpret_cast(buffer), length); + return {reinterpret_cast(buffer), length}; } bool RSA::VerifyMessage(Key key, const std::string& message, const std::string& signature) @@ -123,7 +123,7 @@ namespace Utils ltc_mp = ltm_desc; int result = 0; - return (rsa_verify_hash(reinterpret_cast(signature.data()), signature.size(), reinterpret_cast(message.data()), message.size(), find_hash("sha1"), 0, &result, key.getKeyPtr()) == CRYPT_OK && result != 0); + return (rsa_verify_hash(reinterpret_cast(signature.data()), signature.size(), reinterpret_cast(message.data()), message.size(), find_hash("sha1"), 0, &result, key.getKeyPtr()) == CRYPT_OK && result != 0); } #pragma endregion @@ -143,8 +143,8 @@ namespace Utils symmetric_CBC cbc; int des3 = find_cipher("3des"); - cbc_start(des3, reinterpret_cast(iv.data()), reinterpret_cast(key.data()), key.size(), 0, &cbc); - cbc_encrypt(reinterpret_cast(text.data()), reinterpret_cast(const_cast(encData.data())), text.size(), &cbc); + cbc_start(des3, reinterpret_cast(iv.data()), reinterpret_cast(key.data()), key.size(), 0, &cbc); + cbc_encrypt(reinterpret_cast(text.data()), reinterpret_cast(encData.data()), text.size(), &cbc); cbc_done(&cbc); return encData; @@ -158,8 +158,8 @@ namespace Utils symmetric_CBC cbc; int des3 = find_cipher("3des"); - cbc_start(des3, reinterpret_cast(iv.data()), reinterpret_cast(key.data()), key.size(), 0, &cbc); - cbc_decrypt(reinterpret_cast(data.data()), reinterpret_cast(const_cast(decData.data())), data.size(), &cbc); + cbc_start(des3, reinterpret_cast(iv.data()), reinterpret_cast(key.data()), key.size(), 0, &cbc); + cbc_decrypt(reinterpret_cast(data.data()), reinterpret_cast(decData.data()), data.size(), &cbc); cbc_done(&cbc); return decData; @@ -171,12 +171,12 @@ namespace Utils std::string Tiger::Compute(const std::string& data, bool hex) { - return Tiger::Compute(reinterpret_cast(data.data()), data.size(), hex); + return Compute(reinterpret_cast(data.data()), data.size(), hex); } - std::string Tiger::Compute(const uint8_t* data, size_t length, bool hex) + std::string Tiger::Compute(const std::uint8_t* data, std::size_t length, bool hex) { - uint8_t buffer[24] = { 0 }; + std::uint8_t buffer[24]{}; hash_state state; tiger_init(&state); @@ -186,7 +186,7 @@ namespace Utils std::string hash(reinterpret_cast(buffer), sizeof(buffer)); if (!hex) return hash; - return Utils::String::DumpHex(hash, ""); + return String::DumpHex(hash, ""); } #pragma endregion @@ -195,12 +195,12 @@ namespace Utils std::string SHA1::Compute(const std::string& data, bool hex) { - return SHA1::Compute(reinterpret_cast(data.data()), data.size(), hex); + return Compute(reinterpret_cast(data.data()), data.size(), hex); } - std::string SHA1::Compute(const uint8_t* data, size_t length, bool hex) + std::string SHA1::Compute(const std::uint8_t* data, std::size_t length, bool hex) { - uint8_t buffer[20] = { 0 }; + std::uint8_t buffer[20]{}; hash_state state; sha1_init(&state); @@ -210,7 +210,7 @@ namespace Utils std::string hash(reinterpret_cast(buffer), sizeof(buffer)); if (!hex) return hash; - return Utils::String::DumpHex(hash, ""); + return String::DumpHex(hash, ""); } #pragma endregion @@ -219,12 +219,12 @@ namespace Utils std::string SHA256::Compute(const std::string& data, bool hex) { - return SHA256::Compute(reinterpret_cast(data.data()), data.size(), hex); + return Compute(reinterpret_cast(data.data()), data.size(), hex); } - std::string SHA256::Compute(const uint8_t* data, size_t length, bool hex) + std::string SHA256::Compute(const std::uint8_t* data, std::size_t length, bool hex) { - uint8_t buffer[32] = { 0 }; + std::uint8_t buffer[32]{}; hash_state state; sha256_init(&state); @@ -234,7 +234,7 @@ namespace Utils std::string hash(reinterpret_cast(buffer), sizeof(buffer)); if (!hex) return hash; - return Utils::String::DumpHex(hash, ""); + return String::DumpHex(hash, ""); } #pragma endregion @@ -243,12 +243,12 @@ namespace Utils std::string SHA512::Compute(const std::string& data, bool hex) { - return SHA512::Compute(reinterpret_cast(data.data()), data.size(), hex); + return Compute(reinterpret_cast(data.data()), data.size(), hex); } - std::string SHA512::Compute(const uint8_t* data, size_t length, bool hex) + std::string SHA512::Compute(const std::uint8_t* data, std::size_t length, bool hex) { - uint8_t buffer[64] = { 0 }; + std::uint8_t buffer[64]{}; hash_state state; sha512_init(&state); @@ -258,7 +258,7 @@ namespace Utils std::string hash(reinterpret_cast(buffer), sizeof(buffer)); if (!hex) return hash; - return Utils::String::DumpHex(hash, ""); + return String::DumpHex(hash, ""); } #pragma endregion @@ -267,7 +267,7 @@ namespace Utils unsigned int JenkinsOneAtATime::Compute(const std::string& data) { - return JenkinsOneAtATime::Compute(data.data(), data.size()); + return Compute(data.data(), data.size()); } unsigned int JenkinsOneAtATime::Compute(const char *key, size_t len) @@ -286,6 +286,5 @@ namespace Utils } #pragma endregion - } } diff --git a/src/Utils/Cryptography.hpp b/src/Utils/Cryptography.hpp index c130a8b7..09f66010 100644 --- a/src/Utils/Cryptography.hpp +++ b/src/Utils/Cryptography.hpp @@ -31,7 +31,7 @@ namespace Utils if (!i) { // Prepend here, as /dev/urandom says so ;) https://github.com/IW4x/iw4x-client-node/wikis/technical-information#incrementing-the-token - this->tokenString = std::basic_string(reinterpret_cast(const_cast("\0")), 1) + this->tokenString; + this->tokenString = std::basic_string(reinterpret_cast(const_cast("\0")), 1) + this->tokenString; break; } } @@ -253,16 +253,18 @@ namespace Utils Key() : keyStorage(new rsa_key) { ZeroMemory(this->getKeyPtr(), sizeof(*this->getKeyPtr())); - }; - Key(rsa_key* key) : Key() { if (key) std::memmove(this->getKeyPtr(), key, sizeof(*key)); }; - Key(rsa_key key) : Key(&key) {}; + } + + Key(rsa_key* key) : Key() { if (key) std::memmove(this->getKeyPtr(), key, sizeof(*key)); } + Key(rsa_key key) : Key(&key) {} + ~Key() { if (this->keyStorage.use_count() <= 1) { this->free(); } - }; + } rsa_key* getKeyPtr() { @@ -271,7 +273,7 @@ namespace Utils bool isValid() { - return (!Utils::Memory::IsSet(this->getKeyPtr(), 0, sizeof(*this->getKeyPtr()))); + return (!Memory::IsSet(this->getKeyPtr(), 0, sizeof(*this->getKeyPtr()))); } void free() @@ -305,35 +307,35 @@ namespace Utils { public: static std::string Compute(const std::string& data, bool hex = false); - static std::string Compute(const uint8_t* data, size_t length, bool hex = false); + static std::string Compute(const std::uint8_t* data, std::size_t length, bool hex = false); }; class SHA1 { public: static std::string Compute(const std::string& data, bool hex = false); - static std::string Compute(const uint8_t* data, size_t length, bool hex = false); + static std::string Compute(const std::uint8_t* data, std::size_t length, bool hex = false); }; class SHA256 { public: static std::string Compute(const std::string& data, bool hex = false); - static std::string Compute(const uint8_t* data, size_t length, bool hex = false); + static std::string Compute(const std::uint8_t* data, std::size_t length, bool hex = false); }; class SHA512 { public: static std::string Compute(const std::string& data, bool hex = false); - static std::string Compute(const uint8_t* data, size_t length, bool hex = false); + static std::string Compute(const std::uint8_t* data, std::size_t length, bool hex = false); }; class JenkinsOneAtATime { public: static unsigned int Compute(const std::string& data); - static unsigned int Compute(const char *key, size_t len); + static unsigned int Compute(const char *key, std::size_t len); }; } } diff --git a/src/Utils/Entities.cpp b/src/Utils/Entities.cpp index f2a38b86..5c31dfbe 100644 --- a/src/Utils/Entities.cpp +++ b/src/Utils/Entities.cpp @@ -2,7 +2,7 @@ namespace Utils { - std::string Entities::build() + std::string Entities::build() const { std::string entityString; @@ -31,9 +31,9 @@ namespace Utils for (auto& entity : this->entities) { - if (entity.find("model") != entity.end()) + if (const auto itr = entity.find("model"); itr != entity.end()) { - std::string model = entity["model"]; + const auto& model = itr->second; if (!model.empty() && model[0] != '*' && model[0] != '?') // Skip brushmodels { @@ -55,7 +55,7 @@ namespace Utils if (i->find("classname") != i->end()) { std::string classname = (*i)["classname"]; - if (Utils::String::StartsWith(classname, "trigger_")) + if (String::StartsWith(classname, "trigger_")) { i = this->entities.erase(i); continue; @@ -105,9 +105,9 @@ namespace Utils std::string value; std::unordered_map entity; - for (unsigned int i = 0; i < buffer.size(); ++i) + for (std::size_t i = 0; i < buffer.size(); ++i) { - char character = buffer[i]; + const auto character = buffer[i]; if (character == '{') { entity.clear(); @@ -146,7 +146,7 @@ namespace Utils } else if (parseState == PARSE_READ_VALUE) { - entity[Utils::String::ToLower(key)] = value; + entity[String::ToLower(key)] = value; parseState = PARSE_AWAIT_KEY; } else diff --git a/src/Utils/Entities.hpp b/src/Utils/Entities.hpp index 11eb56d9..f74a36fc 100644 --- a/src/Utils/Entities.hpp +++ b/src/Utils/Entities.hpp @@ -5,12 +5,12 @@ namespace Utils class Entities { public: - Entities() {}; - Entities(const char* string, size_t lenPlusOne) : Entities(std::string(string, lenPlusOne - 1)) {} - Entities(const std::string& buffer) : Entities() { this->parse(buffer); }; - Entities(const Entities &obj) : entities(obj.entities) {}; + Entities() = default; + Entities(const std::string& buffer) : Entities() { this->parse(buffer); } + Entities(const char* string, std::size_t lenPlusOne) : Entities(std::string(string, lenPlusOne - 1)) {} + Entities(const Entities& obj) = default; - std::string build(); + [[nodiscard]] std::string build() const; std::vector getModels(); void deleteTriggers(); diff --git a/src/Utils/IO.cpp b/src/Utils/IO.cpp index 9b720ed7..d05b887f 100644 --- a/src/Utils/IO.cpp +++ b/src/Utils/IO.cpp @@ -1,114 +1,111 @@ #include -namespace Utils +namespace Utils::IO { - namespace IO + bool FileExists(const std::string& file) { - bool FileExists(const std::string& file) + //return std::ifstream(file).good(); + return GetFileAttributesA(file.data()) != INVALID_FILE_ATTRIBUTES; + } + + bool WriteFile(const std::string& file, const std::string& data, bool append) + { + const auto pos = file.find_last_of("/\\"); + if (pos != std::string::npos) { - //return std::ifstream(file).good(); - return GetFileAttributesA(file.data()) != INVALID_FILE_ATTRIBUTES; + CreateDir(file.substr(0, pos)); } - bool WriteFile(const std::string& file, const std::string& data, bool append) + std::ofstream stream(file, std::ios::binary | std::ofstream::out | (append ? std::ofstream::app : std::ofstream::out)); + + if (stream.is_open()) { - auto pos = file.find_last_of("/\\"); - if (pos != std::string::npos) - { - CreateDir(file.substr(0, pos)); - } + stream.write(data.data(), static_cast(data.size())); + stream.close(); + return true; + } - std::ofstream stream(file, std::ios::binary | std::ofstream::out | (append ? std::ofstream::app : std::ofstream::out)); + return false; + } - if (stream.is_open()) + std::string ReadFile(const std::string& file) + { + std::string data; + ReadFile(file, &data); + return data; + } + + bool ReadFile(const std::string& file, std::string* data) + { + if (!data) return false; + data->clear(); + + if (FileExists(file)) + { + std::ifstream stream(file, std::ios::binary); + if (!stream.is_open()) return false; + + stream.seekg(0, std::ios::end); + std::streamsize size = stream.tellg(); + stream.seekg(0, std::ios::beg); + + if (size > -1) { - stream.write(data.data(), data.size()); + data->resize(static_cast(size)); + stream.read(data->data(), size); stream.close(); return true; } - - return false; } - std::string ReadFile(const std::string& file) - { - std::string data; - ReadFile(file, &data); - return data; - } + return false; + } - bool ReadFile(const std::string& file, std::string* data) - { - if (!data) return false; - data->clear(); + bool RemoveFile(const std::string& file) + { + return DeleteFileA(file.data()) == TRUE; + } - if (FileExists(file)) + std::size_t FileSize(const std::string& file) + { + if (FileExists(file)) + { + std::ifstream stream(file, std::ios::binary); + + if (stream.good()) { - std::ifstream stream(file, std::ios::binary); - if (!stream.is_open()) return false; - stream.seekg(0, std::ios::end); - std::streamsize size = stream.tellg(); - stream.seekg(0, std::ios::beg); - - if (size > -1) - { - data->resize(static_cast(size)); - stream.read(data->data(), size); - stream.close(); - return true; - } + return static_cast(stream.tellg()); } - - return false; } - bool RemoveFile(const std::string& file) + return 0; + } + + bool CreateDir(const std::string& dir) + { + return std::filesystem::create_directories(dir); + } + + bool DirectoryExists(const std::filesystem::path& directory) + { + return std::filesystem::is_directory(directory); + } + + bool DirectoryIsEmpty(const std::filesystem::path& directory) + { + return std::filesystem::is_empty(directory); + } + + std::vector ListFiles(const std::filesystem::path& directory) + { + std::vector files; + + for (auto& file : std::filesystem::directory_iterator(directory)) { - return DeleteFileA(file.data()) == TRUE; + files.push_back(file.path().generic_string()); } - std::size_t FileSize(const std::string& file) - { - if (FileExists(file)) - { - std::ifstream stream(file, std::ios::binary); - - if (stream.good()) - { - stream.seekg(0, std::ios::end); - return static_cast(stream.tellg()); - } - } - - return 0; - } - - bool CreateDir(const std::string& dir) - { - return std::filesystem::create_directories(dir); - } - - bool DirectoryExists(const std::filesystem::path& directory) - { - return std::filesystem::is_directory(directory); - } - - bool DirectoryIsEmpty(const std::filesystem::path& directory) - { - return std::filesystem::is_empty(directory); - } - - std::vector ListFiles(const std::filesystem::path& directory) - { - std::vector files; - - for (auto& file : std::filesystem::directory_iterator(directory)) - { - files.push_back(file.path().generic_string()); - } - - return files; - } + return files; } } diff --git a/src/Utils/Memory.cpp b/src/Utils/Memory.cpp index bba45884..9b3a0910 100644 --- a/src/Utils/Memory.cpp +++ b/src/Utils/Memory.cpp @@ -6,22 +6,22 @@ namespace Utils void* Memory::AllocateAlign(size_t length, size_t alignment) { - void* data = _aligned_malloc(length, alignment); - assert(data != nullptr); + auto* data = _aligned_malloc(length, alignment); + assert(data); if (data) ZeroMemory(data, length); return data; } void* Memory::Allocate(size_t length) { - void* data = calloc(length, 1); - assert(data != nullptr); + auto* data = calloc(length, 1); + assert(data); return data; } char* Memory::DuplicateString(const std::string& string) { - char* newString = Memory::AllocateArray(string.size() + 1); + auto* newString = Memory::AllocateArray(string.size() + 1); std::memcpy(newString, string.data(), string.size()); return newString; } @@ -30,13 +30,13 @@ namespace Utils { if (data) { - free(data); + ::free(data); } } void Memory::Free(const void* data) { - Memory::Free(const_cast(data)); + Free(const_cast(data)); } void Memory::FreeAlign(void* data) @@ -49,13 +49,13 @@ namespace Utils void Memory::FreeAlign(const void* data) { - Memory::FreeAlign(const_cast(data)); + FreeAlign(const_cast(data)); } // Complementary function for memset, which checks if memory is filled with a char bool Memory::IsSet(void* mem, char chr, size_t length) { - char* memArr = reinterpret_cast(mem); + auto* memArr = static_cast(mem); for (size_t i = 0; i < length; ++i) { @@ -98,7 +98,7 @@ namespace Utils return true; } - Utils::Memory::Allocator* Memory::GetAllocator() + Memory::Allocator* Memory::GetAllocator() { return &Memory::MemAllocator; } diff --git a/src/Utils/Memory.hpp b/src/Utils/Memory.hpp index cc0bb48c..7d3fc150 100644 --- a/src/Utils/Memory.hpp +++ b/src/Utils/Memory.hpp @@ -22,7 +22,7 @@ namespace Utils void clear() { - std::lock_guard _(this->mutex); + std::lock_guard _(this->mutex); for (auto i = this->refMemory.begin(); i != this->refMemory.end(); ++i) { @@ -36,7 +36,7 @@ namespace Utils for (const auto& data : this->pool) { - Memory::Free(data); + Free(data); } this->pool.clear(); @@ -44,7 +44,7 @@ namespace Utils void free(void* data) { - std::lock_guard _(this->mutex); + std::lock_guard _(this->mutex); auto i = this->refMemory.find(data); if (i != this->refMemory.end()) @@ -56,7 +56,7 @@ namespace Utils auto j = std::find(this->pool.begin(), this->pool.end(), data); if (j != this->pool.end()) { - Memory::Free(data); + Free(data); this->pool.erase(j); } } @@ -68,45 +68,45 @@ namespace Utils void reference(void* memory, FreeCallback callback) { - std::lock_guard _(this->mutex); + std::lock_guard _(this->mutex); this->refMemory[memory] = callback; } void* allocate(size_t length) { - std::lock_guard _(this->mutex); + std::lock_guard _(this->mutex); - void* data = Memory::Allocate(length); + void* data = Allocate(length); this->pool.push_back(data); return data; } - template inline T* allocate() + template T* allocate() { return this->allocateArray(1); } - template inline T* allocateArray(size_t count = 1) + template T* allocateArray(size_t count = 1) { return static_cast(this->allocate(count * sizeof(T))); } - bool empty() + bool empty() const { return (this->pool.empty() && this->refMemory.empty()); } char* duplicateString(const std::string& string) { - std::lock_guard _(this->mutex); + std::lock_guard _(this->mutex); - char* data = Memory::DuplicateString(string); + char* data = DuplicateString(string); this->pool.push_back(data); return data; } - bool isPointerMapped(void* ptr) + bool isPointerMapped(void* ptr) const { return this->ptrMap.contains(ptr); } @@ -115,7 +115,7 @@ namespace Utils { if (this->isPointerMapped(oldPtr)) { - return reinterpret_cast(this->ptrMap[oldPtr]); + return static_cast(this->ptrMap[oldPtr]); } return nullptr; @@ -135,16 +135,16 @@ namespace Utils static void* AllocateAlign(size_t length, size_t alignment); static void* Allocate(size_t length); - template static inline T* Allocate() + template static T* Allocate() { return AllocateArray(1); } - template static inline T* AllocateArray(size_t count = 1) + template static T* AllocateArray(size_t count = 1) { return static_cast(Allocate(count * sizeof(T))); } - template static inline T* Duplicate(T* original) + template static T* Duplicate(T* original) { T* data = Memory::Allocate(); std::memcpy(data, original, sizeof(T)); @@ -164,9 +164,9 @@ namespace Utils static bool IsBadReadPtr(const void* ptr); static bool IsBadCodePtr(const void* ptr); - static Utils::Memory::Allocator* GetAllocator(); + static Allocator* GetAllocator(); private: - static Utils::Memory::Allocator MemAllocator; + static Allocator MemAllocator; }; } diff --git a/src/Utils/Stream.cpp b/src/Utils/Stream.cpp index e3ef1b14..95d83dfc 100644 --- a/src/Utils/Stream.cpp +++ b/src/Utils/Stream.cpp @@ -29,7 +29,7 @@ namespace Utils throw std::runtime_error("Reading past the buffer"); } - void* Stream::Reader::read(size_t size, size_t count) + void* Stream::Reader::read(size_t size, std::size_t count) { size_t bytes = size * count; @@ -112,17 +112,17 @@ namespace Utils } }; - size_t Stream::length() + std::size_t Stream::length() const { return this->buffer.length(); } - size_t Stream::capacity() + std::size_t Stream::capacity() const { return this->buffer.capacity(); } - void Stream::assertPointer(const void* pointer, size_t length) + void Stream::assertPointer(const void* pointer, std::size_t length) { if (!this->ptrAssertion) return; @@ -131,22 +131,24 @@ namespace Utils unsigned int ePtr = reinterpret_cast(entry.first); unsigned int tPtr = reinterpret_cast(pointer); - if (Utils::HasIntercection(ePtr, entry.second, tPtr, length)) + if (HasIntersection(ePtr, entry.second, tPtr, length)) { MessageBoxA(nullptr, "Duplicate data written!", "ERROR", MB_ICONERROR); +#ifdef _DEBUG __debugbreak(); +#endif } } this->ptrList.push_back({ pointer, length }); } - char* Stream::save(const void* _str, size_t size, size_t count) + char* Stream::save(const void* _str, std::size_t size, std::size_t count) { return this->save(this->getCurrentBlock(), _str, size, count); } - char* Stream::save(Game::XFILE_BLOCK_TYPES stream, const void * _str, size_t size, size_t count) + char* Stream::save(Game::XFILE_BLOCK_TYPES stream, const void * _str, std::size_t size, std::size_t count) { // Only those seem to actually write data. // everything else is allocated at runtime but XFILE_BLOCK_RUNTIME is the only one that actually allocates anything @@ -179,7 +181,7 @@ namespace Utils return this->at() - (size * count); } - char* Stream::save(Game::XFILE_BLOCK_TYPES stream, int value, size_t count) + char* Stream::save(Game::XFILE_BLOCK_TYPES stream, int value, std::size_t count) { auto ret = this->length(); @@ -201,7 +203,7 @@ namespace Utils return this->saveString(string, strlen(string)); } - char* Stream::saveString(const char* string, size_t len) + char* Stream::saveString(const char* string, std::size_t len) { auto ret = this->length(); @@ -220,7 +222,7 @@ namespace Utils return this->save(string.data(), string.length()); } - char* Stream::saveByte(unsigned char byte, size_t count) + char* Stream::saveByte(unsigned char byte, std::size_t count) { auto ret = this->length(); diff --git a/src/Utils/Stream.hpp b/src/Utils/Stream.hpp index bf5e12dc..b63fc978 100644 --- a/src/Utils/Stream.hpp +++ b/src/Utils/Stream.hpp @@ -16,7 +16,7 @@ namespace Utils { private: bool ptrAssertion; - std::vector> ptrList; + std::vector> ptrList; int criticalSectionState; unsigned int blockSize[Game::MAX_XFILE_COUNT]; @@ -27,21 +27,21 @@ namespace Utils class Reader { public: - Reader(Utils::Memory::Allocator* _allocator, const std::string& _buffer) : position(0), buffer(_buffer), allocator(_allocator) {} + Reader(Memory::Allocator* _allocator, const std::string& _buffer) : position(0), buffer(_buffer), allocator(_allocator) {} std::string readString(); const char* readCString(); char readByte(); - void* read(size_t size, size_t count = 1); - template inline T* readObject() + void* read(std::size_t size, std::size_t count = 1); + template T* readObject() { return readArray(1); } - template inline T* readArray(size_t count = 1) + template T* readArray(std::size_t count = 1) { - return reinterpret_cast(this->read(sizeof(T), count)); + return static_cast(this->read(sizeof(T), count)); } template T read() { @@ -89,25 +89,25 @@ namespace Utils Stream(size_t size); ~Stream(); - size_t length(); - size_t capacity(); + std::size_t length() const; + std::size_t capacity() const; - char* save(const void * _str, size_t size, size_t count = 1); - char* save(Game::XFILE_BLOCK_TYPES stream, const void * _str, size_t size, size_t count); - char* save(Game::XFILE_BLOCK_TYPES stream, int value, size_t count); + char* save(const void * _str, std::size_t size, std::size_t count = 1); + char* save(Game::XFILE_BLOCK_TYPES stream, const void * _str, std::size_t size, std::size_t count); + char* save(Game::XFILE_BLOCK_TYPES stream, int value, std::size_t count); template inline char* save(T* object) { return saveArray(object, 1); } - template inline char* saveArray(T* array, size_t count) + template inline char* saveArray(T* array, std::size_t count) { return save(array, sizeof(T), count); } char* saveString(const std::string& string); char* saveString(const char* string); - char* saveString(const char* string, size_t len); - char* saveByte(unsigned char byte, size_t count = 1); + char* saveString(const char* string, std::size_t len); + char* saveByte(unsigned char byte, std::size_t count = 1); char* saveNull(size_t count = 1); char* saveMax(size_t count = 1); @@ -140,7 +140,7 @@ namespace Utils { this->ptrAssertion = value; } - void assertPointer(const void* pointer, size_t length); + void assertPointer(const void* pointer, std::size_t length); void toBuffer(std::string& outBuffer); std::string toBuffer(); diff --git a/src/Utils/String.cpp b/src/Utils/String.cpp index 360c5032..502fe000 100644 --- a/src/Utils/String.cpp +++ b/src/Utils/String.cpp @@ -3,247 +3,246 @@ #include "base128.h" #endif -namespace Utils +namespace Utils::String { - namespace String + const char *VA(const char *fmt, ...) { - const char *VA(const char *fmt, ...) + static VAProvider<4, 100> globalProvider; + static thread_local VAProvider<8, 256> provider; + + va_list ap; + va_start(ap, fmt); + + const char* result; + if (Components::Loader::IsUninitializing()) result = globalProvider.get(fmt, ap); + else result = provider.get(fmt, ap); + + va_end(ap); + return result; + } + + std::string ToLower(std::string text) + { + std::transform(text.begin(), text.end(), text.begin(), [](const unsigned char input) { - static VAProvider<4, 100> globalProvider; - static thread_local VAProvider<8, 256> provider; + return static_cast(std::tolower(input)); + }); - va_list ap; - va_start(ap, fmt); + return text; + } - const char* result; - if (Components::Loader::IsUninitializing()) result = globalProvider.get(fmt, ap); - else result = provider.get(fmt, ap); - - va_end(ap); - return result; - } - - std::string ToLower(std::string text) + std::string ToUpper(std::string text) + { + std::transform(text.begin(), text.end(), text.begin(), [](const unsigned char input) { - std::transform(text.begin(), text.end(), text.begin(), [](const unsigned char input) + return static_cast(std::toupper(input)); + }); + + return text; + } + + bool Compare(const std::string& lhs, const std::string& rhs) + { + return std::ranges::equal(lhs, rhs, [](const unsigned char a, const unsigned char b) + { + return std::tolower(a) == std::tolower(b); + }); + } + + std::string DumpHex(const std::string& data, const std::string& separator) + { + std::string result; + + for (std::size_t i = 0; i < data.size(); ++i) + { + if (i > 0) { - return static_cast(std::tolower(input)); - }); - - return text; - } - - std::string ToUpper(std::string text) - { - std::transform(text.begin(), text.end(), text.begin(), [](const unsigned char input) - { - return static_cast(std::toupper(input)); - }); - - return text; - } - - bool Compare(const std::string& lhs, const std::string& rhs) - { - return std::ranges::equal(lhs, rhs, [](const unsigned char a, const unsigned char b) - { - return std::tolower(a) == std::tolower(b); - }); - } - - std::string DumpHex(const std::string& data, const std::string& separator) - { - std::string result; - - for (unsigned int i = 0; i < data.size(); ++i) - { - if (i > 0) - { - result.append(separator); - } - - result.append(Utils::String::VA("%02X", data[i] & 0xFF)); + result.append(separator); } - return result; + result.append(VA("%02X", data[i] & 0xFF)); } - std::string XOR(std::string str, char value) + return result; + } + + std::string XOR(std::string str, char value) + { + for (std::size_t i = 0; i < str.size(); ++i) { - for (unsigned int i = 0; i < str.size(); ++i) - { - str[i] ^= value; - } - - return str; + str[i] ^= static_cast(value); } - std::vector Split(const std::string& str, const char delim) + return str; + } + + std::vector Split(const std::string& str, const char delim) + { + std::stringstream ss(str); + std::string item; + std::vector elems; + + while (std::getline(ss, item, delim)) { - std::stringstream ss(str); - std::string item; - std::vector elems; - - while (std::getline(ss, item, delim)) - { - elems.push_back(item); // elems.push_back(std::move(item)); // if C++11 (based on comment from S1x) - } - - return elems; + elems.push_back(item); // elems.push_back(std::move(item)); // if C++11 (based on comment from S1x) } - void Replace(std::string& str, const std::string& from, const std::string& to) + return elems; + } + + void Replace(std::string& str, const std::string& from, const std::string& to) + { + std::size_t nPos = 0; + + while ((nPos = str.find(from, nPos)) != std::string::npos) { - std::size_t nPos = 0; - - while ((nPos = str.find(from, nPos)) != std::string::npos) - { - str = str.replace(nPos, from.length(), to); - nPos += to.length(); - } + str = str.replace(nPos, from.length(), to); + nPos += to.length(); } + } - bool StartsWith(const std::string& haystack, const std::string& needle) + bool StartsWith(const std::string& haystack, const std::string& needle) + { + return haystack.find(needle) == 0; // If the pos of the first found char is 0, string starts with 'needle' + } + + bool EndsWith(const std::string& haystack, const std::string& needle) + { + if (needle.size() > haystack.size()) return false; + return std::equal(needle.rbegin(), needle.rend(), haystack.rbegin()); + } + + bool IsNumber(const std::string& str) + { + return !str.empty() && std::find_if(str.begin(), str.end(), [](unsigned char input) { - return haystack.find(needle) == 0; // If the pos of the first found char is 0, string starts with 'needle' - } + return !std::isdigit(input); + }) == str.end(); + } - bool EndsWith(const std::string& haystack, const std::string& needle) + // Trim from start + std::string& LTrim(std::string& str) + { + str.erase(str.begin(), std::find_if(str.begin(), str.end(), [](const unsigned char input) { - if (needle.size() > haystack.size()) return false; - return std::equal(needle.rbegin(), needle.rend(), haystack.rbegin()); - } + return !std::isspace(input); + })); - bool IsNumber(const std::string& str) + return str; + } + + // Trim from end + std::string& RTrim(std::string& str) + { + str.erase(std::find_if(str.rbegin(), str.rend(), [](const unsigned char input) { - return !str.empty() && std::find_if(str.begin(), - str.end(), [](unsigned char input) { return !std::isdigit(input); }) == str.end(); - } + return !std::isspace(input); + }).base(), str.end()); - // Trim from start - std::string& LTrim(std::string& str) + return str; + } + + // Trim from both ends + std::string& Trim(std::string& str) + { + return LTrim(RTrim(str)); + } + + std::string Convert(const std::wstring& wstr) + { + std::string result; + result.reserve(wstr.size()); + + for (const auto& chr : wstr) { - str.erase(str.begin(), std::find_if(str.begin(), str.end(), [](const unsigned char input) - { - return !std::isspace(input); - })); - - return str; + result.push_back(static_cast(chr)); } - // Trim from end - std::string& RTrim(std::string& str) + return result; + } + + std::wstring Convert(const std::string& str) + { + std::wstring result; + result.reserve(str.size()); + + for (const auto& chr : str) { - str.erase(std::find_if(str.rbegin(), str.rend(), [](const unsigned char input) - { - return !std::isspace(input); - }).base(), str.end()); - - return str; + result.push_back(static_cast(chr)); } - // Trim from both ends - std::string& Trim(std::string& str) + return result; + } + + std::string FormatTimeSpan(int milliseconds) + { + int secondsTotal = milliseconds / 1000; + int seconds = secondsTotal % 60; + int minutesTotal = secondsTotal / 60; + int minutes = minutesTotal % 60; + int hoursTotal = minutesTotal / 60; + + return VA("%02d:%02d:%02d", hoursTotal, minutes, seconds); + } + + std::string FormatBandwidth(std::size_t bytes, int milliseconds) + { + static const char* sizes[] = { - return LTrim(RTrim(str)); - } + "B", + "KB", + "MB", + "GB", + "TB", + }; - std::string Convert(const std::wstring& wstr) + if (!milliseconds) return "0.00 B/s"; + + double bytesPerSecond = (1000.0 / milliseconds) * bytes; + + std::size_t i; + for (i = 0; bytesPerSecond > 1000 && i < ARRAYSIZE(sizes); ++i) // 1024 or 1000? { - std::string result; - result.reserve(wstr.size()); - - for (const auto& chr : wstr) - { - result.push_back(static_cast(chr)); - } - - return result; + bytesPerSecond /= 1000; } - std::wstring Convert(const std::string& str) - { - std::wstring result; - result.reserve(str.size()); - - for (const auto& chr : str) - { - result.push_back(static_cast(chr)); - } - - return result; - } - - std::string FormatTimeSpan(int milliseconds) - { - int secondsTotal = milliseconds / 1000; - int seconds = secondsTotal % 60; - int minutesTotal = secondsTotal / 60; - int minutes = minutesTotal % 60; - int hoursTotal = minutesTotal / 60; - - return Utils::String::VA("%02d:%02d:%02d", hoursTotal, minutes, seconds); - } - - std::string FormatBandwidth(size_t bytes, int milliseconds) - { - static const char* sizes[] = - { - "B", - "KB", - "MB", - "GB", - "TB" - }; - - if (!milliseconds) return "0.00 B/s"; - - double bytesPerSecond = (1000.0 / milliseconds) * bytes; - - int i; - for (i = 0; bytesPerSecond > 1000 && i < ARRAYSIZE(sizes); ++i) // 1024 or 1000? - { - bytesPerSecond /= 1000; - } - - return Utils::String::VA("%.2f %s/s", static_cast(bytesPerSecond), sizes[i]); - } + return VA("%.2f %s/s", static_cast(bytesPerSecond), sizes[i]); + } #ifdef ENABLE_BASE64 - // Encodes a given string in Base64 - std::string EncodeBase64(const char* input, const unsigned long inputSize) - { - unsigned long outlen = long(inputSize + (inputSize / 3.0) + 16); - unsigned char* outbuf = new unsigned char[outlen]; //Reserve output memory - base64_encode(reinterpret_cast(const_cast(input)), inputSize, outbuf, &outlen); - std::string ret(reinterpret_cast(outbuf), outlen); - delete[] outbuf; - return ret; - } + // Encodes a given string in Base64 + std::string EncodeBase64(const char* input, const unsigned long inputSize) + { + unsigned long outlen = long(inputSize + (inputSize / 3.0) + 16); + unsigned char* outbuf = new unsigned char[outlen]; //Reserve output memory + base64_encode(reinterpret_cast(const_cast(input)), inputSize, outbuf, &outlen); + std::string ret(reinterpret_cast(outbuf), outlen); + delete[] outbuf; + return ret; + } - // Encodes a given string in Base64 - std::string EncodeBase64(const std::string& input) - { - return EncodeBase64(input.data(), input.size()); - } + // Encodes a given string in Base64 + std::string EncodeBase64(const std::string& input) + { + return EncodeBase64(input.data(), input.size()); + } #endif #ifdef ENABLE_BASE128 - // Encodes a given string in Base128 - std::string EncodeBase128(const std::string& input) - { - base128 encoder; + // Encodes a given string in Base128 + std::string EncodeBase128(const std::string& input) + { + base128 encoder; - void* inbuffer = const_cast(input.data()); - char* buffer = encoder.encode(inbuffer, input.size()); - /* - Interesting to see that the buffer returned by the encoder is not a standalone string copy - but instead is a pointer to the internal "encoded" field of the encoder. So if you deinitialize - the encoder that string will probably become garbage. - */ - std::string retval(buffer); - return retval; - } -#endif + void* inbuffer = const_cast(input.data()); + char* buffer = encoder.encode(inbuffer, input.size()); + /* + Interesting to see that the buffer returned by the encoder is not a standalone string copy + but instead is a pointer to the internal "encoded" field of the encoder. So if you deinitialize + the encoder that string will probably become garbage. + */ + std::string retval(buffer); + return retval; } +#endif } diff --git a/src/Utils/String.hpp b/src/Utils/String.hpp index 1f1edd2f..7ff19f5c 100644 --- a/src/Utils/String.hpp +++ b/src/Utils/String.hpp @@ -1,105 +1,102 @@ #pragma once -namespace Utils +namespace Utils::String { - namespace String + template + class VAProvider { - template - class VAProvider + public: + static_assert(Buffers != 0 && MinBufferSize != 0, "Buffers and MinBufferSize mustn't be 0"); + + VAProvider() : currentBuffer(0) {} + ~VAProvider() = default; + + const char* get(const char* format, va_list ap) { - public: - static_assert(Buffers != 0 && MinBufferSize != 0, "Buffers and MinBufferSize mustn't be 0"); + ++this->currentBuffer %= ARRAYSIZE(this->stringPool); + auto entry = &this->stringPool[this->currentBuffer]; - VAProvider() : currentBuffer(0) {} - ~VAProvider() = default; - - const char* get(const char* format, va_list ap) + if (!entry->size || !entry->buffer) { - ++this->currentBuffer %= ARRAYSIZE(this->stringPool); - auto entry = &this->stringPool[this->currentBuffer]; - - if (!entry->size || !entry->buffer) - { - throw std::runtime_error("String pool not initialized"); - } - - while (true) - { - const auto res = vsnprintf_s(entry->buffer, entry->size, _TRUNCATE, format, ap); - if (res > 0) break; // Success - if (res == 0) return ""; // Error - - entry->doubleSize(); - } - - return entry->buffer; + throw std::runtime_error("String pool not initialized"); } - private: - class Entry + while (true) { - public: - Entry(size_t _size = MinBufferSize) : size(_size), buffer(nullptr) - { - if (this->size < MinBufferSize) this->size = MinBufferSize; - this->allocate(); - } + const auto res = vsnprintf_s(entry->buffer, entry->size, _TRUNCATE, format, ap); + if (res > 0) break; // Success + if (res == 0) return ""; // Error - ~Entry() - { - if (this->buffer) Memory::GetAllocator()->free(this->buffer); - this->size = 0; - this->buffer = nullptr; - } + entry->doubleSize(); + } - void allocate() - { - if (this->buffer) Memory::GetAllocator()->free(this->buffer); - this->buffer = Memory::GetAllocator()->allocateArray(this->size + 1); - } + return entry->buffer; + } - void doubleSize() - { - this->size *= 2; - this->allocate(); - } + private: + class Entry + { + public: + Entry(std::size_t _size = MinBufferSize) : size(_size), buffer(nullptr) + { + if (this->size < MinBufferSize) this->size = MinBufferSize; + this->allocate(); + } - size_t size; - char* buffer; - }; + ~Entry() + { + if (this->buffer) Memory::GetAllocator()->free(this->buffer); + this->size = 0; + this->buffer = nullptr; + } - size_t currentBuffer; - Entry stringPool[Buffers]; + void allocate() + { + if (this->buffer) Memory::GetAllocator()->free(this->buffer); + this->buffer = Memory::GetAllocator()->allocateArray(this->size + 1); + } + + void doubleSize() + { + this->size *= 2; + this->allocate(); + } + + std::size_t size; + char* buffer; }; - const char *VA(const char *fmt, ...); + std::size_t currentBuffer; + Entry stringPool[Buffers]; + }; - std::string ToLower(std::string text); - std::string ToUpper(std::string text); - bool Compare(const std::string& lhs, const std::string& rhs); - std::vector Split(const std::string& str, char delim); - void Replace(std::string& str, const std::string& from, const std::string& to); - bool StartsWith(const std::string& haystack, const std::string& needle); - bool EndsWith(const std::string& haystack, const std::string& needle); - bool IsNumber(const std::string& str); + const char *VA(const char *fmt, ...); - std::string& LTrim(std::string& str); - std::string& RTrim(std::string& str); - std::string& Trim(std::string& str); + std::string ToLower(std::string text); + std::string ToUpper(std::string text); + bool Compare(const std::string& lhs, const std::string& rhs); + std::vector Split(const std::string& str, char delim); + void Replace(std::string& str, const std::string& from, const std::string& to); + bool StartsWith(const std::string& haystack, const std::string& needle); + bool EndsWith(const std::string& haystack, const std::string& needle); + bool IsNumber(const std::string& str); - std::string Convert(const std::wstring& wstr); - std::wstring Convert(const std::string& str); + std::string& LTrim(std::string& str); + std::string& RTrim(std::string& str); + std::string& Trim(std::string& str); - std::string FormatTimeSpan(int milliseconds); - std::string FormatBandwidth(size_t bytes, int milliseconds); + std::string Convert(const std::wstring& wstr); + std::wstring Convert(const std::string& str); - std::string DumpHex(const std::string& data, const std::string& separator = " "); + std::string FormatTimeSpan(int milliseconds); + std::string FormatBandwidth(std::size_t bytes, int milliseconds); - std::string XOR(std::string str, char value); + std::string DumpHex(const std::string& data, const std::string& separator = " "); - std::string EncodeBase64(const char* input, const unsigned long inputSize); - std::string EncodeBase64(const std::string& input); + std::string XOR(std::string str, char value); - std::string EncodeBase128(const std::string& input); - } + std::string EncodeBase64(const char* input, const unsigned long inputSize); + std::string EncodeBase64(const std::string& input); + + std::string EncodeBase128(const std::string& input); } diff --git a/src/Utils/Time.cpp b/src/Utils/Time.cpp index 8e257e7d..3d12d524 100644 --- a/src/Utils/Time.cpp +++ b/src/Utils/Time.cpp @@ -1,42 +1,39 @@ #include -namespace Utils +namespace Utils::Time { - namespace Time + void Interval::update() { - void Interval::update() - { - this->lastPoint = std::chrono::high_resolution_clock::now(); - } + this->lastPoint = std::chrono::high_resolution_clock::now(); + } - bool Interval::elapsed(std::chrono::nanoseconds nsecs) - { - return ((std::chrono::high_resolution_clock::now() - this->lastPoint) >= nsecs); - } + bool Interval::elapsed(std::chrono::nanoseconds nsecs) const + { + return ((std::chrono::high_resolution_clock::now() - this->lastPoint) >= nsecs); + } - Point::Point() : lastPoint(Game::Sys_Milliseconds()) - { + Point::Point() : lastPoint(Game::Sys_Milliseconds()) + { - } + } - void Point::update() - { - this->lastPoint = Game::Sys_Milliseconds(); - } + void Point::update() + { + this->lastPoint = Game::Sys_Milliseconds(); + } - int Point::diff(Point point) - { - return point.lastPoint - this->lastPoint; - } + int Point::diff(Point point) const + { + return point.lastPoint - this->lastPoint; + } - bool Point::after(Point point) - { - return this->diff(point) < 0; - } + bool Point::after(Point point) const + { + return this->diff(point) < 0; + } - bool Point::elapsed(int milliseconds) - { - return (Game::Sys_Milliseconds() - this->lastPoint) >= milliseconds; - } + bool Point::elapsed(int milliseconds) const + { + return (Game::Sys_Milliseconds() - this->lastPoint) >= milliseconds; } } diff --git a/src/Utils/Time.hpp b/src/Utils/Time.hpp index d26763ad..68a0a23d 100644 --- a/src/Utils/Time.hpp +++ b/src/Utils/Time.hpp @@ -1,33 +1,30 @@ #pragma once -namespace Utils +namespace Utils::Time { - namespace Time + class Interval { - class Interval - { - protected: - std::chrono::high_resolution_clock::time_point lastPoint; + protected: + std::chrono::high_resolution_clock::time_point lastPoint; - public: - Interval() : lastPoint(std::chrono::high_resolution_clock::now()) {} + public: + Interval() : lastPoint(std::chrono::high_resolution_clock::now()) {} - void update(); - bool elapsed(std::chrono::nanoseconds nsecs); - }; + void update(); + bool elapsed(std::chrono::nanoseconds nsecs) const; + }; - class Point - { - public: - Point(); + class Point + { + public: + Point(); - void update(); - int diff(Point point); - bool after(Point point); - bool elapsed(int milliseconds); + void update(); + int diff(Point point) const; + bool after(Point point) const; + bool elapsed(int milliseconds) const; - private: - int lastPoint; - }; - } + private: + int lastPoint; + }; } diff --git a/src/Utils/Utils.cpp b/src/Utils/Utils.cpp index 53ed0ce8..6b789189 100644 --- a/src/Utils/Utils.cpp +++ b/src/Utils/Utils.cpp @@ -72,7 +72,7 @@ namespace Utils return 0; } - size_t GetModuleSize(HMODULE module) + std::size_t GetModuleSize(HMODULE module) { PIMAGE_DOS_HEADER header = PIMAGE_DOS_HEADER(module); PIMAGE_NT_HEADERS ntHeader = PIMAGE_NT_HEADERS(DWORD(module) + header->e_lfanew); @@ -158,7 +158,7 @@ namespace Utils SafeShellExecute(nullptr, "open", url.data(), nullptr, nullptr, SW_SHOWNORMAL); } - bool HasIntercection(unsigned int base1, unsigned int len1, unsigned int base2, unsigned int len2) + bool HasIntersection(unsigned int base1, unsigned int len1, unsigned int base2, unsigned int len2) { return !(base1 + len1 <= base2 || base2 + len2 <= base1); } diff --git a/src/Utils/Utils.hpp b/src/Utils/Utils.hpp index 79c6b706..702efd38 100644 --- a/src/Utils/Utils.hpp +++ b/src/Utils/Utils.hpp @@ -15,7 +15,7 @@ namespace Utils bool IsWineEnvironment(); unsigned long GetParentProcessId(); - size_t GetModuleSize(HMODULE); + std::size_t GetModuleSize(HMODULE); void* GetThreadStartAddress(HANDLE hThread); HMODULE GetNTDLL(); @@ -23,7 +23,7 @@ namespace Utils void OpenUrl(const std::string& url); - bool HasIntercection(unsigned int base1, unsigned int len1, unsigned int base2, unsigned int len2); + bool HasIntersection(unsigned int base1, unsigned int len1, unsigned int base2, unsigned int len2); template void RotLeft(T& object, size_t bits) { diff --git a/src/Utils/WebIO.cpp b/src/Utils/WebIO.cpp index b9189215..b449226c 100644 --- a/src/Utils/WebIO.cpp +++ b/src/Utils/WebIO.cpp @@ -10,7 +10,7 @@ namespace Utils this->setURL(url); } - WebIO::WebIO(const std::string& useragent) : cancel(false), timeout(5000), hSession(nullptr) // 5 seconds timeout by default + WebIO::WebIO(const std::string& useragent) : cancel(false), hSession(nullptr), timeout(5000) // 5 seconds timeout by default { this->openSession(useragent); } @@ -91,7 +91,7 @@ namespace Utils server = server.substr(2); } - size_t pos = server.find("/"); + size_t pos = server.find('/'); if (pos == std::string::npos) { this->url.server = server; @@ -105,7 +105,7 @@ namespace Utils this->url.port.clear(); - pos = this->url.server.find(":"); + pos = this->url.server.find(':'); if (pos != std::string::npos) { this->url.port = this->url.server.substr(pos + 1); @@ -128,7 +128,7 @@ namespace Utils this->isFTP = (this->url.protocol == "ftp"); } - std::string WebIO::buildPostBody(WebIO::Params params) + std::string WebIO::buildPostBody(Params params) { std::string body; @@ -157,15 +157,15 @@ namespace Utils std::string WebIO::postFile(const std::string& data, std::string fieldName, std::string fileName) { - WebIO::Params headers; + Params headers; std::string boundary = "----WebKitFormBoundaryHoLVocRsBxs71fU6"; headers["Content-Type"] = "multipart/form-data, boundary=" + boundary; - Utils::String::Replace(fieldName, "\"", "\\\""); - Utils::String::Replace(fieldName, "\\", "\\\\"); - Utils::String::Replace(fileName, "\"", "\\\""); - Utils::String::Replace(fileName, "\\", "\\\\"); + String::Replace(fieldName, "\"", "\\\""); + String::Replace(fieldName, "\\", "\\\\"); + String::Replace(fileName, "\"", "\\\""); + String::Replace(fileName, "\\", "\\\\"); std::string body = "--" + boundary + "\r\n"; body += "Content-Disposition: form-data; name=\""; @@ -177,7 +177,7 @@ namespace Utils body += data + "\r\n"; body += "--" + boundary + "--\r\n"; - headers["Content-Length"] = Utils::String::VA("%u", body.size()); + headers["Content-Length"] = String::VA("%u", body.size()); return this->execute("POST", body, headers); } @@ -188,13 +188,13 @@ namespace Utils return this->post(body, success); } - std::string WebIO::post(const std::string& _url, WebIO::Params params, bool* success) + std::string WebIO::post(const std::string& _url, Params params, bool* success) { this->setURL(_url); return this->post(params, success); } - std::string WebIO::post(WebIO::Params params, bool* success) + std::string WebIO::post(Params params, bool* success) { return this->post(this->buildPostBody(params), success); } @@ -259,7 +259,7 @@ namespace Utils std::string WebIO::execute(const char* command, const std::string& body, WebIO::Params headers, bool* success) { if (success) *success = false; - if (!this->openConnection()) return ""; + if (!this->openConnection()) return {}; const char *acceptTypes[] = { "application/x-www-form-urlencoded", nullptr }; @@ -276,12 +276,12 @@ namespace Utils if (!this->hFile || this->hFile == INVALID_HANDLE_VALUE) { this->closeConnection(); - return ""; + return {}; } - if (headers.find("Content-Type") == headers.end()) + if (const auto itr = headers.find("Content-Type"); itr == headers.end()) { - headers["Content-Type"] = "application/x-www-form-urlencoded"; + itr->second = "application/x-www-form-urlencoded"; } std::string finalHeaders; @@ -296,20 +296,20 @@ namespace Utils if (HttpSendRequestA(this->hFile, finalHeaders.data(), finalHeaders.size(), const_cast(body.data()), body.size() + 1) == FALSE) { - return ""; + return {}; } DWORD statusCode = 404; DWORD length = sizeof(statusCode); - if (HttpQueryInfo(this->hFile, HTTP_QUERY_FLAG_NUMBER | HTTP_QUERY_STATUS_CODE, &statusCode, &length, nullptr) == FALSE || (statusCode != 200 && statusCode != 201)) + if (HttpQueryInfoA(this->hFile, HTTP_QUERY_FLAG_NUMBER | HTTP_QUERY_STATUS_CODE, &statusCode, &length, nullptr) == FALSE || (statusCode != 200 && statusCode != 201)) { this->closeConnection(); - return ""; + return {}; } DWORD contentLength = 0; length = sizeof(statusCode); - if (HttpQueryInfo(this->hFile, HTTP_QUERY_FLAG_NUMBER | HTTP_QUERY_CONTENT_LENGTH, &contentLength, &length, nullptr) == FALSE) + if (HttpQueryInfoA(this->hFile, HTTP_QUERY_FLAG_NUMBER | HTTP_QUERY_CONTENT_LENGTH, &contentLength, &length, nullptr) == FALSE) { contentLength = 0; } @@ -317,15 +317,15 @@ namespace Utils std::string returnBuffer; returnBuffer.reserve(contentLength); - DWORD size = 0; - char buffer[0x2001] = { 0 }; + DWORD size{}; + char buffer[0x2001]{}; - while (InternetReadFile(this->hFile, buffer, 0x2000, &size)) + while (InternetReadFile(this->hFile, buffer, sizeof(buffer) - 1, &size)) { if (this->cancel) { this->closeConnection(); - return ""; + return {}; } returnBuffer.append(buffer, size); @@ -339,9 +339,9 @@ namespace Utils return returnBuffer; } - bool WebIO::isSecuredConnection() + bool WebIO::isSecuredConnection() const { - return (this->url.protocol == "https"); + return this->url.protocol == "https"s; } bool WebIO::connect() @@ -368,7 +368,7 @@ namespace Utils this->formatPath(directory, true); this->formatPath(currentDir, true); - char path[MAX_PATH] = { 0 }; + char path[MAX_PATH]{}; PathCombineA(path, currentDir.data(), directory.data()); std::string newPath(path); @@ -384,8 +384,8 @@ namespace Utils { directory.clear(); - DWORD size = MAX_PATH; - char currentDir[MAX_PATH] = { 0 }; + char currentDir[MAX_PATH]{}; + DWORD size = sizeof(currentDir); if (FtpGetCurrentDirectoryA(this->hConnect, currentDir, &size) == TRUE) { @@ -398,7 +398,7 @@ namespace Utils void WebIO::formatPath(std::string& path, bool win) { - size_t nPos; + std::size_t nPos; std::string find = "\\"; std::string replace = "/"; @@ -451,7 +451,7 @@ namespace Utils WIN32_FIND_DATAA findFileData; bool result = false; - DWORD dwAttribute = (files ? FILE_ATTRIBUTE_NORMAL : FILE_ATTRIBUTE_DIRECTORY); + const DWORD dwAttribute = (files ? FILE_ATTRIBUTE_NORMAL : FILE_ATTRIBUTE_DIRECTORY); // Any filename. std::string tempDir; @@ -469,8 +469,7 @@ namespace Utils if (findFileData.dwFileAttributes == dwAttribute) // No bitwise flag check, as it might return archives/offline/hidden or other files/dirs { - //printf("%s: %X\n", findFileData.cFileName, findFileData.dwFileAttributes); - list.push_back(findFileData.cFileName); + list.emplace_back(findFileData.cFileName); result = true; } } while (InternetFindNextFileA(this->hFile, &findFileData)); @@ -556,7 +555,7 @@ namespace Utils return false; } - void WebIO::setProgressCallback(Utils::Slot callback) + void WebIO::setProgressCallback(const Slot& callback) { this->progressCallback = callback; } diff --git a/src/Utils/WebIO.hpp b/src/Utils/WebIO.hpp index 07af0c0f..712c60c3 100644 --- a/src/Utils/WebIO.hpp +++ b/src/Utils/WebIO.hpp @@ -30,9 +30,9 @@ namespace Utils std::string postFile(const std::string& url, const std::string& data, const std::string& fieldName, const std::string& fileName); std::string postFile(const std::string& data, std::string fieldName, std::string fileName); - std::string post(const std::string& url, WebIO::Params params, bool* success = nullptr); + std::string post(const std::string& url, Params params, bool* success = nullptr); std::string post(const std::string& url, const std::string& body, bool* success = nullptr); - std::string post(WebIO::Params params, bool* success = nullptr); + std::string post(Params params, bool* success = nullptr); std::string post(const std::string& body, bool* success = nullptr); std::string get(const std::string& url, bool* success = nullptr); @@ -62,7 +62,7 @@ namespace Utils bool uploadFileData(const std::string& file,const std::string& data); bool downloadFileData(const std::string& file, std::string& data); - void setProgressCallback(Utils::Slot callback); + void setProgressCallback(const Slot& callback); void cancelDownload() { this->cancel = true; } private: @@ -96,13 +96,13 @@ namespace Utils DWORD timeout; - Utils::Slot progressCallback; + Slot progressCallback; - std::string buildPostBody(WebIO::Params params); + static std::string buildPostBody(Params params); - bool isSecuredConnection(); + bool isSecuredConnection() const; - std::string execute(const char* command, const std::string& body, WebIO::Params headers = WebIO::Params(), bool* success = nullptr); + std::string execute(const char* command, const std::string& body, Params headers = {}, bool* success = nullptr); bool listElements(const std::string& directory, std::vector& list, bool files); @@ -112,6 +112,6 @@ namespace Utils bool openConnection(); void closeConnection(); - void formatPath(std::string& path, bool win); /* if (win == true): / -> \\ */ + static void formatPath(std::string& path, bool win); /* if (win == true): / -> \\ */ }; }