diff options
Diffstat (limited to 'src/util')
32 files changed, 1675 insertions, 1760 deletions
diff --git a/src/util/areastore.cpp b/src/util/areastore.cpp index cea526336..9754f96eb 100644 --- a/src/util/areastore.cpp +++ b/src/util/areastore.cpp @@ -22,28 +22,27 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/container.h" #if USE_SPATIAL - #include <spatialindex/SpatialIndex.h> - #include <spatialindex/RTree.h> - #include <spatialindex/Point.h> +#include <spatialindex/SpatialIndex.h> +#include <spatialindex/RTree.h> +#include <spatialindex/Point.h> #endif #define AST_SMALLER_EQ_AS(p, q) (((p).X <= (q).X) && ((p).Y <= (q).Y) && ((p).Z <= (q).Z)) -#define AST_OVERLAPS_IN_DIMENSION(amine, amaxe, b, d) \ +#define AST_OVERLAPS_IN_DIMENSION(amine, amaxe, b, d) \ (!(((amine).d > (b)->maxedge.d) || ((amaxe).d < (b)->minedge.d))) -#define AST_CONTAINS_PT(a, p) (AST_SMALLER_EQ_AS((a)->minedge, (p)) && \ - AST_SMALLER_EQ_AS((p), (a)->maxedge)) +#define AST_CONTAINS_PT(a, p) \ + (AST_SMALLER_EQ_AS((a)->minedge, (p)) && AST_SMALLER_EQ_AS((p), (a)->maxedge)) -#define AST_CONTAINS_AREA(amine, amaxe, b) \ - (AST_SMALLER_EQ_AS((amine), (b)->minedge) \ - && AST_SMALLER_EQ_AS((b)->maxedge, (amaxe))) - -#define AST_AREAS_OVERLAP(amine, amaxe, b) \ - (AST_OVERLAPS_IN_DIMENSION((amine), (amaxe), (b), X) && \ - AST_OVERLAPS_IN_DIMENSION((amine), (amaxe), (b), Y) && \ - AST_OVERLAPS_IN_DIMENSION((amine), (amaxe), (b), Z)) +#define AST_CONTAINS_AREA(amine, amaxe, b) \ + (AST_SMALLER_EQ_AS((amine), (b)->minedge) && \ + AST_SMALLER_EQ_AS((b)->maxedge, (amaxe))) +#define AST_AREAS_OVERLAP(amine, amaxe, b) \ + (AST_OVERLAPS_IN_DIMENSION((amine), (amaxe), (b), X) && \ + AST_OVERLAPS_IN_DIMENSION((amine), (amaxe), (b), Y) && \ + AST_OVERLAPS_IN_DIMENSION((amine), (amaxe), (b), Z)) AreaStore *AreaStore::getOptimalImplementation() { @@ -92,7 +91,7 @@ void AreaStore::deserialize(std::istream &is) // Assume forwards-compatibility before version 5 if (ver >= 5) throw SerializationError("Unknown AreaStore " - "serialization version!"); + "serialization version!"); u16 num_areas = readU16(is); std::vector<Area> areas; @@ -105,7 +104,7 @@ void AreaStore::deserialize(std::istream &is) is.read(data, data_len); a.data = std::string(data, data_len); areas.emplace_back(a); - delete [] data; + delete[] data; } bool read_ids = is.good(); // EOF for old formats @@ -152,10 +151,7 @@ void AreaStore::cacheMiss(void *data, const v3s16 &mpos, std::vector<Area *> *de // get the points at the edges of the mapblock v3s16 minedge(mpos.X * r, mpos.Y * r, mpos.Z * r); - v3s16 maxedge( - minedge.X + r - 1, - minedge.Y + r - 1, - minedge.Z + r - 1); + v3s16 maxedge(minedge.X + r - 1, minedge.Y + r - 1, minedge.Z + r - 1); as->getAreasInArea(dest, minedge, maxedge, true); @@ -184,12 +180,10 @@ void AreaStore::getAreasForPos(std::vector<Area *> *result, v3s16 pos) } } - //// // VectorAreaStore //// - bool VectorAreaStore::insertArea(Area *a) { if (a->id == U32_MAX) @@ -210,8 +204,8 @@ bool VectorAreaStore::removeArea(u32 id) if (it == areas_map.end()) return false; Area *a = &it->second; - for (std::vector<Area *>::iterator v_it = m_areas.begin(); - v_it != m_areas.end(); ++v_it) { + for (std::vector<Area *>::iterator v_it = m_areas.begin(); v_it != m_areas.end(); + ++v_it) { if (*v_it == a) { m_areas.erase(v_it); break; @@ -231,12 +225,12 @@ void VectorAreaStore::getAreasForPosImpl(std::vector<Area *> *result, v3s16 pos) } } -void VectorAreaStore::getAreasInArea(std::vector<Area *> *result, - v3s16 minedge, v3s16 maxedge, bool accept_overlap) +void VectorAreaStore::getAreasInArea(std::vector<Area *> *result, v3s16 minedge, + v3s16 maxedge, bool accept_overlap) { for (Area *area : m_areas) { - if (accept_overlap ? AST_AREAS_OVERLAP(minedge, maxedge, area) : - AST_CONTAINS_AREA(minedge, maxedge, area)) { + if (accept_overlap ? AST_AREAS_OVERLAP(minedge, maxedge, area) + : AST_CONTAINS_AREA(minedge, maxedge, area)) { result->push_back(area); } } @@ -244,13 +238,11 @@ void VectorAreaStore::getAreasInArea(std::vector<Area *> *result, #if USE_SPATIAL -static inline SpatialIndex::Region get_spatial_region(const v3s16 minedge, - const v3s16 maxedge) +static inline SpatialIndex::Region get_spatial_region( + const v3s16 minedge, const v3s16 maxedge) { - const double p_low[] = {(double)minedge.X, - (double)minedge.Y, (double)minedge.Z}; - const double p_high[] = {(double)maxedge.X, (double)maxedge.Y, - (double)maxedge.Z}; + const double p_low[] = {(double)minedge.X, (double)minedge.Y, (double)minedge.Z}; + const double p_high[] = {(double)maxedge.X, (double)maxedge.Y, (double)maxedge.Z}; return SpatialIndex::Region(p_low, p_high, 3); } @@ -260,7 +252,6 @@ static inline SpatialIndex::Point get_spatial_point(const v3s16 pos) return SpatialIndex::Point(p, 3); } - bool SpatialAreaStore::insertArea(Area *a) { if (a->id == U32_MAX) @@ -278,8 +269,8 @@ bool SpatialAreaStore::removeArea(u32 id) std::map<u32, Area>::iterator itr = areas_map.find(id); if (itr != areas_map.end()) { Area *a = &itr->second; - bool result = m_tree->deleteData(get_spatial_region(a->minedge, - a->maxedge), id); + bool result = m_tree->deleteData( + get_spatial_region(a->minedge, a->maxedge), id); areas_map.erase(itr); invalidateCache(); return result; @@ -294,13 +285,13 @@ void SpatialAreaStore::getAreasForPosImpl(std::vector<Area *> *result, v3s16 pos m_tree->pointLocationQuery(get_spatial_point(pos), visitor); } -void SpatialAreaStore::getAreasInArea(std::vector<Area *> *result, - v3s16 minedge, v3s16 maxedge, bool accept_overlap) +void SpatialAreaStore::getAreasInArea(std::vector<Area *> *result, v3s16 minedge, + v3s16 maxedge, bool accept_overlap) { VectorResultVisitor visitor(result, this); if (accept_overlap) { - m_tree->intersectsWithQuery(get_spatial_region(minedge, maxedge), - visitor); + m_tree->intersectsWithQuery( + get_spatial_region(minedge, maxedge), visitor); } else { m_tree->containsWhatQuery(get_spatial_region(minedge, maxedge), visitor); } @@ -313,17 +304,14 @@ SpatialAreaStore::~SpatialAreaStore() SpatialAreaStore::SpatialAreaStore() { - m_storagemanager = - SpatialIndex::StorageManager::createNewMemoryStorageManager(); + m_storagemanager = SpatialIndex::StorageManager::createNewMemoryStorageManager(); SpatialIndex::id_type id; - m_tree = SpatialIndex::RTree::createNewRTree( - *m_storagemanager, - .7, // Fill factor - 100, // Index capacity - 100, // Leaf capacity - 3, // dimension :) - SpatialIndex::RTree::RV_RSTAR, - id); + m_tree = SpatialIndex::RTree::createNewRTree(*m_storagemanager, + .7, // Fill factor + 100, // Index capacity + 100, // Leaf capacity + 3, // dimension :) + SpatialIndex::RTree::RV_RSTAR, id); } #endif diff --git a/src/util/areastore.h b/src/util/areastore.h index 150a043db..9a44bf231 100644 --- a/src/util/areastore.h +++ b/src/util/areastore.h @@ -28,19 +28,19 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/container.h" #include "util/numeric.h" #ifndef ANDROID - #include "cmake_config.h" +#include "cmake_config.h" #endif #if USE_SPATIAL - #include <spatialindex/SpatialIndex.h> - #include "util/serialize.h" +#include <spatialindex/SpatialIndex.h> +#include "util/serialize.h" #endif - -struct Area { +struct Area +{ Area(u32 area_id) : id(area_id) {} Area(const v3s16 &mine, const v3s16 &maxe, u32 area_id = U32_MAX) : - id(area_id), minedge(mine), maxedge(maxe) + id(area_id), minedge(mine), maxedge(maxe) { sortBoxVerticies(minedge, maxedge); } @@ -50,18 +50,16 @@ struct Area { std::string data; }; - -class AreaStore { +class AreaStore +{ public: - AreaStore() : - m_res_cache(1000, &cacheMiss, this) - {} + AreaStore() : m_res_cache(1000, &cacheMiss, this) {} virtual ~AreaStore() = default; static AreaStore *getOptimalImplementation(); - virtual void reserve(size_t count) {}; + virtual void reserve(size_t count){}; size_t size() const { return areas_map.size(); } /// Add an area to the store. @@ -80,8 +78,8 @@ public: /// Finds areas that are completely contained inside the area defined /// by the passed edges. If @p accept_overlap is true this finds any /// areas that intersect with the passed area at any point. - virtual void getAreasInArea(std::vector<Area *> *result, - v3s16 minedge, v3s16 maxedge, bool accept_overlap) = 0; + virtual void getAreasInArea(std::vector<Area *> *result, v3s16 minedge, + v3s16 maxedge, bool accept_overlap) = 0; /// Sets cache parameters. void setCacheParams(bool enabled, u8 block_radius, size_t limit); @@ -124,17 +122,17 @@ private: /// Range, in nodes, of the getAreasForPos cache. /// If you modify this, call invalidateCache() u8 m_cacheblock_radius = 64; - LRUCache<v3s16, std::vector<Area *> > m_res_cache; + LRUCache<v3s16, std::vector<Area *>> m_res_cache; }; - -class VectorAreaStore : public AreaStore { +class VectorAreaStore : public AreaStore +{ public: virtual void reserve(size_t count) { m_areas.reserve(count); } virtual bool insertArea(Area *a); virtual bool removeArea(u32 id); - virtual void getAreasInArea(std::vector<Area *> *result, - v3s16 minedge, v3s16 maxedge, bool accept_overlap); + virtual void getAreasInArea(std::vector<Area *> *result, v3s16 minedge, + v3s16 maxedge, bool accept_overlap); protected: virtual void getAreasForPosImpl(std::vector<Area *> *result, v3s16 pos); @@ -143,18 +141,18 @@ private: std::vector<Area *> m_areas; }; - #if USE_SPATIAL -class SpatialAreaStore : public AreaStore { +class SpatialAreaStore : public AreaStore +{ public: SpatialAreaStore(); virtual ~SpatialAreaStore(); virtual bool insertArea(Area *a); virtual bool removeArea(u32 id); - virtual void getAreasInArea(std::vector<Area *> *result, - v3s16 minedge, v3s16 maxedge, bool accept_overlap); + virtual void getAreasInArea(std::vector<Area *> *result, v3s16 minedge, + v3s16 maxedge, bool accept_overlap); protected: virtual void getAreasForPosImpl(std::vector<Area *> *result, v3s16 pos); @@ -163,12 +161,15 @@ private: SpatialIndex::ISpatialIndex *m_tree = nullptr; SpatialIndex::IStorageManager *m_storagemanager = nullptr; - class VectorResultVisitor : public SpatialIndex::IVisitor { + class VectorResultVisitor : public SpatialIndex::IVisitor + { public: - VectorResultVisitor(std::vector<Area *> *result, SpatialAreaStore *store) : - m_store(store), - m_result(result) - {} + VectorResultVisitor( + std::vector<Area *> *result, SpatialAreaStore *store) : + m_store(store), + m_result(result) + { + } ~VectorResultVisitor() {} virtual void visitNode(const SpatialIndex::INode &in) {} diff --git a/src/util/auth.cpp b/src/util/auth.cpp index 3dd5a9afa..8a208b2c2 100644 --- a/src/util/auth.cpp +++ b/src/util/auth.cpp @@ -31,8 +31,7 @@ with this program; if not, write to the Free Software Foundation, Inc., // their password. (Exception : if the password field is // blank, we send a blank password - this is for backwards // compatibility with password-less players). -std::string translate_password(const std::string &name, - const std::string &password) +std::string translate_password(const std::string &name, const std::string &password) { if (password.length() == 0) return ""; @@ -50,21 +49,20 @@ std::string translate_password(const std::string &name, // given pointers. Contains the preparations, call parameters // and error checking common to all srp verifier generation code. // See docs of srp_create_salted_verification_key for more info. -static inline void gen_srp_v(const std::string &name, - const std::string &password, char **salt, size_t *salt_len, - char **bytes_v, size_t *len_v) +static inline void gen_srp_v(const std::string &name, const std::string &password, + char **salt, size_t *salt_len, char **bytes_v, size_t *len_v) { std::string n_name = lowercase(name); SRP_Result res = srp_create_salted_verification_key(SRP_SHA256, SRP_NG_2048, - n_name.c_str(), (const unsigned char *)password.c_str(), - password.size(), (unsigned char **)salt, salt_len, - (unsigned char **)bytes_v, len_v, NULL, NULL); + n_name.c_str(), (const unsigned char *)password.c_str(), + password.size(), (unsigned char **)salt, salt_len, + (unsigned char **)bytes_v, len_v, NULL, NULL); FATAL_ERROR_IF(res != SRP_OK, "Couldn't create salted SRP verifier"); } /// Creates a verification key with given salt and password. -std::string generate_srp_verifier(const std::string &name, - const std::string &password, const std::string &salt) +std::string generate_srp_verifier(const std::string &name, const std::string &password, + const std::string &salt) { size_t salt_len = salt.size(); // The API promises us that the salt doesn't @@ -80,9 +78,8 @@ std::string generate_srp_verifier(const std::string &name, } /// Creates a verification key and salt with given password. -void generate_srp_verifier_and_salt(const std::string &name, - const std::string &password, std::string *verifier, - std::string *salt) +void generate_srp_verifier_and_salt(const std::string &name, const std::string &password, + std::string *verifier, std::string *salt) { char *bytes_v = nullptr; size_t verifier_len; @@ -97,8 +94,7 @@ void generate_srp_verifier_and_salt(const std::string &name, /// Gets an SRP verifier, generating a salt, /// and encodes it as DB-ready string. -std::string get_encoded_srp_verifier(const std::string &name, - const std::string &password) +std::string get_encoded_srp_verifier(const std::string &name, const std::string &password) { std::string verifier; std::string salt; @@ -107,31 +103,28 @@ std::string get_encoded_srp_verifier(const std::string &name, } /// Converts the passed SRP verifier into a DB-ready format. -std::string encode_srp_verifier(const std::string &verifier, - const std::string &salt) +std::string encode_srp_verifier(const std::string &verifier, const std::string &salt) { std::ostringstream ret_str; - ret_str << "#1#" - << base64_encode((unsigned char *)salt.c_str(), salt.size()) << "#" + ret_str << "#1#" << base64_encode((unsigned char *)salt.c_str(), salt.size()) + << "#" << base64_encode((unsigned char *)verifier.c_str(), verifier.size()); return ret_str.str(); } /// Reads the DB-formatted SRP verifier and gets the verifier /// and salt components. -bool decode_srp_verifier_and_salt(const std::string &encoded, - std::string *verifier, std::string *salt) +bool decode_srp_verifier_and_salt( + const std::string &encoded, std::string *verifier, std::string *salt) { std::vector<std::string> components = str_split(encoded, '#'); - if ((components.size() != 4) - || (components[1] != "1") // 1 means srp - || !base64_is_valid(components[2]) - || !base64_is_valid(components[3])) + if ((components.size() != 4) || (components[1] != "1") // 1 means srp + || !base64_is_valid(components[2]) || + !base64_is_valid(components[3])) return false; *salt = base64_decode(components[2]); *verifier = base64_decode(components[3]); return true; - } diff --git a/src/util/auth.h b/src/util/auth.h index ba827f322..c04bb63a6 100644 --- a/src/util/auth.h +++ b/src/util/auth.h @@ -20,28 +20,25 @@ with this program; if not, write to the Free Software Foundation, Inc., #pragma once /// Gets the base64 encoded legacy password db entry. -std::string translate_password(const std::string &name, - const std::string &password); +std::string translate_password(const std::string &name, const std::string &password); /// Creates a verification key with given salt and password. -std::string generate_srp_verifier(const std::string &name, - const std::string &password, const std::string &salt); +std::string generate_srp_verifier(const std::string &name, const std::string &password, + const std::string &salt); /// Creates a verification key and salt with given password. -void generate_srp_verifier_and_salt(const std::string &name, - const std::string &password, std::string *verifier, - std::string *salt); +void generate_srp_verifier_and_salt(const std::string &name, const std::string &password, + std::string *verifier, std::string *salt); /// Gets an SRP verifier, generating a salt, /// and encodes it as DB-ready string. -std::string get_encoded_srp_verifier(const std::string &name, - const std::string &password); +std::string get_encoded_srp_verifier( + const std::string &name, const std::string &password); /// Converts the passed SRP verifier into a DB-ready format. -std::string encode_srp_verifier(const std::string &verifier, - const std::string &salt); +std::string encode_srp_verifier(const std::string &verifier, const std::string &salt); /// Reads the DB-formatted SRP verifier and gets the verifier /// and salt components. -bool decode_srp_verifier_and_salt(const std::string &encoded, - std::string *verifier, std::string *salt); +bool decode_srp_verifier_and_salt( + const std::string &encoded, std::string *verifier, std::string *salt); diff --git a/src/util/base64.cpp b/src/util/base64.cpp index c75f98598..7150913de 100644 --- a/src/util/base64.cpp +++ b/src/util/base64.cpp @@ -28,17 +28,16 @@ RenĂ© Nyffenegger rene.nyffenegger@adp-gmbh.ch #include "base64.h" #include <iostream> -static const std::string base64_chars = - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789+/"; +static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; - -static inline bool is_base64(unsigned char c) { +static inline bool is_base64(unsigned char c) +{ return (isalnum(c) || (c == '+') || (c == '/')); } -bool base64_is_valid(std::string const& s) +bool base64_is_valid(std::string const &s) { for (char i : s) if (!is_base64(i)) @@ -46,7 +45,8 @@ bool base64_is_valid(std::string const& s) return true; } -std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) { +std::string base64_encode(unsigned char const *bytes_to_encode, unsigned int in_len) +{ std::string ret; int i = 0; int j = 0; @@ -57,40 +57,42 @@ std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_ char_array_3[i++] = *(bytes_to_encode++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; - char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); - char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); + char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + + ((char_array_3[1] & 0xf0) >> 4); + char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; - for(i = 0; (i <4) ; i++) + for (i = 0; (i < 4); i++) ret += base64_chars[char_array_4[i]]; i = 0; } } - if (i) - { - for(j = i; j < 3; j++) + if (i) { + for (j = i; j < 3; j++) char_array_3[j] = '\0'; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; - char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); - char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); + char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + + ((char_array_3[1] & 0xf0) >> 4); + char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0; (j < i + 1); j++) ret += base64_chars[char_array_4[j]]; - // Don't pad it with = + // Don't pad it with = /*while((i++ < 3)) ret += '=';*/ - } return ret; - } -std::string base64_decode(std::string const& encoded_string) { +std::string base64_decode(std::string const &encoded_string) +{ int in_len = encoded_string.size(); int i = 0; int j = 0; @@ -98,15 +100,20 @@ std::string base64_decode(std::string const& encoded_string) { unsigned char char_array_4[4], char_array_3[3]; std::string ret; - while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { - char_array_4[i++] = encoded_string[in_]; in_++; - if (i ==4) { - for (i = 0; i <4; i++) + while (in_len-- && (encoded_string[in_] != '=') && + is_base64(encoded_string[in_])) { + char_array_4[i++] = encoded_string[in_]; + in_++; + if (i == 4) { + for (i = 0; i < 4; i++) char_array_4[i] = base64_chars.find(char_array_4[i]); - char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); - char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); - char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; + char_array_3[0] = (char_array_4[0] << 2) + + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[2] = + ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (i = 0; (i < 3); i++) ret += char_array_3[i]; @@ -115,17 +122,20 @@ std::string base64_decode(std::string const& encoded_string) { } if (i) { - for (j = i; j <4; j++) + for (j = i; j < 4; j++) char_array_4[j] = 0; - for (j = 0; j <4; j++) + for (j = 0; j < 4; j++) char_array_4[j] = base64_chars.find(char_array_4[j]); - char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); - char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[0] = + (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; - for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; + for (j = 0; (j < i - 1); j++) + ret += char_array_3[j]; } return ret; diff --git a/src/util/base64.h b/src/util/base64.h index 7f2bf1368..d837adc5d 100644 --- a/src/util/base64.h +++ b/src/util/base64.h @@ -21,6 +21,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <string> -bool base64_is_valid(std::string const& s); -std::string base64_encode(unsigned char const* , unsigned int len); -std::string base64_decode(std::string const& s); +bool base64_is_valid(std::string const &s); +std::string base64_encode(unsigned char const *, unsigned int len); +std::string base64_decode(std::string const &s); diff --git a/src/util/basic_macros.h b/src/util/basic_macros.h index 334e342e0..2d5cdb3b4 100644 --- a/src/util/basic_macros.h +++ b/src/util/basic_macros.h @@ -32,27 +32,26 @@ with this program; if not, write to the Free Software Foundation, Inc., // 'Foobar', add the macro DISABLE_CLASS_COPY(Foobar) as a private member. // Note this also disables copying for any classes derived from 'Foobar' as well // as classes having a 'Foobar' member. -#define DISABLE_CLASS_COPY(C) \ - C(const C &) = delete; \ +#define DISABLE_CLASS_COPY(C) \ + C(const C &) = delete; \ C &operator=(const C &) = delete; #ifndef _MSC_VER - #define UNUSED_ATTRIBUTE __attribute__ ((unused)) +#define UNUSED_ATTRIBUTE __attribute__((unused)) #else - #define UNUSED_ATTRIBUTE +#define UNUSED_ATTRIBUTE #endif // Fail compilation if condition expr is not met. // Note that 'msg' must follow the format of a valid identifier, e.g. // STATIC_ASSERT(sizeof(foobar_t) == 40), foobar_t_is_wrong_size); -#define STATIC_ASSERT(expr, msg) \ - UNUSED_ATTRIBUTE typedef char msg[!!(expr) * 2 - 1] +#define STATIC_ASSERT(expr, msg) UNUSED_ATTRIBUTE typedef char msg[!!(expr)*2 - 1] // Macros to facilitate writing position vectors to a stream // Usage: // v3s16 pos(1,2,3); // mystream << "message " << PP(pos) << std::endl; -#define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")" +#define PP(x) "(" << (x).X << "," << (x).Y << "," << (x).Z << ")" -#define PP2(x) "("<<(x).X<<","<<(x).Y<<")" +#define PP2(x) "(" << (x).X << "," << (x).Y << ")" diff --git a/src/util/container.h b/src/util/container.h index 2ad2bbfc7..7be04459d 100644 --- a/src/util/container.h +++ b/src/util/container.h @@ -33,21 +33,18 @@ with this program; if not, write to the Free Software Foundation, Inc., Queue with unique values with fast checking of value existence */ -template<typename Value> -class UniqueQueue +template <typename Value> class UniqueQueue { public: - /* Does nothing if value is already queued. Return value: true: value added false: value already exists */ - bool push_back(const Value& value) + bool push_back(const Value &value) { - if (m_set.insert(value).second) - { + if (m_set.insert(value).second) { m_queue.push(value); return true; } @@ -60,23 +57,16 @@ public: m_queue.pop(); } - const Value& front() const - { - return m_queue.front(); - } + const Value &front() const { return m_queue.front(); } - u32 size() const - { - return m_queue.size(); - } + u32 size() const { return m_queue.size(); } private: std::set<Value> m_set; std::queue<Value> m_queue; }; -template<typename Key, typename Value> -class MutexedMap +template <typename Key, typename Value> class MutexedMap { public: MutexedMap() = default; @@ -90,8 +80,7 @@ public: bool get(const Key &name, Value *result) const { MutexAutoLock lock(m_mutex); - typename std::map<Key, Value>::const_iterator n = - m_values.find(name); + typename std::map<Key, Value>::const_iterator n = m_values.find(name); if (n == m_values.end()) return false; if (result) @@ -103,9 +92,8 @@ public: { MutexAutoLock lock(m_mutex); std::vector<Value> result; - for (typename std::map<Key, Value>::const_iterator - it = m_values.begin(); - it != m_values.end(); ++it){ + for (typename std::map<Key, Value>::const_iterator it = m_values.begin(); + it != m_values.end(); ++it) { result.push_back(it->second); } return result; @@ -118,14 +106,12 @@ private: mutable std::mutex m_mutex; }; - // Thread-safe Double-ended queue -template<typename T> -class MutexedQueue +template <typename T> class MutexedQueue { public: - template<typename Key, typename U, typename Caller, typename CallerData> + template <typename Key, typename U, typename Caller, typename CallerData> friend class RequestQueue; MutexedQueue() = default; @@ -144,8 +130,8 @@ public: } /* this version of pop_front returns a empty element of T on timeout. - * Make sure default constructor of T creates a recognizable "empty" element - */ + * Make sure default constructor of T creates a recognizable "empty" element + */ T pop_frontNoEx(u32 wait_time_max_ms) { if (m_signal.wait(wait_time_max_ms)) { @@ -183,7 +169,7 @@ public: return t; } - T pop_back(u32 wait_time_max_ms=0) + T pop_back(u32 wait_time_max_ms = 0) { if (m_signal.wait(wait_time_max_ms)) { MutexAutoLock lock(m_mutex); @@ -197,8 +183,8 @@ public: } /* this version of pop_back returns a empty element of T on timeout. - * Make sure default constructor of T creates a recognizable "empty" element - */ + * Make sure default constructor of T creates a recognizable "empty" element + */ T pop_backNoEx(u32 wait_time_max_ms) { if (m_signal.wait(wait_time_max_ms)) { @@ -233,8 +219,7 @@ protected: Semaphore m_signal; }; -template<typename K, typename V> -class LRUCache +template <typename K, typename V> class LRUCache { public: LRUCache(size_t limit, void (*cache_miss)(void *data, const K &key, V *dest), @@ -274,8 +259,7 @@ public: entry.first = m_queue.begin(); } else { // cache miss -- enter into cache - cache_entry_t &entry = - m_map[key]; + cache_entry_t &entry = m_map[key]; ret = &entry.second; m_cache_miss(m_cache_miss_data, key, &entry.second); @@ -291,11 +275,13 @@ public: } return ret; } + private: void (*m_cache_miss)(void *data, const K &key, V *dest); void *m_cache_miss_data; size_t m_limit; - typedef typename std::template pair<typename std::template list<K>::iterator, V> cache_entry_t; + typedef typename std::template pair<typename std::template list<K>::iterator, V> + cache_entry_t; typedef std::template map<K, cache_entry_t> cache_type; cache_type m_map; // we can't use std::deque here, because its iterators get invalidated diff --git a/src/util/directiontables.cpp b/src/util/directiontables.cpp index 296585f90..fba432c15 100644 --- a/src/util/directiontables.cpp +++ b/src/util/directiontables.cpp @@ -19,102 +19,91 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "directiontables.h" -const v3s16 g_6dirs[6] = -{ - // +right, +top, +back - v3s16( 0, 0, 1), // back - v3s16( 0, 1, 0), // top - v3s16( 1, 0, 0), // right - v3s16( 0, 0,-1), // front - v3s16( 0,-1, 0), // bottom - v3s16(-1, 0, 0) // left +const v3s16 g_6dirs[6] = { + // +right, +top, +back + v3s16(0, 0, 1), // back + v3s16(0, 1, 0), // top + v3s16(1, 0, 0), // right + v3s16(0, 0, -1), // front + v3s16(0, -1, 0), // bottom + v3s16(-1, 0, 0) // left }; -const v3s16 g_7dirs[7] = -{ - v3s16(0,0,1), // back - v3s16(0,1,0), // top - v3s16(1,0,0), // right - v3s16(0,0,-1), // front - v3s16(0,-1,0), // bottom - v3s16(-1,0,0), // left - v3s16(0,0,0), // self +const v3s16 g_7dirs[7] = { + v3s16(0, 0, 1), // back + v3s16(0, 1, 0), // top + v3s16(1, 0, 0), // right + v3s16(0, 0, -1), // front + v3s16(0, -1, 0), // bottom + v3s16(-1, 0, 0), // left + v3s16(0, 0, 0), // self }; -const v3s16 g_26dirs[26] = -{ - // +right, +top, +back - v3s16( 0, 0, 1), // back - v3s16( 0, 1, 0), // top - v3s16( 1, 0, 0), // right - v3s16( 0, 0,-1), // front - v3s16( 0,-1, 0), // bottom - v3s16(-1, 0, 0), // left - // 6 - v3s16(-1, 1, 0), // top left - v3s16( 1, 1, 0), // top right - v3s16( 0, 1, 1), // top back - v3s16( 0, 1,-1), // top front - v3s16(-1, 0, 1), // back left - v3s16( 1, 0, 1), // back right - v3s16(-1, 0,-1), // front left - v3s16( 1, 0,-1), // front right - v3s16(-1,-1, 0), // bottom left - v3s16( 1,-1, 0), // bottom right - v3s16( 0,-1, 1), // bottom back - v3s16( 0,-1,-1), // bottom front - // 18 - v3s16(-1, 1, 1), // top back-left - v3s16( 1, 1, 1), // top back-right - v3s16(-1, 1,-1), // top front-left - v3s16( 1, 1,-1), // top front-right - v3s16(-1,-1, 1), // bottom back-left - v3s16( 1,-1, 1), // bottom back-right - v3s16(-1,-1,-1), // bottom front-left - v3s16( 1,-1,-1), // bottom front-right - // 26 +const v3s16 g_26dirs[26] = { + // +right, +top, +back + v3s16(0, 0, 1), // back + v3s16(0, 1, 0), // top + v3s16(1, 0, 0), // right + v3s16(0, 0, -1), // front + v3s16(0, -1, 0), // bottom + v3s16(-1, 0, 0), // left + // 6 + v3s16(-1, 1, 0), // top left + v3s16(1, 1, 0), // top right + v3s16(0, 1, 1), // top back + v3s16(0, 1, -1), // top front + v3s16(-1, 0, 1), // back left + v3s16(1, 0, 1), // back right + v3s16(-1, 0, -1), // front left + v3s16(1, 0, -1), // front right + v3s16(-1, -1, 0), // bottom left + v3s16(1, -1, 0), // bottom right + v3s16(0, -1, 1), // bottom back + v3s16(0, -1, -1), // bottom front + // 18 + v3s16(-1, 1, 1), // top back-left + v3s16(1, 1, 1), // top back-right + v3s16(-1, 1, -1), // top front-left + v3s16(1, 1, -1), // top front-right + v3s16(-1, -1, 1), // bottom back-left + v3s16(1, -1, 1), // bottom back-right + v3s16(-1, -1, -1), // bottom front-left + v3s16(1, -1, -1), // bottom front-right + // 26 }; -const v3s16 g_27dirs[27] = -{ - // +right, +top, +back - v3s16( 0, 0, 1), // back - v3s16( 0, 1, 0), // top - v3s16( 1, 0, 0), // right - v3s16( 0, 0,-1), // front - v3s16( 0,-1, 0), // bottom - v3s16(-1, 0, 0), // left - // 6 - v3s16(-1, 1, 0), // top left - v3s16( 1, 1, 0), // top right - v3s16( 0, 1, 1), // top back - v3s16( 0, 1,-1), // top front - v3s16(-1, 0, 1), // back left - v3s16( 1, 0, 1), // back right - v3s16(-1, 0,-1), // front left - v3s16( 1, 0,-1), // front right - v3s16(-1,-1, 0), // bottom left - v3s16( 1,-1, 0), // bottom right - v3s16( 0,-1, 1), // bottom back - v3s16( 0,-1,-1), // bottom front - // 18 - v3s16(-1, 1, 1), // top back-left - v3s16( 1, 1, 1), // top back-right - v3s16(-1, 1,-1), // top front-left - v3s16( 1, 1,-1), // top front-right - v3s16(-1,-1, 1), // bottom back-left - v3s16( 1,-1, 1), // bottom back-right - v3s16(-1,-1,-1), // bottom front-left - v3s16( 1,-1,-1), // bottom front-right - // 26 - v3s16(0,0,0), +const v3s16 g_27dirs[27] = { + // +right, +top, +back + v3s16(0, 0, 1), // back + v3s16(0, 1, 0), // top + v3s16(1, 0, 0), // right + v3s16(0, 0, -1), // front + v3s16(0, -1, 0), // bottom + v3s16(-1, 0, 0), // left + // 6 + v3s16(-1, 1, 0), // top left + v3s16(1, 1, 0), // top right + v3s16(0, 1, 1), // top back + v3s16(0, 1, -1), // top front + v3s16(-1, 0, 1), // back left + v3s16(1, 0, 1), // back right + v3s16(-1, 0, -1), // front left + v3s16(1, 0, -1), // front right + v3s16(-1, -1, 0), // bottom left + v3s16(1, -1, 0), // bottom right + v3s16(0, -1, 1), // bottom back + v3s16(0, -1, -1), // bottom front + // 18 + v3s16(-1, 1, 1), // top back-left + v3s16(1, 1, 1), // top back-right + v3s16(-1, 1, -1), // top front-left + v3s16(1, 1, -1), // top front-right + v3s16(-1, -1, 1), // bottom back-left + v3s16(1, -1, 1), // bottom back-right + v3s16(-1, -1, -1), // bottom front-left + v3s16(1, -1, -1), // bottom front-right + // 26 + v3s16(0, 0, 0), }; -const u8 wallmounted_to_facedir[6] = { - 20, - 0, - 16 + 1, - 12 + 3, - 8, - 4 + 2 -}; +const u8 wallmounted_to_facedir[6] = {20, 0, 16 + 1, 12 + 3, 8, 4 + 2}; diff --git a/src/util/directiontables.h b/src/util/directiontables.h index ef00e3bfe..ea67521fc 100644 --- a/src/util/directiontables.h +++ b/src/util/directiontables.h @@ -35,15 +35,16 @@ extern const u8 wallmounted_to_facedir[6]; /// Direction in the 6D format. g_27dirs contains corresponding vectors. /// Here P means Positive, N stands for Negative. -enum Direction6D { -// 0 +enum Direction6D +{ + // 0 D6D_ZP, D6D_YP, D6D_XP, D6D_ZN, D6D_YN, D6D_XN, -// 6 + // 6 D6D_XN_YP, D6D_XP_YP, D6D_YP_ZP, @@ -56,7 +57,7 @@ enum Direction6D { D6D_XP_YN, D6D_YN_ZP, D6D_YN_ZN, -// 18 + // 18 D6D_XN_YP_ZP, D6D_XP_YP_ZP, D6D_XN_YP_ZN, @@ -65,21 +66,22 @@ enum Direction6D { D6D_XP_YN_ZP, D6D_XN_YN_ZN, D6D_XP_YN_ZN, -// 26 + // 26 D6D, -// aliases - D6D_BACK = D6D_ZP, - D6D_TOP = D6D_YP, - D6D_RIGHT = D6D_XP, - D6D_FRONT = D6D_ZN, + // aliases + D6D_BACK = D6D_ZP, + D6D_TOP = D6D_YP, + D6D_RIGHT = D6D_XP, + D6D_FRONT = D6D_ZN, D6D_BOTTOM = D6D_YN, - D6D_LEFT = D6D_XN, + D6D_LEFT = D6D_XN, }; /// Direction in the wallmounted format. /// P is Positive, N is Negative. -enum DirectionWallmounted { +enum DirectionWallmounted +{ DWM_YP, DWM_YN, DWM_XP, diff --git a/src/util/enriched_string.cpp b/src/util/enriched_string.cpp index 762d094eb..133c5930f 100644 --- a/src/util/enriched_string.cpp +++ b/src/util/enriched_string.cpp @@ -29,8 +29,8 @@ EnrichedString::EnrichedString() clear(); } -EnrichedString::EnrichedString(const std::wstring &string, - const std::vector<SColor> &colors) +EnrichedString::EnrichedString( + const std::wstring &string, const std::vector<SColor> &colors) { clear(); m_string = string; @@ -68,8 +68,8 @@ void EnrichedString::operator=(const wchar_t *str) void EnrichedString::addAtEnd(const std::wstring &s, const SColor &initial_color) { SColor color(initial_color); - bool use_default = (m_default_length == m_string.size() && - color == m_default_color); + bool use_default = + (m_default_length == m_string.size() && color == m_default_color); size_t i = 0; while (i < s.length()) { @@ -171,10 +171,9 @@ EnrichedString EnrichedString::substr(size_t pos, size_t len) const if (len == std::string::npos || pos + len > m_string.length()) len = m_string.length() - pos; - EnrichedString str( - m_string.substr(pos, len), - std::vector<SColor>(m_colors.begin() + pos, m_colors.begin() + pos + len) - ); + EnrichedString str(m_string.substr(pos, len), + std::vector<SColor>(m_colors.begin() + pos, + m_colors.begin() + pos + len)); str.m_has_background = m_has_background; str.m_background = m_background; diff --git a/src/util/enriched_string.h b/src/util/enriched_string.h index c8a095887..9bcccc060 100644 --- a/src/util/enriched_string.h +++ b/src/util/enriched_string.h @@ -23,15 +23,18 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <vector> #include <SColor.h> -class EnrichedString { +class EnrichedString +{ public: EnrichedString(); EnrichedString(const std::wstring &s, - const irr::video::SColor &color = irr::video::SColor(255, 255, 255, 255)); + const irr::video::SColor &color = irr::video::SColor( + 255, 255, 255, 255)); EnrichedString(const wchar_t *str, - const irr::video::SColor &color = irr::video::SColor(255, 255, 255, 255)); + const irr::video::SColor &color = irr::video::SColor( + 255, 255, 255, 255)); EnrichedString(const std::wstring &string, - const std::vector<irr::video::SColor> &colors); + const std::vector<irr::video::SColor> &colors); void clear(); void operator=(const wchar_t *str); void addAtEnd(const std::wstring &s, const irr::video::SColor &color); @@ -67,23 +70,11 @@ public: { return !(*this == other); } - inline bool empty() const - { - return m_string.empty(); - } - inline size_t size() const - { - return m_string.size(); - } + inline bool empty() const { return m_string.empty(); } + inline size_t size() const { return m_string.size(); } - inline bool hasBackground() const - { - return m_has_background; - } - inline irr::video::SColor getBackground() const - { - return m_background; - } + inline bool hasBackground() const { return m_has_background; } + inline irr::video::SColor getBackground() const { return m_background; } inline void setBackground(const irr::video::SColor &color) { m_background = color; diff --git a/src/util/md32_common.h b/src/util/md32_common.h index a4c2099c9..79a48e2af 100644 --- a/src/util/md32_common.h +++ b/src/util/md32_common.h @@ -112,31 +112,31 @@ #pragma once #if !defined(DATA_ORDER_IS_BIG_ENDIAN) && !defined(DATA_ORDER_IS_LITTLE_ENDIAN) -# error "DATA_ORDER must be defined!" +#error "DATA_ORDER must be defined!" #endif #ifndef HASH_CBLOCK -# error "HASH_CBLOCK must be defined!" +#error "HASH_CBLOCK must be defined!" #endif #ifndef HASH_LONG -# error "HASH_LONG must be defined!" +#error "HASH_LONG must be defined!" #endif #ifndef HASH_CTX -# error "HASH_CTX must be defined!" +#error "HASH_CTX must be defined!" #endif #ifndef HASH_UPDATE -# error "HASH_UPDATE must be defined!" +#error "HASH_UPDATE must be defined!" #endif #ifndef HASH_TRANSFORM -# error "HASH_TRANSFORM must be defined!" +#error "HASH_TRANSFORM must be defined!" #endif #ifndef HASH_FINAL -# error "HASH_FINAL must be defined!" +#error "HASH_FINAL must be defined!" #endif #ifndef HASH_BLOCK_DATA_ORDER -# error "HASH_BLOCK_DATA_ORDER must be defined!" +#error "HASH_BLOCK_DATA_ORDER must be defined!" #endif /* @@ -144,154 +144,175 @@ */ #undef ROTATE #ifndef PEDANTIC -# if defined(_MSC_VER) -# define ROTATE(a,n) _lrotl(a,n) -# elif defined(__ICC) -# define ROTATE(a,n) _rotl(a,n) -# elif defined(__MWERKS__) -# if defined(__POWERPC__) -# define ROTATE(a,n) __rlwinm(a,n,0,31) -# elif defined(__MC68K__) - /* Motorola specific tweak. <appro@fy.chalmers.se> */ -# define ROTATE(a,n) ( n<24 ? __rol(a,n) : __ror(a,32-n) ) -# else -# define ROTATE(a,n) __rol(a,n) -# endif -# elif defined(__GNUC__) && __GNUC__>=2 && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) - /* - * Some GNU C inline assembler templates. Note that these are - * rotates by *constant* number of bits! But that's exactly - * what we need here... - * <appro@fy.chalmers.se> - */ -# if defined(__i386) || defined(__i386__) || defined(__x86_64) || defined(__x86_64__) -# define ROTATE(a,n) ({ register unsigned int ret; \ - asm ( \ - "roll %1,%0" \ - : "=r"(ret) \ - : "I"(n), "0"((unsigned int)(a)) \ - : "cc"); \ - ret; \ - }) -# elif defined(_ARCH_PPC) || defined(_ARCH_PPC64) || \ - defined(__powerpc) || defined(__ppc__) || defined(__powerpc64__) -# define ROTATE(a,n) ({ register unsigned int ret; \ - asm ( \ - "rlwinm %0,%1,%2,0,31" \ - : "=r"(ret) \ - : "r"(a), "I"(n)); \ - ret; \ - }) -# elif defined(__s390x__) -# define ROTATE(a,n) ({ register unsigned int ret; \ - asm ("rll %0,%1,%2" \ - : "=r"(ret) \ - : "r"(a), "I"(n)); \ - ret; \ - }) -# endif -# endif -#endif /* PEDANTIC */ +#if defined(_MSC_VER) +#define ROTATE(a, n) _lrotl(a, n) +#elif defined(__ICC) +#define ROTATE(a, n) _rotl(a, n) +#elif defined(__MWERKS__) +#if defined(__POWERPC__) +#define ROTATE(a, n) __rlwinm(a, n, 0, 31) +#elif defined(__MC68K__) +/* Motorola specific tweak. <appro@fy.chalmers.se> */ +#define ROTATE(a, n) (n < 24 ? __rol(a, n) : __ror(a, 32 - n)) +#else +#define ROTATE(a, n) __rol(a, n) +#endif +#elif defined(__GNUC__) && __GNUC__ >= 2 && !defined(OPENSSL_NO_ASM) && \ + !defined(OPENSSL_NO_INLINE_ASM) +/* + * Some GNU C inline assembler templates. Note that these are + * rotates by *constant* number of bits! But that's exactly + * what we need here... + * <appro@fy.chalmers.se> + */ +#if defined(__i386) || defined(__i386__) || defined(__x86_64) || defined(__x86_64__) +#define ROTATE(a, n) \ + ({ \ + register unsigned int ret; \ + asm("roll %1,%0" : "=r"(ret) : "I"(n), "0"((unsigned int)(a)) : "cc"); \ + ret; \ + }) +#elif defined(_ARCH_PPC) || defined(_ARCH_PPC64) || defined(__powerpc) || \ + defined(__ppc__) || defined(__powerpc64__) +#define ROTATE(a, n) \ + ({ \ + register unsigned int ret; \ + asm("rlwinm %0,%1,%2,0,31" : "=r"(ret) : "r"(a), "I"(n)); \ + ret; \ + }) +#elif defined(__s390x__) +#define ROTATE(a, n) \ + ({ \ + register unsigned int ret; \ + asm("rll %0,%1,%2" : "=r"(ret) : "r"(a), "I"(n)); \ + ret; \ + }) +#endif +#endif +#endif /* PEDANTIC */ #ifndef ROTATE -# define ROTATE(a,n) (((a)<<(n))|(((a)&0xffffffff)>>(32-(n)))) +#define ROTATE(a, n) (((a) << (n)) | (((a)&0xffffffff) >> (32 - (n)))) #endif #if defined(DATA_ORDER_IS_BIG_ENDIAN) -# ifndef PEDANTIC -# if defined(__GNUC__) && __GNUC__>=2 && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) -# if ((defined(__i386) || defined(__i386__)) && !defined(I386_ONLY)) || \ - (defined(__x86_64) || defined(__x86_64__)) -# if !defined(B_ENDIAN) - /* - * This gives ~30-40% performance improvement in SHA-256 compiled - * with gcc [on P4]. Well, first macro to be frank. We can pull - * this trick on x86* platforms only, because these CPUs can fetch - * unaligned data without raising an exception. - */ -# define HOST_c2l(c,l) ({ unsigned int r=*((const unsigned int *)(c)); \ - asm ("bswapl %0":"=r"(r):"0"(r)); \ - (c)+=4; (l)=r; }) -# define HOST_l2c(l,c) ({ unsigned int r=(l); \ - asm ("bswapl %0":"=r"(r):"0"(r)); \ - *((unsigned int *)(c))=r; (c)+=4; r; }) -# endif -# elif defined(__aarch64__) -# if defined(__BYTE_ORDER__) -# if defined(__ORDER_LITTLE_ENDIAN__) && __BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__ -# define HOST_c2l(c,l) ({ unsigned int r; \ - asm ("rev %w0,%w1" \ - :"=r"(r) \ - :"r"(*((const unsigned int *)(c))));\ - (c)+=4; (l)=r; }) -# define HOST_l2c(l,c) ({ unsigned int r; \ - asm ("rev %w0,%w1" \ - :"=r"(r) \ - :"r"((unsigned int)(l)));\ - *((unsigned int *)(c))=r; (c)+=4; r; }) -# elif defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__==__ORDER_BIG_ENDIAN__ -# define HOST_c2l(c,l) ((l)=*((const unsigned int *)(c)), (c)+=4, (l)) -# define HOST_l2c(l,c) (*((unsigned int *)(c))=(l), (c)+=4, (l)) -# endif -# endif -# endif -# endif -# if defined(__s390__) || defined(__s390x__) -# define HOST_c2l(c,l) ((l)=*((const unsigned int *)(c)), (c)+=4, (l)) -# define HOST_l2c(l,c) (*((unsigned int *)(c))=(l), (c)+=4, (l)) -# endif -# endif +#ifndef PEDANTIC +#if defined(__GNUC__) && __GNUC__ >= 2 && !defined(OPENSSL_NO_ASM) && \ + !defined(OPENSSL_NO_INLINE_ASM) +#if ((defined(__i386) || defined(__i386__)) && !defined(I386_ONLY)) || \ + (defined(__x86_64) || defined(__x86_64__)) +#if !defined(B_ENDIAN) +/* + * This gives ~30-40% performance improvement in SHA-256 compiled + * with gcc [on P4]. Well, first macro to be frank. We can pull + * this trick on x86* platforms only, because these CPUs can fetch + * unaligned data without raising an exception. + */ +#define HOST_c2l(c, l) \ + ({ \ + unsigned int r = *((const unsigned int *)(c)); \ + asm("bswapl %0" : "=r"(r) : "0"(r)); \ + (c) += 4; \ + (l) = r; \ + }) +#define HOST_l2c(l, c) \ + ({ \ + unsigned int r = (l); \ + asm("bswapl %0" : "=r"(r) : "0"(r)); \ + *((unsigned int *)(c)) = r; \ + (c) += 4; \ + r; \ + }) +#endif +#elif defined(__aarch64__) +#if defined(__BYTE_ORDER__) +#if defined(__ORDER_LITTLE_ENDIAN__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ +#define HOST_c2l(c, l) \ + ({ \ + unsigned int r; \ + asm("rev %w0,%w1" : "=r"(r) : "r"(*((const unsigned int *)(c)))); \ + (c) += 4; \ + (l) = r; \ + }) +#define HOST_l2c(l, c) \ + ({ \ + unsigned int r; \ + asm("rev %w0,%w1" : "=r"(r) : "r"((unsigned int)(l))); \ + *((unsigned int *)(c)) = r; \ + (c) += 4; \ + r; \ + }) +#elif defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ +#define HOST_c2l(c, l) ((l) = *((const unsigned int *)(c)), (c) += 4, (l)) +#define HOST_l2c(l, c) (*((unsigned int *)(c)) = (l), (c) += 4, (l)) +#endif +#endif +#endif +#endif +#if defined(__s390__) || defined(__s390x__) +#define HOST_c2l(c, l) ((l) = *((const unsigned int *)(c)), (c) += 4, (l)) +#define HOST_l2c(l, c) (*((unsigned int *)(c)) = (l), (c) += 4, (l)) +#endif +#endif -# ifndef HOST_c2l -# define HOST_c2l(c,l) (l =(((unsigned long)(*((c)++)))<<24), \ - l|=(((unsigned long)(*((c)++)))<<16), \ - l|=(((unsigned long)(*((c)++)))<< 8), \ - l|=(((unsigned long)(*((c)++))) ) ) -# endif -# ifndef HOST_l2c -# define HOST_l2c(l,c) (*((c)++)=(unsigned char)(((l)>>24)&0xff), \ - *((c)++)=(unsigned char)(((l)>>16)&0xff), \ - *((c)++)=(unsigned char)(((l)>> 8)&0xff), \ - *((c)++)=(unsigned char)(((l) )&0xff), \ - l) -# endif +#ifndef HOST_c2l +#define HOST_c2l(c, l) \ + (l = (((unsigned long)(*((c)++))) << 24), \ + l |= (((unsigned long)(*((c)++))) << 16), \ + l |= (((unsigned long)(*((c)++))) << 8), \ + l |= (((unsigned long)(*((c)++))))) +#endif +#ifndef HOST_l2c +#define HOST_l2c(l, c) \ + (*((c)++) = (unsigned char)(((l) >> 24) & 0xff), \ + *((c)++) = (unsigned char)(((l) >> 16) & 0xff), \ + *((c)++) = (unsigned char)(((l) >> 8) & 0xff), \ + *((c)++) = (unsigned char)(((l)) & 0xff), l) +#endif #elif defined(DATA_ORDER_IS_LITTLE_ENDIAN) -# ifndef PEDANTIC -# if defined(__GNUC__) && __GNUC__>=2 && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) -# if defined(__s390x__) -# define HOST_c2l(c,l) ({ asm ("lrv %0,%1" \ - :"=d"(l) :"m"(*(const unsigned int *)(c)));\ - (c)+=4; (l); }) -# define HOST_l2c(l,c) ({ asm ("strv %1,%0" \ - :"=m"(*(unsigned int *)(c)) :"d"(l));\ - (c)+=4; (l); }) -# endif -# endif -# if defined(__i386) || defined(__i386__) || defined(__x86_64) || defined(__x86_64__) -# ifndef B_ENDIAN - /* See comment in DATA_ORDER_IS_BIG_ENDIAN section. */ -# define HOST_c2l(c,l) ((l)=*((const unsigned int *)(c)), (c)+=4, l) -# define HOST_l2c(l,c) (*((unsigned int *)(c))=(l), (c)+=4, l) -# endif -# endif -# endif +#ifndef PEDANTIC +#if defined(__GNUC__) && __GNUC__ >= 2 && !defined(OPENSSL_NO_ASM) && \ + !defined(OPENSSL_NO_INLINE_ASM) +#if defined(__s390x__) +#define HOST_c2l(c, l) \ + ({ \ + asm("lrv %0,%1" : "=d"(l) : "m"(*(const unsigned int *)(c))); \ + (c) += 4; \ + (l); \ + }) +#define HOST_l2c(l, c) \ + ({ \ + asm("strv %1,%0" : "=m"(*(unsigned int *)(c)) : "d"(l)); \ + (c) += 4; \ + (l); \ + }) +#endif +#endif +#if defined(__i386) || defined(__i386__) || defined(__x86_64) || defined(__x86_64__) +#ifndef B_ENDIAN +/* See comment in DATA_ORDER_IS_BIG_ENDIAN section. */ +#define HOST_c2l(c, l) ((l) = *((const unsigned int *)(c)), (c) += 4, l) +#define HOST_l2c(l, c) (*((unsigned int *)(c)) = (l), (c) += 4, l) +#endif +#endif +#endif -# ifndef HOST_c2l -# define HOST_c2l(c,l) (l =(((unsigned long)(*((c)++))) ), \ - l|=(((unsigned long)(*((c)++)))<< 8), \ - l|=(((unsigned long)(*((c)++)))<<16), \ - l|=(((unsigned long)(*((c)++)))<<24) ) -# endif -# ifndef HOST_l2c -# define HOST_l2c(l,c) (*((c)++)=(unsigned char)(((l) )&0xff), \ - *((c)++)=(unsigned char)(((l)>> 8)&0xff), \ - *((c)++)=(unsigned char)(((l)>>16)&0xff), \ - *((c)++)=(unsigned char)(((l)>>24)&0xff), \ - l) -# endif +#ifndef HOST_c2l +#define HOST_c2l(c, l) \ + (l = (((unsigned long)(*((c)++)))), l |= (((unsigned long)(*((c)++))) << 8), \ + l |= (((unsigned long)(*((c)++))) << 16), \ + l |= (((unsigned long)(*((c)++))) << 24)) +#endif +#ifndef HOST_l2c +#define HOST_l2c(l, c) \ + (*((c)++) = (unsigned char)(((l)) & 0xff), \ + *((c)++) = (unsigned char)(((l) >> 8) & 0xff), \ + *((c)++) = (unsigned char)(((l) >> 16) & 0xff), \ + *((c)++) = (unsigned char)(((l) >> 24) & 0xff), l) +#endif #endif @@ -301,105 +322,105 @@ int HASH_UPDATE(HASH_CTX *c, const void *data_, size_t len) { - const unsigned char *data = data_; - unsigned char *p; - HASH_LONG l; - size_t n; + const unsigned char *data = data_; + unsigned char *p; + HASH_LONG l; + size_t n; - if (len == 0) - return 1; + if (len == 0) + return 1; - l = (c->Nl + (((HASH_LONG) len) << 3)) & 0xffffffffUL; - /* - * 95-05-24 eay Fixed a bug with the overflow handling, thanks to Wei Dai - * <weidai@eskimo.com> for pointing it out. - */ - if (l < c->Nl) /* overflow */ - c->Nh++; - c->Nh += (HASH_LONG) (len >> 29); /* might cause compiler warning on - * 16-bit */ - c->Nl = l; + l = (c->Nl + (((HASH_LONG)len) << 3)) & 0xffffffffUL; + /* + * 95-05-24 eay Fixed a bug with the overflow handling, thanks to Wei Dai + * <weidai@eskimo.com> for pointing it out. + */ + if (l < c->Nl) /* overflow */ + c->Nh++; + c->Nh += (HASH_LONG)(len >> 29); /* might cause compiler warning on + * 16-bit */ + c->Nl = l; - n = c->num; - if (n != 0) { - p = (unsigned char *)c->data; + n = c->num; + if (n != 0) { + p = (unsigned char *)c->data; - if (len >= HASH_CBLOCK || len + n >= HASH_CBLOCK) { - memcpy(p + n, data, HASH_CBLOCK - n); - HASH_BLOCK_DATA_ORDER(c, p, 1); - n = HASH_CBLOCK - n; - data += n; - len -= n; - c->num = 0; - memset(p, 0, HASH_CBLOCK); /* keep it zeroed */ - } else { - memcpy(p + n, data, len); - c->num += (unsigned int)len; - return 1; - } - } + if (len >= HASH_CBLOCK || len + n >= HASH_CBLOCK) { + memcpy(p + n, data, HASH_CBLOCK - n); + HASH_BLOCK_DATA_ORDER(c, p, 1); + n = HASH_CBLOCK - n; + data += n; + len -= n; + c->num = 0; + memset(p, 0, HASH_CBLOCK); /* keep it zeroed */ + } else { + memcpy(p + n, data, len); + c->num += (unsigned int)len; + return 1; + } + } - n = len / HASH_CBLOCK; - if (n > 0) { - HASH_BLOCK_DATA_ORDER(c, data, n); - n *= HASH_CBLOCK; - data += n; - len -= n; - } + n = len / HASH_CBLOCK; + if (n > 0) { + HASH_BLOCK_DATA_ORDER(c, data, n); + n *= HASH_CBLOCK; + data += n; + len -= n; + } - if (len != 0) { - p = (unsigned char *)c->data; - c->num = (unsigned int)len; - memcpy(p, data, len); - } - return 1; + if (len != 0) { + p = (unsigned char *)c->data; + c->num = (unsigned int)len; + memcpy(p, data, len); + } + return 1; } void HASH_TRANSFORM(HASH_CTX *c, const unsigned char *data) { - HASH_BLOCK_DATA_ORDER(c, data, 1); + HASH_BLOCK_DATA_ORDER(c, data, 1); } int HASH_FINAL(unsigned char *md, HASH_CTX *c) { - unsigned char *p = (unsigned char *)c->data; - size_t n = c->num; + unsigned char *p = (unsigned char *)c->data; + size_t n = c->num; - p[n] = 0x80; /* there is always room for one */ - n++; + p[n] = 0x80; /* there is always room for one */ + n++; - if (n > (HASH_CBLOCK - 8)) { - memset(p + n, 0, HASH_CBLOCK - n); - n = 0; - HASH_BLOCK_DATA_ORDER(c, p, 1); - } - memset(p + n, 0, HASH_CBLOCK - 8 - n); + if (n > (HASH_CBLOCK - 8)) { + memset(p + n, 0, HASH_CBLOCK - n); + n = 0; + HASH_BLOCK_DATA_ORDER(c, p, 1); + } + memset(p + n, 0, HASH_CBLOCK - 8 - n); - p += HASH_CBLOCK - 8; -#if defined(DATA_ORDER_IS_BIG_ENDIAN) - (void)HOST_l2c(c->Nh, p); - (void)HOST_l2c(c->Nl, p); + p += HASH_CBLOCK - 8; +#if defined(DATA_ORDER_IS_BIG_ENDIAN) + (void)HOST_l2c(c->Nh, p); + (void)HOST_l2c(c->Nl, p); #elif defined(DATA_ORDER_IS_LITTLE_ENDIAN) - (void)HOST_l2c(c->Nl, p); - (void)HOST_l2c(c->Nh, p); + (void)HOST_l2c(c->Nl, p); + (void)HOST_l2c(c->Nh, p); #endif - p -= HASH_CBLOCK; - HASH_BLOCK_DATA_ORDER(c, p, 1); - c->num = 0; - memset(p, 0, HASH_CBLOCK); + p -= HASH_CBLOCK; + HASH_BLOCK_DATA_ORDER(c, p, 1); + c->num = 0; + memset(p, 0, HASH_CBLOCK); #ifndef HASH_MAKE_STRING -# error "HASH_MAKE_STRING must be defined!" +#error "HASH_MAKE_STRING must be defined!" #else - HASH_MAKE_STRING(c, md); + HASH_MAKE_STRING(c, md); #endif - return 1; + return 1; } #ifndef MD32_REG_T -# if defined(__alpha) || defined(__sparcv9) || defined(__mips) -# define MD32_REG_T long +#if defined(__alpha) || defined(__sparcv9) || defined(__mips) +#define MD32_REG_T long /* * This comment was originaly written for MD5, which is why it * discusses A-D. But it basically applies to all 32-bit digests, @@ -417,7 +438,7 @@ int HASH_FINAL(unsigned char *md, HASH_CTX *c) * performance degradation. * <appro@fy.chalmers.se> */ -# else +#else /* * Above is not absolute and there are LP64 compilers that * generate better code if MD32_REG_T is defined int. The above @@ -425,6 +446,6 @@ int HASH_FINAL(unsigned char *md, HASH_CTX *c) * the conclusion was made and is subject to further extension. * <appro@fy.chalmers.se> */ -# define MD32_REG_T int -# endif +#define MD32_REG_T int +#endif #endif diff --git a/src/util/numeric.cpp b/src/util/numeric.cpp index 1af3f66be..d464c5836 100644 --- a/src/util/numeric.cpp +++ b/src/util/numeric.cpp @@ -21,12 +21,11 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "log.h" #include "constants.h" // BS, MAP_BLOCKSIZE -#include "noise.h" // PseudoRandom, PcgRandom +#include "noise.h" // PseudoRandom, PcgRandom #include "threading/mutex_auto_lock.h" #include <cstring> #include <cmath> - // myrand PcgRandom g_pcgrand; @@ -51,7 +50,6 @@ int myrand_range(int min, int max) return g_pcgrand.range(min, max); } - /* 64-bit unaligned version of MurmurHash */ @@ -79,14 +77,21 @@ u64 murmur_hash_64_ua(const void *key, int len, unsigned int seed) const unsigned char *data2 = (const unsigned char *)data; switch (len & 7) { - case 7: h ^= (u64)data2[6] << 48; - case 6: h ^= (u64)data2[5] << 40; - case 5: h ^= (u64)data2[4] << 32; - case 4: h ^= (u64)data2[3] << 24; - case 3: h ^= (u64)data2[2] << 16; - case 2: h ^= (u64)data2[1] << 8; - case 1: h ^= (u64)data2[0]; - h *= m; + case 7: + h ^= (u64)data2[6] << 48; + case 6: + h ^= (u64)data2[5] << 40; + case 5: + h ^= (u64)data2[4] << 32; + case 4: + h ^= (u64)data2[3] << 24; + case 3: + h ^= (u64)data2[2] << 16; + case 2: + h ^= (u64)data2[1] << 8; + case 1: + h ^= (u64)data2[0]; + h *= m; } h ^= h >> r; @@ -103,21 +108,20 @@ u64 murmur_hash_64_ua(const void *key, int len, unsigned int seed) range: viewing range distance_ptr: return location for distance from the camera */ -bool isBlockInSight(v3s16 blockpos_b, v3f camera_pos, v3f camera_dir, - f32 camera_fov, f32 range, f32 *distance_ptr) +bool isBlockInSight(v3s16 blockpos_b, v3f camera_pos, v3f camera_dir, f32 camera_fov, + f32 range, f32 *distance_ptr) { // Maximum radius of a block. The magic number is // sqrt(3.0) / 2.0 in literal form. - static constexpr const f32 block_max_radius = 0.866025403784f * MAP_BLOCKSIZE * BS; + static constexpr const f32 block_max_radius = + 0.866025403784f * MAP_BLOCKSIZE * BS; v3s16 blockpos_nodes = blockpos_b * MAP_BLOCKSIZE; // Block center position - v3f blockpos( - ((float)blockpos_nodes.X + MAP_BLOCKSIZE/2) * BS, - ((float)blockpos_nodes.Y + MAP_BLOCKSIZE/2) * BS, - ((float)blockpos_nodes.Z + MAP_BLOCKSIZE/2) * BS - ); + v3f blockpos(((float)blockpos_nodes.X + MAP_BLOCKSIZE / 2) * BS, + ((float)blockpos_nodes.Y + MAP_BLOCKSIZE / 2) * BS, + ((float)blockpos_nodes.Z + MAP_BLOCKSIZE / 2) * BS); // Block position relative to camera v3f blockpos_relative = blockpos - camera_pos; @@ -172,7 +176,7 @@ s16 adjustDist(s16 dist, float zoom_fov) return dist; return std::round(dist * std::cbrt((1.0f - std::cos(threshold_fov)) / - (1.0f - std::cos(zoom_fov / 2.0f)))); + (1.0f - std::cos(zoom_fov / 2.0f)))); } void setPitchYawRollRad(core::matrix4 &m, const v3f &rot) @@ -201,11 +205,11 @@ v3f getPitchYawRollRad(const core::matrix4 &m) const f32 *M = m.pointer(); f64 a1 = atan2(M[1], M[5]); - f32 c2 = std::sqrt((f64)M[10]*M[10] + (f64)M[8]*M[8]); + f32 c2 = std::sqrt((f64)M[10] * M[10] + (f64)M[8] * M[8]); f32 a2 = atan2f(-M[9], c2); f64 c1 = cos(a1); f64 s1 = sin(a1); - f32 a3 = atan2f(s1*M[6] - c1*M[2], c1*M[0] - s1*M[4]); + f32 a3 = atan2f(s1 * M[6] - c1 * M[2], c1 * M[0] - s1 * M[4]); return v3f(a2, a3, a1); } diff --git a/src/util/numeric.h b/src/util/numeric.h index 864ab7543..385179b40 100644 --- a/src/util/numeric.h +++ b/src/util/numeric.h @@ -28,14 +28,14 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <matrix4.h> #define rangelim(d, min, max) ((d) < (min) ? (min) : ((d) > (max) ? (max) : (d))) -#define myfloor(x) ((x) < 0.0 ? (int)(x) - 1 : (int)(x)) +#define myfloor(x) ((x) < 0.0 ? (int)(x)-1 : (int)(x)) // The naive swap performs better than the xor version -#define SWAP(t, x, y) do { \ - t temp = x; \ - x = y; \ - y = temp; \ -} while (0) - +#define SWAP(t, x, y) \ + do { \ + t temp = x; \ + x = y; \ + y = temp; \ + } while (0) inline s16 getContainerPos(s16 p, s16 d) { @@ -44,36 +44,24 @@ inline s16 getContainerPos(s16 p, s16 d) inline v2s16 getContainerPos(v2s16 p, s16 d) { - return v2s16( - getContainerPos(p.X, d), - getContainerPos(p.Y, d) - ); + return v2s16(getContainerPos(p.X, d), getContainerPos(p.Y, d)); } inline v3s16 getContainerPos(v3s16 p, s16 d) { - return v3s16( - getContainerPos(p.X, d), - getContainerPos(p.Y, d), - getContainerPos(p.Z, d) - ); + return v3s16(getContainerPos(p.X, d), getContainerPos(p.Y, d), + getContainerPos(p.Z, d)); } inline v2s16 getContainerPos(v2s16 p, v2s16 d) { - return v2s16( - getContainerPos(p.X, d.X), - getContainerPos(p.Y, d.Y) - ); + return v2s16(getContainerPos(p.X, d.X), getContainerPos(p.Y, d.Y)); } inline v3s16 getContainerPos(v3s16 p, v3s16 d) { - return v3s16( - getContainerPos(p.X, d.X), - getContainerPos(p.Y, d.Y), - getContainerPos(p.Z, d.Z) - ); + return v3s16(getContainerPos(p.X, d.X), getContainerPos(p.Y, d.Y), + getContainerPos(p.Z, d.Z)); } inline void getContainerPosWithOffset(s16 p, s16 d, s16 &container, s16 &offset) @@ -82,47 +70,38 @@ inline void getContainerPosWithOffset(s16 p, s16 d, s16 &container, s16 &offset) offset = p & (d - 1); } -inline void getContainerPosWithOffset(const v2s16 &p, s16 d, v2s16 &container, v2s16 &offset) +inline void getContainerPosWithOffset( + const v2s16 &p, s16 d, v2s16 &container, v2s16 &offset) { getContainerPosWithOffset(p.X, d, container.X, offset.X); getContainerPosWithOffset(p.Y, d, container.Y, offset.Y); } -inline void getContainerPosWithOffset(const v3s16 &p, s16 d, v3s16 &container, v3s16 &offset) +inline void getContainerPosWithOffset( + const v3s16 &p, s16 d, v3s16 &container, v3s16 &offset) { getContainerPosWithOffset(p.X, d, container.X, offset.X); getContainerPosWithOffset(p.Y, d, container.Y, offset.Y); getContainerPosWithOffset(p.Z, d, container.Z, offset.Z); } - inline bool isInArea(v3s16 p, s16 d) { - return ( - p.X >= 0 && p.X < d && - p.Y >= 0 && p.Y < d && - p.Z >= 0 && p.Z < d - ); + return (p.X >= 0 && p.X < d && p.Y >= 0 && p.Y < d && p.Z >= 0 && p.Z < d); } inline bool isInArea(v2s16 p, s16 d) { - return ( - p.X >= 0 && p.X < d && - p.Y >= 0 && p.Y < d - ); + return (p.X >= 0 && p.X < d && p.Y >= 0 && p.Y < d); } inline bool isInArea(v3s16 p, v3s16 d) { - return ( - p.X >= 0 && p.X < d.X && - p.Y >= 0 && p.Y < d.Y && - p.Z >= 0 && p.Z < d.Z - ); + return (p.X >= 0 && p.X < d.X && p.Y >= 0 && p.Y < d.Y && p.Z >= 0 && p.Z < d.Z); } -inline void sortBoxVerticies(v3s16 &p1, v3s16 &p2) { +inline void sortBoxVerticies(v3s16 &p1, v3s16 &p2) +{ if (p1.X > p2.X) SWAP(s16, p1.X, p2.X); if (p1.Y > p2.Y) @@ -141,7 +120,6 @@ inline v3s16 componentwise_max(const v3s16 &a, const v3s16 &b) return v3s16(MYMAX(a.X, b.X), MYMAX(a.Y, b.Y), MYMAX(a.Z, b.Z)); } - /** Returns \p f wrapped to the range [-360, 360] * * See test.cpp for example cases. @@ -174,18 +152,16 @@ inline float modulo360f(float f) return sign * (whole + fraction); } - /** Returns \p f wrapped to the range [0, 360] - */ + */ inline float wrapDegrees_0_360(float f) { float value = modulo360f(f); return value < 0 ? value + 360 : value; } - /** Returns \p v3f wrapped to the range [0, 360] - */ + */ inline v3f wrapDegrees_0_360_v3f(v3f v) { v3f value_v3f; @@ -200,9 +176,8 @@ inline v3f wrapDegrees_0_360_v3f(v3f v) return value_v3f; } - /** Returns \p f wrapped to the range [-180, 180] - */ + */ inline float wrapDegrees_180(float f) { float value = modulo360f(f + 180); @@ -248,8 +223,8 @@ inline u32 calc_parity(u32 v) u64 murmur_hash_64_ua(const void *key, int len, unsigned int seed); -bool isBlockInSight(v3s16 blockpos_b, v3f camera_pos, v3f camera_dir, - f32 camera_fov, f32 range, f32 *distance_ptr=NULL); +bool isBlockInSight(v3s16 blockpos_b, v3f camera_pos, v3f camera_dir, f32 camera_fov, + f32 range, f32 *distance_ptr = NULL); s16 adjustDist(s16 dist, float zoom_fov); @@ -272,10 +247,9 @@ inline constexpr f32 sqr(f32 f) */ inline v3s16 floatToInt(v3f p, f32 d) { - return v3s16( - (p.X + (p.X > 0 ? d / 2 : -d / 2)) / d, - (p.Y + (p.Y > 0 ? d / 2 : -d / 2)) / d, - (p.Z + (p.Z > 0 ? d / 2 : -d / 2)) / d); + return v3s16((p.X + (p.X > 0 ? d / 2 : -d / 2)) / d, + (p.Y + (p.Y > 0 ? d / 2 : -d / 2)) / d, + (p.Z + (p.Z > 0 ? d / 2 : -d / 2)) / d); } /* @@ -283,10 +257,9 @@ inline v3s16 floatToInt(v3f p, f32 d) */ inline v3s16 doubleToInt(v3d p, double d) { - return v3s16( - (p.X + (p.X > 0 ? d / 2 : -d / 2)) / d, - (p.Y + (p.Y > 0 ? d / 2 : -d / 2)) / d, - (p.Z + (p.Z > 0 ? d / 2 : -d / 2)) / d); + return v3s16((p.X + (p.X > 0 ? d / 2 : -d / 2)) / d, + (p.Y + (p.Y > 0 ? d / 2 : -d / 2)) / d, + (p.Z + (p.Z > 0 ? d / 2 : -d / 2)) / d); } /* @@ -294,27 +267,17 @@ inline v3s16 doubleToInt(v3d p, double d) */ inline v3f intToFloat(v3s16 p, f32 d) { - return v3f( - (f32)p.X * d, - (f32)p.Y * d, - (f32)p.Z * d - ); + return v3f((f32)p.X * d, (f32)p.Y * d, (f32)p.Z * d); } // Random helper. Usually d=BS inline aabb3f getNodeBox(v3s16 p, float d) { - return aabb3f( - (float)p.X * d - 0.5f * d, - (float)p.Y * d - 0.5f * d, - (float)p.Z * d - 0.5f * d, - (float)p.X * d + 0.5f * d, - (float)p.Y * d + 0.5f * d, - (float)p.Z * d + 0.5f * d - ); + return aabb3f((float)p.X * d - 0.5f * d, (float)p.Y * d - 0.5f * d, + (float)p.Z * d - 0.5f * d, (float)p.X * d + 0.5f * d, + (float)p.Y * d + 0.5f * d, (float)p.Z * d + 0.5f * d); } - class IntervalLimiter { public: @@ -340,7 +303,6 @@ private: float m_accumulator = 0.0f; }; - /* Splits a list into "pages". For example, the list [1,2,3,4,5] split into two pages would be [1,2,3],[4,5]. This function computes the @@ -359,16 +321,16 @@ inline void paging(u32 length, u32 page, u32 pagecount, u32 &minindex, u32 &maxi if (length < 1 || pagecount < 1 || page < 1 || page > pagecount) { // Special cases or invalid parameters minindex = maxindex = 0; - } else if(pagecount <= length) { + } else if (pagecount <= length) { // Less pages than entries in the list: // Each page contains at least one entry - minindex = (length * (page-1) + (pagecount-1)) / pagecount; - maxindex = (length * page + (pagecount-1)) / pagecount; + minindex = (length * (page - 1) + (pagecount - 1)) / pagecount; + maxindex = (length * page + (pagecount - 1)) / pagecount; } else { // More pages than entries in the list: // Make sure the empty pages are at the end if (page < length) { - minindex = page-1; + minindex = page - 1; maxindex = page; } else { minindex = 0; @@ -379,9 +341,11 @@ inline void paging(u32 length, u32 page, u32 pagecount, u32 &minindex, u32 &maxi inline float cycle_shift(float value, float by = 0, float max = 1) { - if (value + by < 0) return value + by + max; - if (value + by > max) return value + by - max; - return value + by; + if (value + by < 0) + return value + by + max; + if (value + by > max) + return value + by - max; + return value + by; } inline bool is_power_of_two(u32 n) @@ -391,7 +355,8 @@ inline bool is_power_of_two(u32 n) // Compute next-higher power of 2 efficiently, e.g. for power-of-2 texture sizes. // Public Domain: https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 -inline u32 npot2(u32 orig) { +inline u32 npot2(u32 orig) +{ orig--; orig |= orig >> 1; orig |= orig >> 2; @@ -403,9 +368,9 @@ inline u32 npot2(u32 orig) { // Gradual steps towards the target value in a wrapped (circular) system // using the shorter of both ways -template<typename T> -inline void wrappedApproachShortest(T ¤t, const T target, const T stepsize, - const T maximum) +template <typename T> +inline void wrappedApproachShortest( + T ¤t, const T target, const T stepsize, const T maximum) { T delta = target - current; if (delta < 0) diff --git a/src/util/pointedthing.cpp b/src/util/pointedthing.cpp index b906264d0..89cf91f22 100644 --- a/src/util/pointedthing.cpp +++ b/src/util/pointedthing.cpp @@ -24,26 +24,20 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <sstream> PointedThing::PointedThing(const v3s16 &under, const v3s16 &above, - const v3s16 &real_under, const v3f &point, const v3s16 &normal, - u16 box_id, f32 distSq): - type(POINTEDTHING_NODE), - node_undersurface(under), - node_abovesurface(above), - node_real_undersurface(real_under), - intersection_point(point), - intersection_normal(normal), - box_id(box_id), - distanceSq(distSq) -{} + const v3s16 &real_under, const v3f &point, const v3s16 &normal, + u16 box_id, f32 distSq) : + type(POINTEDTHING_NODE), + node_undersurface(under), node_abovesurface(above), + node_real_undersurface(real_under), intersection_point(point), + intersection_normal(normal), box_id(box_id), distanceSq(distSq) +{ +} -PointedThing::PointedThing(s16 id, const v3f &point, const v3s16 &normal, - f32 distSq) : - type(POINTEDTHING_OBJECT), - object_id(id), - intersection_point(point), - intersection_normal(normal), - distanceSq(distSq) -{} +PointedThing::PointedThing(s16 id, const v3f &point, const v3s16 &normal, f32 distSq) : + type(POINTEDTHING_OBJECT), object_id(id), intersection_point(point), + intersection_normal(normal), distanceSq(distSq) +{ +} std::string PointedThing::dump() const { @@ -52,14 +46,12 @@ std::string PointedThing::dump() const case POINTEDTHING_NOTHING: os << "[nothing]"; break; - case POINTEDTHING_NODE: - { + case POINTEDTHING_NODE: { const v3s16 &u = node_undersurface; const v3s16 &a = node_abovesurface; - os << "[node under=" << u.X << "," << u.Y << "," << u.Z << " above=" - << a.X << "," << a.Y << "," << a.Z << "]"; - } - break; + os << "[node under=" << u.X << "," << u.Y << "," << u.Z + << " above=" << a.X << "," << a.Y << "," << a.Z << "]"; + } break; case POINTEDTHING_OBJECT: os << "[object " << object_id << "]"; break; @@ -89,9 +81,9 @@ void PointedThing::serialize(std::ostream &os) const void PointedThing::deSerialize(std::istream &is) { int version = readU8(is); - if (version != 0) throw SerializationError( - "unsupported PointedThing version"); - type = (PointedThingType) readU8(is); + if (version != 0) + throw SerializationError("unsupported PointedThing version"); + type = (PointedThingType)readU8(is); switch (type) { case POINTEDTHING_NOTHING: break; @@ -109,19 +101,15 @@ void PointedThing::deSerialize(std::istream &is) bool PointedThing::operator==(const PointedThing &pt2) const { - if (type != pt2.type) - { + if (type != pt2.type) { return false; } - if (type == POINTEDTHING_NODE) - { - if ((node_undersurface != pt2.node_undersurface) - || (node_abovesurface != pt2.node_abovesurface) - || (node_real_undersurface != pt2.node_real_undersurface)) + if (type == POINTEDTHING_NODE) { + if ((node_undersurface != pt2.node_undersurface) || + (node_abovesurface != pt2.node_abovesurface) || + (node_real_undersurface != pt2.node_real_undersurface)) return false; - } - else if (type == POINTEDTHING_OBJECT) - { + } else if (type == POINTEDTHING_OBJECT) { if (object_id != pt2.object_id) return false; } diff --git a/src/util/pointedthing.h b/src/util/pointedthing.h index 5b30ed031..0d3044880 100644 --- a/src/util/pointedthing.h +++ b/src/util/pointedthing.h @@ -89,9 +89,8 @@ struct PointedThing //! Constructor for POINTEDTHING_NOTHING PointedThing() = default; //! Constructor for POINTEDTHING_NODE - PointedThing(const v3s16 &under, const v3s16 &above, - const v3s16 &real_under, const v3f &point, const v3s16 &normal, - u16 box_id, f32 distSq); + PointedThing(const v3s16 &under, const v3s16 &above, const v3s16 &real_under, + const v3f &point, const v3s16 &normal, u16 box_id, f32 distSq); //! Constructor for POINTEDTHING_OBJECT PointedThing(s16 id, const v3f &point, const v3s16 &normal, f32 distSq); std::string dump() const; diff --git a/src/util/pointer.h b/src/util/pointer.h index d29ec8739..ea868b3f0 100644 --- a/src/util/pointer.h +++ b/src/util/pointer.h @@ -23,8 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "debug.h" // For assert() #include <cstring> -template <typename T> -class Buffer +template <typename T> class Buffer { public: Buffer() @@ -35,7 +34,7 @@ public: Buffer(unsigned int size) { m_size = size; - if(size != 0) + if (size != 0) data = new T[size]; else data = NULL; @@ -43,61 +42,41 @@ public: Buffer(const Buffer &buffer) { m_size = buffer.m_size; - if(m_size != 0) - { + if (m_size != 0) { data = new T[buffer.m_size]; memcpy(data, buffer.data, buffer.m_size); - } - else + } else data = NULL; } Buffer(const T *t, unsigned int size) { m_size = size; - if(size != 0) - { + if (size != 0) { data = new T[size]; memcpy(data, t, size); - } - else + } else data = NULL; } - ~Buffer() + ~Buffer() { drop(); } + Buffer &operator=(const Buffer &buffer) { - drop(); - } - Buffer& operator=(const Buffer &buffer) - { - if(this == &buffer) + if (this == &buffer) return *this; drop(); m_size = buffer.m_size; - if(m_size != 0) - { + if (m_size != 0) { data = new T[buffer.m_size]; memcpy(data, buffer.data, buffer.m_size); - } - else + } else data = NULL; return *this; } - T & operator[](unsigned int i) const - { - return data[i]; - } - T * operator*() const - { - return data; - } - unsigned int getSize() const - { - return m_size; - } + T &operator[](unsigned int i) const { return data[i]; } + T *operator*() const { return data; } + unsigned int getSize() const { return m_size; } + private: - void drop() - { - delete[] data; - } + void drop() { delete[] data; } T *data; unsigned int m_size; }; @@ -109,8 +88,7 @@ private: * ONLY use in a single-threaded context! * * * ************************************************/ -template <typename T> -class SharedBuffer +template <typename T> class SharedBuffer { public: SharedBuffer() @@ -123,12 +101,12 @@ public: SharedBuffer(unsigned int size) { m_size = size; - if(m_size != 0) + if (m_size != 0) data = new T[m_size]; else data = NULL; refcount = new unsigned int; - memset(data,0,sizeof(T)*m_size); + memset(data, 0, sizeof(T) * m_size); (*refcount) = 1; } SharedBuffer(const SharedBuffer &buffer) @@ -138,9 +116,9 @@ public: refcount = buffer.refcount; (*refcount)++; } - SharedBuffer & operator=(const SharedBuffer & buffer) + SharedBuffer &operator=(const SharedBuffer &buffer) { - if(this == &buffer) + if (this == &buffer) return *this; drop(); m_size = buffer.m_size; @@ -155,12 +133,10 @@ public: SharedBuffer(const T *t, unsigned int size) { m_size = size; - if(m_size != 0) - { + if (m_size != 0) { data = new T[m_size]; memcpy(data, t, m_size); - } - else + } else data = NULL; refcount = new unsigned int; (*refcount) = 1; @@ -172,42 +148,29 @@ public: { m_size = buffer.getSize(); if (m_size != 0) { - data = new T[m_size]; - memcpy(data, *buffer, buffer.getSize()); - } - else + data = new T[m_size]; + memcpy(data, *buffer, buffer.getSize()); + } else data = NULL; refcount = new unsigned int; (*refcount) = 1; } - ~SharedBuffer() - { - drop(); - } - T & operator[](unsigned int i) const + ~SharedBuffer() { drop(); } + T &operator[](unsigned int i) const { assert(i < m_size); return data[i]; } - T * operator*() const - { - return data; - } - unsigned int getSize() const - { - return m_size; - } - operator Buffer<T>() const - { - return Buffer<T>(data, m_size); - } + T *operator*() const { return data; } + unsigned int getSize() const { return m_size; } + operator Buffer<T>() const { return Buffer<T>(data, m_size); } + private: void drop() { assert((*refcount) > 0); (*refcount)--; - if(*refcount == 0) - { + if (*refcount == 0) { delete[] data; delete refcount; } diff --git a/src/util/quicktune.cpp b/src/util/quicktune.cpp index 37d4933de..e7409c894 100644 --- a/src/util/quicktune.cpp +++ b/src/util/quicktune.cpp @@ -23,7 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., std::string QuicktuneValue::getString() { - switch(type){ + switch (type) { case QVT_NONE: return "(none)"; case QVT_FLOAT: @@ -33,14 +33,15 @@ std::string QuicktuneValue::getString() } void QuicktuneValue::relativeAdd(float amount) { - switch(type){ + switch (type) { case QVT_NONE: break; case QVT_FLOAT: - value_QVT_FLOAT.current += amount * (value_QVT_FLOAT.max - value_QVT_FLOAT.min); - if(value_QVT_FLOAT.current > value_QVT_FLOAT.max) + value_QVT_FLOAT.current += + amount * (value_QVT_FLOAT.max - value_QVT_FLOAT.min); + if (value_QVT_FLOAT.current > value_QVT_FLOAT.max) value_QVT_FLOAT.current = value_QVT_FLOAT.max; - if(value_QVT_FLOAT.current < value_QVT_FLOAT.min) + if (value_QVT_FLOAT.current < value_QVT_FLOAT.min) value_QVT_FLOAT.current = value_QVT_FLOAT.min; break; } @@ -52,7 +53,7 @@ std::mutex *g_mutex = NULL; static void makeMutex() { - if(!g_mutex){ + if (!g_mutex) { g_mutex = new std::mutex(); } } @@ -67,7 +68,7 @@ QuicktuneValue getQuicktuneValue(const std::string &name) makeMutex(); MutexAutoLock lock(*g_mutex); std::map<std::string, QuicktuneValue>::iterator i = g_values.find(name); - if(i == g_values.end()){ + if (i == g_values.end()) { QuicktuneValue val; val.type = QVT_NONE; return val; @@ -88,17 +89,16 @@ void updateQuicktuneValue(const std::string &name, QuicktuneValue &val) makeMutex(); MutexAutoLock lock(*g_mutex); std::map<std::string, QuicktuneValue>::iterator i = g_values.find(name); - if(i == g_values.end()){ + if (i == g_values.end()) { g_values[name] = val; g_names.push_back(name); return; } QuicktuneValue &ref = i->second; - if(ref.modified) + if (ref.modified) val = ref; - else{ + else { ref = val; ref.modified = false; } } - diff --git a/src/util/quicktune.h b/src/util/quicktune.h index 1943d19c2..6d47f56df 100644 --- a/src/util/quicktune.h +++ b/src/util/quicktune.h @@ -52,15 +52,18 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <map> #include <vector> -enum QuicktuneValueType{ +enum QuicktuneValueType +{ QVT_NONE, QVT_FLOAT }; struct QuicktuneValue { QuicktuneValueType type = QVT_NONE; - union{ - struct{ + union + { + struct + { float current; float min; float max; @@ -81,18 +84,20 @@ void setQuicktuneValue(const std::string &name, const QuicktuneValue &val); void updateQuicktuneValue(const std::string &name, QuicktuneValue &val); #ifndef NDEBUG - #define QUICKTUNE(type_, var, min_, max_, name){\ - QuicktuneValue qv;\ - qv.type = type_;\ - qv.value_##type_.current = var;\ - qv.value_##type_.min = min_;\ - qv.value_##type_.max = max_;\ - updateQuicktuneValue(name, qv);\ - var = qv.value_##type_.current;\ +#define QUICKTUNE(type_, var, min_, max_, name) \ + { \ + QuicktuneValue qv; \ + qv.type = type_; \ + qv.value_##type_.current = var; \ + qv.value_##type_.min = min_; \ + qv.value_##type_.max = max_; \ + updateQuicktuneValue(name, qv); \ + var = qv.value_##type_.current; \ } #else // NDEBUG - #define QUICKTUNE(type, var, min_, max_, name){} +#define QUICKTUNE(type, var, min_, max_, name) \ + { \ + } #endif -#define QUICKTUNE_AUTONAME(type_, var, min_, max_)\ - QUICKTUNE(type_, var, min_, max_, #var) +#define QUICKTUNE_AUTONAME(type_, var, min_, max_) QUICKTUNE(type_, var, min_, max_, #var) diff --git a/src/util/quicktune_shortcutter.h b/src/util/quicktune_shortcutter.h index 70a7b70b3..15a9a07ef 100644 --- a/src/util/quicktune_shortcutter.h +++ b/src/util/quicktune_shortcutter.h @@ -27,11 +27,9 @@ private: std::vector<std::string> m_names; u32 m_selected_i; std::string m_message; + public: - bool hasMessage() const - { - return !m_message.empty(); - } + bool hasMessage() const { return !m_message.empty(); } std::string getMessage() { @@ -43,42 +41,42 @@ public: } std::string getSelectedName() { - if(m_selected_i < m_names.size()) + if (m_selected_i < m_names.size()) return m_names[m_selected_i]; return "(nothing)"; } void next() { m_names = getQuicktuneNames(); - if(m_selected_i < m_names.size()-1) + if (m_selected_i < m_names.size() - 1) m_selected_i++; else m_selected_i = 0; - m_message = std::string("Selected \"")+getSelectedName()+"\""; + m_message = std::string("Selected \"") + getSelectedName() + "\""; } void prev() { m_names = getQuicktuneNames(); - if(m_selected_i > 0) + if (m_selected_i > 0) m_selected_i--; else - m_selected_i = m_names.size()-1; - m_message = std::string("Selected \"")+getSelectedName()+"\""; + m_selected_i = m_names.size() - 1; + m_message = std::string("Selected \"") + getSelectedName() + "\""; } void inc() { QuicktuneValue val = getQuicktuneValue(getSelectedName()); val.relativeAdd(0.05); - m_message = std::string("\"")+getSelectedName() - +"\" = "+val.getString(); + m_message = std::string("\"") + getSelectedName() + + "\" = " + val.getString(); setQuicktuneValue(getSelectedName(), val); } void dec() { QuicktuneValue val = getQuicktuneValue(getSelectedName()); val.relativeAdd(-0.05); - m_message = std::string("\"")+getSelectedName() - +"\" = "+val.getString(); + m_message = std::string("\"") + getSelectedName() + + "\" = " + val.getString(); setQuicktuneValue(getSelectedName(), val); } }; diff --git a/src/util/serialize.cpp b/src/util/serialize.cpp index 5b276668d..367c8b0ef 100644 --- a/src/util/serialize.cpp +++ b/src/util/serialize.cpp @@ -98,7 +98,6 @@ bool BufReader::getRawDataNoEx(void *val, size_t len) return true; } - //// //// String //// @@ -181,7 +180,7 @@ std::wstring deSerializeWideString(std::istream &is) is.read(&buf[0], 2); if (is.gcount() != 2) { throw SerializationError( - "deSerializeWideString: couldn't read all chars"); + "deSerializeWideString: couldn't read all chars"); } wchar_t c16 = readU16((u8 *)buf); @@ -203,7 +202,7 @@ std::string serializeLongString(const std::string &plain) throw SerializationError("String too long for serializeLongString"); s.reserve(4 + plain.size()); - writeU32((u8*)&buf[0], plain.size()); + writeU32((u8 *)&buf[0], plain.size()); s.append(buf, 4); s.append(plain); return s; @@ -225,13 +224,15 @@ std::string deSerializeLongString(std::istream &is) // We don't really want a remote attacker to force us to allocate 4GB... if (s_size > LONG_STRING_MAX_LEN) { throw SerializationError("deSerializeLongString: " - "string too long: " + itos(s_size) + " bytes"); + "string too long: " + + itos(s_size) + " bytes"); } s.resize(s_size); is.read(&s[0], s_size); if ((u32)is.gcount() != s_size) - throw SerializationError("deSerializeLongString: couldn't read all chars"); + throw SerializationError( + "deSerializeLongString: couldn't read all chars"); return s; } @@ -247,40 +248,40 @@ std::string serializeJsonString(const std::string &plain) for (char c : plain) { switch (c) { - case '"': - os << "\\\""; - break; - case '\\': - os << "\\\\"; - break; - case '/': - os << "\\/"; - break; - case '\b': - os << "\\b"; - break; - case '\f': - os << "\\f"; - break; - case '\n': - os << "\\n"; - break; - case '\r': - os << "\\r"; - break; - case '\t': - os << "\\t"; - break; - default: { - if (c >= 32 && c <= 126) { - os << c; - } else { - u32 cnum = (u8)c; - os << "\\u" << std::hex << std::setw(4) - << std::setfill('0') << cnum; - } - break; + case '"': + os << "\\\""; + break; + case '\\': + os << "\\\\"; + break; + case '/': + os << "\\/"; + break; + case '\b': + os << "\\b"; + break; + case '\f': + os << "\\f"; + break; + case '\n': + os << "\\n"; + break; + case '\r': + os << "\\r"; + break; + case '\t': + os << "\\t"; + break; + default: { + if (c >= 32 && c <= 126) { + os << c; + } else { + u32 cnum = (u8)c; + os << "\\u" << std::hex << std::setw(4) + << std::setfill('0') << cnum; } + break; + } } } @@ -313,38 +314,39 @@ std::string deSerializeJsonString(std::istream &is) if (is.eof()) throw SerializationError("JSON string ended prematurely"); switch (c2) { - case 'b': - os << '\b'; - break; - case 'f': - os << '\f'; - break; - case 'n': - os << '\n'; - break; - case 'r': - os << '\r'; - break; - case 't': - os << '\t'; - break; - case 'u': { - int hexnumber; - char hexdigits[4 + 1]; - - is.read(hexdigits, 4); - if (is.eof()) - throw SerializationError("JSON string ended prematurely"); - hexdigits[4] = 0; - - std::istringstream tmp_is(hexdigits, std::ios::binary); - tmp_is >> std::hex >> hexnumber; - os << (char)hexnumber; - break; - } - default: - os << c2; - break; + case 'b': + os << '\b'; + break; + case 'f': + os << '\f'; + break; + case 'n': + os << '\n'; + break; + case 'r': + os << '\r'; + break; + case 't': + os << '\t'; + break; + case 'u': { + int hexnumber; + char hexdigits[4 + 1]; + + is.read(hexdigits, 4); + if (is.eof()) + throw SerializationError( + "JSON string ended prematurely"); + hexdigits[4] = 0; + + std::istringstream tmp_is(hexdigits, std::ios::binary); + tmp_is >> std::hex >> hexnumber; + os << (char)hexnumber; + break; + } + default: + os << c2; + break; } } else { os << c; @@ -377,7 +379,7 @@ std::string deSerializeJsonStringIfNeeded(std::istream &is) if (expect_initial_quote && c == '"') { tmp_os << c; is_json = true; - } else if(is_json) { + } else if (is_json) { tmp_os << c; if (was_backslash) was_backslash = false; @@ -408,8 +410,8 @@ std::string deSerializeJsonStringIfNeeded(std::istream &is) //// String/Struct conversions //// -bool deSerializeStringToStruct(std::string valstr, - std::string format, void *out, size_t olen) +bool deSerializeStringToStruct( + std::string valstr, std::string format, void *out, size_t olen) { size_t len = olen; std::vector<std::string *> strs_alloced; @@ -434,130 +436,130 @@ bool deSerializeStringToStruct(std::string valstr, valtype = 'i'; switch (valtype) { - case 'u': - is_unsigned = true; - /* FALLTHROUGH */ - case 'i': - if (width == 16) { - bufpos += PADDING(bufpos, u16); - if ((bufpos - buf) + sizeof(u16) <= len) { - if (is_unsigned) - *(u16 *)bufpos = (u16)strtoul(s, &s, 10); - else - *(s16 *)bufpos = (s16)strtol(s, &s, 10); - } - bufpos += sizeof(u16); - } else if (width == 32) { - bufpos += PADDING(bufpos, u32); - if ((bufpos - buf) + sizeof(u32) <= len) { - if (is_unsigned) - *(u32 *)bufpos = (u32)strtoul(s, &s, 10); - else - *(s32 *)bufpos = (s32)strtol(s, &s, 10); - } - bufpos += sizeof(u32); - } else if (width == 64) { - bufpos += PADDING(bufpos, u64); - if ((bufpos - buf) + sizeof(u64) <= len) { - if (is_unsigned) - *(u64 *)bufpos = (u64)strtoull(s, &s, 10); - else - *(s64 *)bufpos = (s64)strtoll(s, &s, 10); - } - bufpos += sizeof(u64); + case 'u': + is_unsigned = true; + /* FALLTHROUGH */ + case 'i': + if (width == 16) { + bufpos += PADDING(bufpos, u16); + if ((bufpos - buf) + sizeof(u16) <= len) { + if (is_unsigned) + *(u16 *)bufpos = (u16)strtoul(s, &s, 10); + else + *(s16 *)bufpos = (s16)strtol(s, &s, 10); } - s = strchr(s, ','); - break; - case 'b': - snext = strchr(s, ','); - if (snext) - *snext++ = 0; + bufpos += sizeof(u16); + } else if (width == 32) { + bufpos += PADDING(bufpos, u32); + if ((bufpos - buf) + sizeof(u32) <= len) { + if (is_unsigned) + *(u32 *)bufpos = (u32)strtoul(s, &s, 10); + else + *(s32 *)bufpos = (s32)strtol(s, &s, 10); + } + bufpos += sizeof(u32); + } else if (width == 64) { + bufpos += PADDING(bufpos, u64); + if ((bufpos - buf) + sizeof(u64) <= len) { + if (is_unsigned) + *(u64 *)bufpos = (u64)strtoull(s, &s, 10); + else + *(s64 *)bufpos = (s64)strtoll(s, &s, 10); + } + bufpos += sizeof(u64); + } + s = strchr(s, ','); + break; + case 'b': + snext = strchr(s, ','); + if (snext) + *snext++ = 0; - bufpos += PADDING(bufpos, bool); - if ((bufpos - buf) + sizeof(bool) <= len) - *(bool *)bufpos = is_yes(std::string(s)); - bufpos += sizeof(bool); + bufpos += PADDING(bufpos, bool); + if ((bufpos - buf) + sizeof(bool) <= len) + *(bool *)bufpos = is_yes(std::string(s)); + bufpos += sizeof(bool); - s = snext; - break; - case 'f': - bufpos += PADDING(bufpos, float); - if ((bufpos - buf) + sizeof(float) <= len) - *(float *)bufpos = strtof(s, &s); - bufpos += sizeof(float); + s = snext; + break; + case 'f': + bufpos += PADDING(bufpos, float); + if ((bufpos - buf) + sizeof(float) <= len) + *(float *)bufpos = strtof(s, &s); + bufpos += sizeof(float); - s = strchr(s, ','); - break; - case 's': - while (*s == ' ' || *s == '\t') - s++; - if (*s++ != '"') //error, expected string - goto fail; - snext = s; + s = strchr(s, ','); + break; + case 's': + while (*s == ' ' || *s == '\t') + s++; + if (*s++ != '"') // error, expected string + goto fail; + snext = s; - while (snext[0] && !(snext[-1] != '\\' && snext[0] == '"')) - snext++; - *snext++ = 0; + while (snext[0] && !(snext[-1] != '\\' && snext[0] == '"')) + snext++; + *snext++ = 0; - bufpos += PADDING(bufpos, std::string *); + bufpos += PADDING(bufpos, std::string *); - str = new std::string(s); - pos = 0; - while ((pos = str->find("\\\"", pos)) != std::string::npos) - str->erase(pos, 1); + str = new std::string(s); + pos = 0; + while ((pos = str->find("\\\"", pos)) != std::string::npos) + str->erase(pos, 1); - if ((bufpos - buf) + sizeof(std::string *) <= len) - *(std::string **)bufpos = str; - bufpos += sizeof(std::string *); - strs_alloced.push_back(str); + if ((bufpos - buf) + sizeof(std::string *) <= len) + *(std::string **)bufpos = str; + bufpos += sizeof(std::string *); + strs_alloced.push_back(str); - s = *snext ? snext + 1 : nullptr; - break; - case 'v': - while (*s == ' ' || *s == '\t') - s++; - if (*s++ != '(') //error, expected vector - goto fail; + s = *snext ? snext + 1 : nullptr; + break; + case 'v': + while (*s == ' ' || *s == '\t') + s++; + if (*s++ != '(') // error, expected vector + goto fail; - if (width == 2) { - bufpos += PADDING(bufpos, v2f); + if (width == 2) { + bufpos += PADDING(bufpos, v2f); - if ((bufpos - buf) + sizeof(v2f) <= len) { + if ((bufpos - buf) + sizeof(v2f) <= len) { v2f *v = (v2f *)bufpos; - v->X = strtof(s, &s); - s++; - v->Y = strtof(s, &s); - } - - bufpos += sizeof(v2f); - } else if (width == 3) { - bufpos += PADDING(bufpos, v3f); - if ((bufpos - buf) + sizeof(v3f) <= len) { - v3f *v = (v3f *)bufpos; - v->X = strtof(s, &s); - s++; - v->Y = strtof(s, &s); - s++; - v->Z = strtof(s, &s); - } - - bufpos += sizeof(v3f); + v->X = strtof(s, &s); + s++; + v->Y = strtof(s, &s); } - s = strchr(s, ','); - break; - default: //error, invalid format specifier - goto fail; + + bufpos += sizeof(v2f); + } else if (width == 3) { + bufpos += PADDING(bufpos, v3f); + if ((bufpos - buf) + sizeof(v3f) <= len) { + v3f *v = (v3f *)bufpos; + v->X = strtof(s, &s); + s++; + v->Y = strtof(s, &s); + s++; + v->Z = strtof(s, &s); + } + + bufpos += sizeof(v3f); + } + s = strchr(s, ','); + break; + default: // error, invalid format specifier + goto fail; } if (s && *s == ',') s++; - if ((size_t)(bufpos - buf) > len) //error, buffer too small + if ((size_t)(bufpos - buf) > len) // error, buffer too small goto fail; } - if (f && *f) { //error, mismatched number of fields and values -fail: + if (f && *f) { // error, mismatched number of fields and values + fail: for (size_t i = 0; i != strs_alloced.size(); i++) delete strs_alloced[i]; delete[] buf; @@ -570,17 +572,16 @@ fail: } // Casts *buf to a signed or unsigned fixed-width integer of 'w' width -#define SIGN_CAST(w, buf) (is_unsigned ? *((u##w *) buf) : *((s##w *) buf)) +#define SIGN_CAST(w, buf) (is_unsigned ? *((u##w *)buf) : *((s##w *)buf)) -bool serializeStructToString(std::string *out, - std::string format, void *value) +bool serializeStructToString(std::string *out, std::string format, void *value) { std::ostringstream os; std::string str; char *f; size_t strpos; - char *bufpos = (char *) value; + char *bufpos = (char *)value; char *fmtpos, *fmt = &format[0]; while ((f = strtok_r(fmt, ",", &fmtpos))) { fmt = nullptr; @@ -593,62 +594,62 @@ bool serializeStructToString(std::string *out, valtype = 'i'; switch (valtype) { - case 'u': - is_unsigned = true; - /* FALLTHROUGH */ - case 'i': - if (width == 16) { - bufpos += PADDING(bufpos, u16); - os << SIGN_CAST(16, bufpos); - bufpos += sizeof(u16); - } else if (width == 32) { - bufpos += PADDING(bufpos, u32); - os << SIGN_CAST(32, bufpos); - bufpos += sizeof(u32); - } else if (width == 64) { - bufpos += PADDING(bufpos, u64); - os << SIGN_CAST(64, bufpos); - bufpos += sizeof(u64); - } - break; - case 'b': - bufpos += PADDING(bufpos, bool); - os << std::boolalpha << *((bool *) bufpos); - bufpos += sizeof(bool); - break; - case 'f': - bufpos += PADDING(bufpos, float); - os << *((float *) bufpos); - bufpos += sizeof(float); - break; - case 's': - bufpos += PADDING(bufpos, std::string *); - str = **((std::string **) bufpos); - - strpos = 0; - while ((strpos = str.find('"', strpos)) != std::string::npos) { - str.insert(strpos, 1, '\\'); - strpos += 2; - } + case 'u': + is_unsigned = true; + /* FALLTHROUGH */ + case 'i': + if (width == 16) { + bufpos += PADDING(bufpos, u16); + os << SIGN_CAST(16, bufpos); + bufpos += sizeof(u16); + } else if (width == 32) { + bufpos += PADDING(bufpos, u32); + os << SIGN_CAST(32, bufpos); + bufpos += sizeof(u32); + } else if (width == 64) { + bufpos += PADDING(bufpos, u64); + os << SIGN_CAST(64, bufpos); + bufpos += sizeof(u64); + } + break; + case 'b': + bufpos += PADDING(bufpos, bool); + os << std::boolalpha << *((bool *)bufpos); + bufpos += sizeof(bool); + break; + case 'f': + bufpos += PADDING(bufpos, float); + os << *((float *)bufpos); + bufpos += sizeof(float); + break; + case 's': + bufpos += PADDING(bufpos, std::string *); + str = **((std::string **)bufpos); + + strpos = 0; + while ((strpos = str.find('"', strpos)) != std::string::npos) { + str.insert(strpos, 1, '\\'); + strpos += 2; + } - os << str; - bufpos += sizeof(std::string *); - break; - case 'v': - if (width == 2) { - bufpos += PADDING(bufpos, v2f); - v2f *v = (v2f *) bufpos; - os << '(' << v->X << ", " << v->Y << ')'; - bufpos += sizeof(v2f); - } else { - bufpos += PADDING(bufpos, v3f); - v3f *v = (v3f *) bufpos; - os << '(' << v->X << ", " << v->Y << ", " << v->Z << ')'; - bufpos += sizeof(v3f); - } - break; - default: - return false; + os << str; + bufpos += sizeof(std::string *); + break; + case 'v': + if (width == 2) { + bufpos += PADDING(bufpos, v2f); + v2f *v = (v2f *)bufpos; + os << '(' << v->X << ", " << v->Y << ')'; + bufpos += sizeof(v2f); + } else { + bufpos += PADDING(bufpos, v3f); + v3f *v = (v3f *)bufpos; + os << '(' << v->X << ", " << v->Y << ", " << v->Z << ')'; + bufpos += sizeof(v3f); + } + break; + default: + return false; } os << ", "; } diff --git a/src/util/serialize.h b/src/util/serialize.h index a4b5a234a..3ecc8e85b 100644 --- a/src/util/serialize.h +++ b/src/util/serialize.h @@ -21,22 +21,22 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "irrlichttypes_bloated.h" #include "exceptions.h" // for SerializationError -#include "debug.h" // for assert +#include "debug.h" // for assert #include "ieee_float.h" #include "config.h" #if HAVE_ENDIAN_H - #ifdef _WIN32 - #define __BYTE_ORDER 0 - #define __LITTLE_ENDIAN 0 - #define __BIG_ENDIAN 1 - #elif defined(__MACH__) && defined(__APPLE__) - #include <machine/endian.h> - #elif defined(__FreeBSD__) || defined(__DragonFly__) - #include <sys/endian.h> - #else - #include <endian.h> - #endif +#ifdef _WIN32 +#define __BYTE_ORDER 0 +#define __LITTLE_ENDIAN 0 +#define __BIG_ENDIAN 1 +#elif defined(__MACH__) && defined(__APPLE__) +#include <machine/endian.h> +#elif defined(__FreeBSD__) || defined(__DragonFly__) +#include <sys/endian.h> +#else +#include <endian.h> +#endif #endif #include <cstring> // for memcpy #include <iostream> @@ -60,7 +60,6 @@ with this program; if not, write to the Free Software Foundation, Inc., // 64 MB ought to be enough for anybody - Billy G. #define LONG_STRING_MAX_LEN (64 * 1024 * 1024) - extern FloatType g_serialize_f32_type; #if HAVE_ENDIAN_H @@ -111,24 +110,20 @@ inline void writeU64(u8 *data, u64 i) inline u16 readU16(const u8 *data) { - return - ((u16)data[0] << 8) | ((u16)data[1] << 0); + return ((u16)data[0] << 8) | ((u16)data[1] << 0); } inline u32 readU32(const u8 *data) { - return - ((u32)data[0] << 24) | ((u32)data[1] << 16) | - ((u32)data[2] << 8) | ((u32)data[3] << 0); + return ((u32)data[0] << 24) | ((u32)data[1] << 16) | ((u32)data[2] << 8) | + ((u32)data[3] << 0); } inline u64 readU64(const u8 *data) { - return - ((u64)data[0] << 56) | ((u64)data[1] << 48) | - ((u64)data[2] << 40) | ((u64)data[3] << 32) | - ((u64)data[4] << 24) | ((u64)data[5] << 16) | - ((u64)data[6] << 8) | ((u64)data[7] << 0); + return ((u64)data[0] << 56) | ((u64)data[1] << 48) | ((u64)data[2] << 40) | + ((u64)data[3] << 32) | ((u64)data[4] << 24) | ((u64)data[5] << 16) | + ((u64)data[6] << 8) | ((u64)data[7] << 0); } inline void writeU16(u8 *data, u16 i) @@ -141,8 +136,8 @@ inline void writeU32(u8 *data, u32 i) { data[0] = (i >> 24) & 0xFF; data[1] = (i >> 16) & 0xFF; - data[2] = (i >> 8) & 0xFF; - data[3] = (i >> 0) & 0xFF; + data[2] = (i >> 8) & 0xFF; + data[3] = (i >> 0) & 0xFF; } inline void writeU64(u8 *data, u64 i) @@ -153,8 +148,8 @@ inline void writeU64(u8 *data, u64 i) data[3] = (i >> 32) & 0xFF; data[4] = (i >> 24) & 0xFF; data[5] = (i >> 16) & 0xFF; - data[6] = (i >> 8) & 0xFF; - data[7] = (i >> 0) & 0xFF; + data[6] = (i >> 8) & 0xFF; + data[7] = (i >> 0) & 0xFF; } #endif // HAVE_ENDIAN_H @@ -197,10 +192,10 @@ inline f32 readF32(const u8 *data) switch (g_serialize_f32_type) { case FLOATTYPE_SYSTEM: { - f32 f; - memcpy(&f, &u, 4); - return f; - } + f32 f; + memcpy(&f, &u, 4); + return f; + } case FLOATTYPE_SLOW: return u32Tof32Slow(u); case FLOATTYPE_UNKNOWN: // First initialization @@ -290,7 +285,7 @@ inline void writeS8(u8 *data, s8 i) inline void writeS16(u8 *data, s16 i) { - writeU16(data, (u16)i); + writeU16(data, (u16)i); } inline void writeS32(u8 *data, s32 i) @@ -313,10 +308,10 @@ inline void writeF32(u8 *data, f32 i) { switch (g_serialize_f32_type) { case FLOATTYPE_SYSTEM: { - u32 u; - memcpy(&u, &i, 4); - return writeU32(data, u); - } + u32 u; + memcpy(&u, &i, 4); + return writeU32(data, u); + } case FLOATTYPE_SLOW: return writeU32(data, f32Tou32Slow(i)); case FLOATTYPE_UNKNOWN: // First initialization @@ -381,58 +376,58 @@ inline void writeV3F32(u8 *data, v3f p) //// Iostream wrapper for data read/write //// -#define MAKE_STREAM_READ_FXN(T, N, S) \ - inline T read ## N(std::istream &is) \ - { \ - char buf[S] = {0}; \ - is.read(buf, sizeof(buf)); \ - return read ## N((u8 *)buf); \ +#define MAKE_STREAM_READ_FXN(T, N, S) \ + inline T read##N(std::istream &is) \ + { \ + char buf[S] = {0}; \ + is.read(buf, sizeof(buf)); \ + return read##N((u8 *)buf); \ } -#define MAKE_STREAM_WRITE_FXN(T, N, S) \ - inline void write ## N(std::ostream &os, T val) \ - { \ - char buf[S]; \ - write ## N((u8 *)buf, val); \ - os.write(buf, sizeof(buf)); \ +#define MAKE_STREAM_WRITE_FXN(T, N, S) \ + inline void write##N(std::ostream &os, T val) \ + { \ + char buf[S]; \ + write##N((u8 *)buf, val); \ + os.write(buf, sizeof(buf)); \ } -MAKE_STREAM_READ_FXN(u8, U8, 1); -MAKE_STREAM_READ_FXN(u16, U16, 2); -MAKE_STREAM_READ_FXN(u32, U32, 4); -MAKE_STREAM_READ_FXN(u64, U64, 8); -MAKE_STREAM_READ_FXN(s8, S8, 1); -MAKE_STREAM_READ_FXN(s16, S16, 2); -MAKE_STREAM_READ_FXN(s32, S32, 4); -MAKE_STREAM_READ_FXN(s64, S64, 8); -MAKE_STREAM_READ_FXN(f32, F1000, 4); -MAKE_STREAM_READ_FXN(f32, F32, 4); -MAKE_STREAM_READ_FXN(v2s16, V2S16, 4); -MAKE_STREAM_READ_FXN(v3s16, V3S16, 6); -MAKE_STREAM_READ_FXN(v2s32, V2S32, 8); -MAKE_STREAM_READ_FXN(v3s32, V3S32, 12); -MAKE_STREAM_READ_FXN(v3f, V3F1000, 12); -MAKE_STREAM_READ_FXN(v2f, V2F32, 8); -MAKE_STREAM_READ_FXN(v3f, V3F32, 12); +MAKE_STREAM_READ_FXN(u8, U8, 1); +MAKE_STREAM_READ_FXN(u16, U16, 2); +MAKE_STREAM_READ_FXN(u32, U32, 4); +MAKE_STREAM_READ_FXN(u64, U64, 8); +MAKE_STREAM_READ_FXN(s8, S8, 1); +MAKE_STREAM_READ_FXN(s16, S16, 2); +MAKE_STREAM_READ_FXN(s32, S32, 4); +MAKE_STREAM_READ_FXN(s64, S64, 8); +MAKE_STREAM_READ_FXN(f32, F1000, 4); +MAKE_STREAM_READ_FXN(f32, F32, 4); +MAKE_STREAM_READ_FXN(v2s16, V2S16, 4); +MAKE_STREAM_READ_FXN(v3s16, V3S16, 6); +MAKE_STREAM_READ_FXN(v2s32, V2S32, 8); +MAKE_STREAM_READ_FXN(v3s32, V3S32, 12); +MAKE_STREAM_READ_FXN(v3f, V3F1000, 12); +MAKE_STREAM_READ_FXN(v2f, V2F32, 8); +MAKE_STREAM_READ_FXN(v3f, V3F32, 12); MAKE_STREAM_READ_FXN(video::SColor, ARGB8, 4); -MAKE_STREAM_WRITE_FXN(u8, U8, 1); -MAKE_STREAM_WRITE_FXN(u16, U16, 2); -MAKE_STREAM_WRITE_FXN(u32, U32, 4); -MAKE_STREAM_WRITE_FXN(u64, U64, 8); -MAKE_STREAM_WRITE_FXN(s8, S8, 1); -MAKE_STREAM_WRITE_FXN(s16, S16, 2); -MAKE_STREAM_WRITE_FXN(s32, S32, 4); -MAKE_STREAM_WRITE_FXN(s64, S64, 8); -MAKE_STREAM_WRITE_FXN(f32, F1000, 4); -MAKE_STREAM_WRITE_FXN(f32, F32, 4); -MAKE_STREAM_WRITE_FXN(v2s16, V2S16, 4); -MAKE_STREAM_WRITE_FXN(v3s16, V3S16, 6); -MAKE_STREAM_WRITE_FXN(v2s32, V2S32, 8); -MAKE_STREAM_WRITE_FXN(v3s32, V3S32, 12); -MAKE_STREAM_WRITE_FXN(v3f, V3F1000, 12); -MAKE_STREAM_WRITE_FXN(v2f, V2F32, 8); -MAKE_STREAM_WRITE_FXN(v3f, V3F32, 12); +MAKE_STREAM_WRITE_FXN(u8, U8, 1); +MAKE_STREAM_WRITE_FXN(u16, U16, 2); +MAKE_STREAM_WRITE_FXN(u32, U32, 4); +MAKE_STREAM_WRITE_FXN(u64, U64, 8); +MAKE_STREAM_WRITE_FXN(s8, S8, 1); +MAKE_STREAM_WRITE_FXN(s16, S16, 2); +MAKE_STREAM_WRITE_FXN(s32, S32, 4); +MAKE_STREAM_WRITE_FXN(s64, S64, 8); +MAKE_STREAM_WRITE_FXN(f32, F1000, 4); +MAKE_STREAM_WRITE_FXN(f32, F32, 4); +MAKE_STREAM_WRITE_FXN(v2s16, V2S16, 4); +MAKE_STREAM_WRITE_FXN(v3s16, V3S16, 6); +MAKE_STREAM_WRITE_FXN(v2s32, V2S32, 8); +MAKE_STREAM_WRITE_FXN(v3s32, V3S32, 12); +MAKE_STREAM_WRITE_FXN(v3f, V3F1000, 12); +MAKE_STREAM_WRITE_FXN(v2f, V2F32, 8); +MAKE_STREAM_WRITE_FXN(v3f, V3F32, 12); MAKE_STREAM_WRITE_FXN(video::SColor, ARGB8, 4); //// @@ -471,63 +466,59 @@ std::string serializeJsonStringIfNeeded(const std::string &s); std::string deSerializeJsonStringIfNeeded(std::istream &is); // Creates a string consisting of the hexadecimal representation of `data` -std::string serializeHexString(const std::string &data, bool insert_spaces=false); +std::string serializeHexString(const std::string &data, bool insert_spaces = false); // Creates a string containing comma delimited values of a struct whose layout is // described by the parameter format -bool serializeStructToString(std::string *out, - std::string format, void *value); +bool serializeStructToString(std::string *out, std::string format, void *value); // Reads a comma delimited string of values into a struct whose layout is // decribed by the parameter format -bool deSerializeStringToStruct(std::string valstr, - std::string format, void *out, size_t olen); +bool deSerializeStringToStruct( + std::string valstr, std::string format, void *out, size_t olen); //// //// BufReader //// -#define MAKE_BUFREADER_GETNOEX_FXN(T, N, S) \ - inline bool get ## N ## NoEx(T *val) \ - { \ - if (pos + S > size) \ - return false; \ - *val = read ## N(data + pos); \ - pos += S; \ - return true; \ +#define MAKE_BUFREADER_GETNOEX_FXN(T, N, S) \ + inline bool get##N##NoEx(T *val) \ + { \ + if (pos + S > size) \ + return false; \ + *val = read##N(data + pos); \ + pos += S; \ + return true; \ } -#define MAKE_BUFREADER_GET_FXN(T, N) \ - inline T get ## N() \ - { \ - T val; \ - if (!get ## N ## NoEx(&val)) \ - throw SerializationError("Attempted read past end of data"); \ - return val; \ +#define MAKE_BUFREADER_GET_FXN(T, N) \ + inline T get##N() \ + { \ + T val; \ + if (!get##N##NoEx(&val)) \ + throw SerializationError("Attempted read past end of data"); \ + return val; \ } -class BufReader { +class BufReader +{ public: - BufReader(const u8 *data_, size_t size_) : - data(data_), - size(size_) - { - } - - MAKE_BUFREADER_GETNOEX_FXN(u8, U8, 1); - MAKE_BUFREADER_GETNOEX_FXN(u16, U16, 2); - MAKE_BUFREADER_GETNOEX_FXN(u32, U32, 4); - MAKE_BUFREADER_GETNOEX_FXN(u64, U64, 8); - MAKE_BUFREADER_GETNOEX_FXN(s8, S8, 1); - MAKE_BUFREADER_GETNOEX_FXN(s16, S16, 2); - MAKE_BUFREADER_GETNOEX_FXN(s32, S32, 4); - MAKE_BUFREADER_GETNOEX_FXN(s64, S64, 8); - MAKE_BUFREADER_GETNOEX_FXN(f32, F1000, 4); - MAKE_BUFREADER_GETNOEX_FXN(v2s16, V2S16, 4); - MAKE_BUFREADER_GETNOEX_FXN(v3s16, V3S16, 6); - MAKE_BUFREADER_GETNOEX_FXN(v2s32, V2S32, 8); - MAKE_BUFREADER_GETNOEX_FXN(v3s32, V3S32, 12); - MAKE_BUFREADER_GETNOEX_FXN(v3f, V3F1000, 12); + BufReader(const u8 *data_, size_t size_) : data(data_), size(size_) {} + + MAKE_BUFREADER_GETNOEX_FXN(u8, U8, 1); + MAKE_BUFREADER_GETNOEX_FXN(u16, U16, 2); + MAKE_BUFREADER_GETNOEX_FXN(u32, U32, 4); + MAKE_BUFREADER_GETNOEX_FXN(u64, U64, 8); + MAKE_BUFREADER_GETNOEX_FXN(s8, S8, 1); + MAKE_BUFREADER_GETNOEX_FXN(s16, S16, 2); + MAKE_BUFREADER_GETNOEX_FXN(s32, S32, 4); + MAKE_BUFREADER_GETNOEX_FXN(s64, S64, 8); + MAKE_BUFREADER_GETNOEX_FXN(f32, F1000, 4); + MAKE_BUFREADER_GETNOEX_FXN(v2s16, V2S16, 4); + MAKE_BUFREADER_GETNOEX_FXN(v3s16, V3S16, 6); + MAKE_BUFREADER_GETNOEX_FXN(v2s32, V2S32, 8); + MAKE_BUFREADER_GETNOEX_FXN(v3s32, V3S32, 12); + MAKE_BUFREADER_GETNOEX_FXN(v3f, V3F1000, 12); MAKE_BUFREADER_GETNOEX_FXN(video::SColor, ARGB8, 4); bool getStringNoEx(std::string *val); @@ -535,24 +526,24 @@ public: bool getLongStringNoEx(std::string *val); bool getRawDataNoEx(void *data, size_t len); - MAKE_BUFREADER_GET_FXN(u8, U8); - MAKE_BUFREADER_GET_FXN(u16, U16); - MAKE_BUFREADER_GET_FXN(u32, U32); - MAKE_BUFREADER_GET_FXN(u64, U64); - MAKE_BUFREADER_GET_FXN(s8, S8); - MAKE_BUFREADER_GET_FXN(s16, S16); - MAKE_BUFREADER_GET_FXN(s32, S32); - MAKE_BUFREADER_GET_FXN(s64, S64); - MAKE_BUFREADER_GET_FXN(f32, F1000); - MAKE_BUFREADER_GET_FXN(v2s16, V2S16); - MAKE_BUFREADER_GET_FXN(v3s16, V3S16); - MAKE_BUFREADER_GET_FXN(v2s32, V2S32); - MAKE_BUFREADER_GET_FXN(v3s32, V3S32); - MAKE_BUFREADER_GET_FXN(v3f, V3F1000); + MAKE_BUFREADER_GET_FXN(u8, U8); + MAKE_BUFREADER_GET_FXN(u16, U16); + MAKE_BUFREADER_GET_FXN(u32, U32); + MAKE_BUFREADER_GET_FXN(u64, U64); + MAKE_BUFREADER_GET_FXN(s8, S8); + MAKE_BUFREADER_GET_FXN(s16, S16); + MAKE_BUFREADER_GET_FXN(s32, S32); + MAKE_BUFREADER_GET_FXN(s64, S64); + MAKE_BUFREADER_GET_FXN(f32, F1000); + MAKE_BUFREADER_GET_FXN(v2s16, V2S16); + MAKE_BUFREADER_GET_FXN(v3s16, V3S16); + MAKE_BUFREADER_GET_FXN(v2s32, V2S32); + MAKE_BUFREADER_GET_FXN(v3s32, V3S32); + MAKE_BUFREADER_GET_FXN(v3f, V3F1000); MAKE_BUFREADER_GET_FXN(video::SColor, ARGB8); - MAKE_BUFREADER_GET_FXN(std::string, String); - MAKE_BUFREADER_GET_FXN(std::wstring, WideString); - MAKE_BUFREADER_GET_FXN(std::string, LongString); + MAKE_BUFREADER_GET_FXN(std::string, String); + MAKE_BUFREADER_GET_FXN(std::wstring, WideString); + MAKE_BUFREADER_GET_FXN(std::string, LongString); inline void getRawData(void *val, size_t len) { @@ -574,7 +565,6 @@ public: #undef MAKE_BUFREADER_GET_FXN #undef MAKE_BUFREADER_GETNOEX_FXN - //// //// Vector-based write routines //// @@ -594,8 +584,8 @@ inline void putU32(std::vector<u8> *dest, u32 val) { dest->push_back((val >> 24) & 0xFF); dest->push_back((val >> 16) & 0xFF); - dest->push_back((val >> 8) & 0xFF); - dest->push_back((val >> 0) & 0xFF); + dest->push_back((val >> 8) & 0xFF); + dest->push_back((val >> 0) & 0xFF); } inline void putU64(std::vector<u8> *dest, u64 val) @@ -606,8 +596,8 @@ inline void putU64(std::vector<u8> *dest, u64 val) dest->push_back((val >> 32) & 0xFF); dest->push_back((val >> 24) & 0xFF); dest->push_back((val >> 16) & 0xFF); - dest->push_back((val >> 8) & 0xFF); - dest->push_back((val >> 0) & 0xFF); + dest->push_back((val >> 8) & 0xFF); + dest->push_back((val >> 0) & 0xFF); } inline void putS8(std::vector<u8> *dest, s8 val) diff --git a/src/util/sha1.cpp b/src/util/sha1.cpp index d61b262af..313a56aa8 100644 --- a/src/util/sha1.cpp +++ b/src/util/sha1.cpp @@ -32,40 +32,38 @@ SOFTWARE. #include "sha1.h" // print out memory in hexadecimal -void SHA1::hexPrinter( unsigned char* c, int l ) +void SHA1::hexPrinter(unsigned char *c, int l) { - assert( c ); - assert( l > 0 ); - while( l > 0 ) - { - printf( " %02x", *c ); + assert(c); + assert(l > 0); + while (l > 0) { + printf(" %02x", *c); l--; c++; } } // circular left bit rotation. MSB wraps around to LSB -Uint32 SHA1::lrot( Uint32 x, int bits ) +Uint32 SHA1::lrot(Uint32 x, int bits) { - return (x<<bits) | (x>>(32 - bits)); + return (x << bits) | (x >> (32 - bits)); }; // Save a 32-bit unsigned integer to memory, in big-endian order -void SHA1::storeBigEndianUint32( unsigned char* byte, Uint32 num ) +void SHA1::storeBigEndianUint32(unsigned char *byte, Uint32 num) { - assert( byte ); - byte[0] = (unsigned char)(num>>24); - byte[1] = (unsigned char)(num>>16); - byte[2] = (unsigned char)(num>>8); + assert(byte); + byte[0] = (unsigned char)(num >> 24); + byte[1] = (unsigned char)(num >> 16); + byte[2] = (unsigned char)(num >> 8); byte[3] = (unsigned char)num; } - // Constructor ******************************************************* SHA1::SHA1() { // make sure that the data type is the right size - assert( sizeof( Uint32 ) * 5 == 20 ); + assert(sizeof(Uint32) * 5 == 20); } // Destructor ******************************************************** @@ -73,15 +71,16 @@ SHA1::~SHA1() { // erase data H0 = H1 = H2 = H3 = H4 = 0; - for( int c = 0; c < 64; c++ ) bytes[c] = 0; + for (int c = 0; c < 64; c++) + bytes[c] = 0; unprocessedBytes = size = 0; } // process *********************************************************** void SHA1::process() { - assert( unprocessedBytes == 64 ); - //printf( "process: " ); hexPrinter( bytes, 64 ); printf( "\n" ); + assert(unprocessedBytes == 64); + // printf( "process: " ); hexPrinter( bytes, 64 ); printf( "\n" ); int t; Uint32 a, b, c, d, e, K, f, W[80]; // starting values @@ -91,36 +90,35 @@ void SHA1::process() d = H3; e = H4; // copy and expand the message block - for( t = 0; t < 16; t++ ) W[t] = (bytes[t*4] << 24) - +(bytes[t*4 + 1] << 16) - +(bytes[t*4 + 2] << 8) - + bytes[t*4 + 3]; - for(; t< 80; t++ ) W[t] = lrot( W[t-3]^W[t-8]^W[t-14]^W[t-16], 1 ); + for (t = 0; t < 16; t++) + W[t] = (bytes[t * 4] << 24) + (bytes[t * 4 + 1] << 16) + + (bytes[t * 4 + 2] << 8) + bytes[t * 4 + 3]; + for (; t < 80; t++) + W[t] = lrot(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); /* main loop */ Uint32 temp; - for( t = 0; t < 80; t++ ) - { - if( t < 20 ) { + for (t = 0; t < 80; t++) { + if (t < 20) { K = 0x5a827999; - f = (b & c) | ((b ^ 0xFFFFFFFF) & d);//TODO: try using ~ - } else if( t < 40 ) { + f = (b & c) | ((b ^ 0xFFFFFFFF) & d); // TODO: try using ~ + } else if (t < 40) { K = 0x6ed9eba1; f = b ^ c ^ d; - } else if( t < 60 ) { + } else if (t < 60) { K = 0x8f1bbcdc; f = (b & c) | (b & d) | (c & d); } else { K = 0xca62c1d6; f = b ^ c ^ d; } - temp = lrot(a,5) + f + e + W[t] + K; + temp = lrot(a, 5) + f + e + W[t] + K; e = d; d = c; - c = lrot(b,30); + c = lrot(b, 30); b = a; a = temp; - //printf( "t=%d %08x %08x %08x %08x %08x\n",t,a,b,c,d,e ); + // printf( "t=%d %08x %08x %08x %08x %08x\n",t,a,b,c,d,e ); } /* add variables */ H0 += a; @@ -128,71 +126,70 @@ void SHA1::process() H2 += c; H3 += d; H4 += e; - //printf( "Current: %08x %08x %08x %08x %08x\n",H0,H1,H2,H3,H4 ); + // printf( "Current: %08x %08x %08x %08x %08x\n",H0,H1,H2,H3,H4 ); /* all bytes have been processed */ unprocessedBytes = 0; } // addBytes ********************************************************** -void SHA1::addBytes( const char* data, int num ) +void SHA1::addBytes(const char *data, int num) { - assert( data ); - assert( num >= 0 ); + assert(data); + assert(num >= 0); // add these bytes to the running total size += num; // repeat until all data is processed - while( num > 0 ) - { + while (num > 0) { // number of bytes required to complete block int needed = 64 - unprocessedBytes; - assert( needed > 0 ); + assert(needed > 0); // number of bytes to copy (use smaller of two) int toCopy = (num < needed) ? num : needed; // Copy the bytes - memcpy( bytes + unprocessedBytes, data, toCopy ); + memcpy(bytes + unprocessedBytes, data, toCopy); // Bytes have been copied num -= toCopy; data += toCopy; unprocessedBytes += toCopy; // there is a full block - if( unprocessedBytes == 64 ) process(); + if (unprocessedBytes == 64) + process(); } } // digest ************************************************************ -unsigned char* SHA1::getDigest() +unsigned char *SHA1::getDigest() { // save the message size Uint32 totalBitsL = size << 3; Uint32 totalBitsH = size >> 29; // add 0x80 to the message - addBytes( "\x80", 1 ); + addBytes("\x80", 1); - unsigned char footer[64] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + unsigned char footer[64] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0}; // block has no room for 8-byte filesize, so finish it - if( unprocessedBytes > 56 ) - addBytes( (char*)footer, 64 - unprocessedBytes); - assert( unprocessedBytes <= 56 ); + if (unprocessedBytes > 56) + addBytes((char *)footer, 64 - unprocessedBytes); + assert(unprocessedBytes <= 56); // how many zeros do we need int neededZeros = 56 - unprocessedBytes; // store file size (in bits) in big-endian format - storeBigEndianUint32( footer + neededZeros , totalBitsH ); - storeBigEndianUint32( footer + neededZeros + 4, totalBitsL ); + storeBigEndianUint32(footer + neededZeros, totalBitsH); + storeBigEndianUint32(footer + neededZeros + 4, totalBitsL); // finish the final block - addBytes( (char*)footer, neededZeros + 8 ); + addBytes((char *)footer, neededZeros + 8); // allocate memory for the digest bytes - unsigned char* digest = (unsigned char*)malloc( 20 ); + unsigned char *digest = (unsigned char *)malloc(20); // copy the digest bytes - storeBigEndianUint32( digest, H0 ); - storeBigEndianUint32( digest + 4, H1 ); - storeBigEndianUint32( digest + 8, H2 ); - storeBigEndianUint32( digest + 12, H3 ); - storeBigEndianUint32( digest + 16, H4 ); + storeBigEndianUint32(digest, H0); + storeBigEndianUint32(digest + 4, H1); + storeBigEndianUint32(digest + 8, H2); + storeBigEndianUint32(digest + 12, H3); + storeBigEndianUint32(digest + 16, H4); // return the digest return digest; } diff --git a/src/util/srp.cpp b/src/util/srp.cpp index f4d369d68..e7ccd5940 100644 --- a/src/util/srp.cpp +++ b/src/util/srp.cpp @@ -47,9 +47,9 @@ #include <config.h> #if USE_SYSTEM_GMP - #include <gmp.h> +#include <gmp.h> #else - #include <mini-gmp.h> +#include <mini-gmp.h> #endif #include <util/sha2.h> @@ -92,98 +92,100 @@ void srp_set_memory_functions( } // clang-format on -typedef struct { +typedef struct +{ mpz_t N; mpz_t g; } NGConstant; -struct NGHex { +struct NGHex +{ const char *n_hex; const char *g_hex; }; /* All constants here were pulled from Appendix A of RFC 5054 */ static struct NGHex global_Ng_constants[] = { - {/* 1024 */ - "EEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C" - "9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE4" - "8E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B29" - "7BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9A" - "FD5138FE8376435B9FC61D2FC0EB06E3", - "2"}, - {/* 2048 */ - "AC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC319294" - "3DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310D" - "CD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FB" - "D5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF74" - "7359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A" - "436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D" - "5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E73" - "03CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB6" - "94B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F" - "9E4AFF73", - "2"}, - {/* 4096 */ - "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" - "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" - "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" - "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" - "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" - "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" - "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" - "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" - "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" - "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" - "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" - "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" - "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" - "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" - "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" - "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" - "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" - "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" - "FFFFFFFFFFFFFFFF", - "5"}, - {/* 8192 */ - "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" - "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" - "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" - "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" - "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" - "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" - "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" - "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" - "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" - "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" - "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" - "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" - "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" - "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" - "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" - "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" - "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" - "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" - "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406" - "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918" - "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151" - "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03" - "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F" - "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" - "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B" - "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632" - "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E" - "6DBE115974A3926F12FEE5E438777CB6A932DF8CD8BEC4D073B931BA" - "3BC832B68D9DD300741FA7BF8AFC47ED2576F6936BA424663AAB639C" - "5AE4F5683423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9" - "22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B4BCBC886" - "2F8385DDFA9D4B7FA2C087E879683303ED5BDD3A062B3CF5B3A278A6" - "6D2A13F83F44F82DDF310EE074AB6A364597E899A0255DC164F31CC5" - "0846851DF9AB48195DED7EA1B1D510BD7EE74D73FAF36BC31ECFA268" - "359046F4EB879F924009438B481C6CD7889A002ED5EE382BC9190DA6" - "FC026E479558E4475677E9AA9E3050E2765694DFC81F56E880B96E71" - "60C980DD98EDD3DFFFFFFFFFFFFFFFFF", - "13"}, - {0, 0} /* null sentinel */ + {/* 1024 */ + "EEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C" + "9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE4" + "8E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B29" + "7BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9A" + "FD5138FE8376435B9FC61D2FC0EB06E3", + "2"}, + {/* 2048 */ + "AC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC319294" + "3DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310D" + "CD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FB" + "D5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF74" + "7359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A" + "436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D" + "5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E73" + "03CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB6" + "94B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F" + "9E4AFF73", + "2"}, + {/* 4096 */ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" + "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" + "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" + "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" + "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" + "FFFFFFFFFFFFFFFF", + "5"}, + {/* 8192 */ + "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" + "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" + "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" + "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" + "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" + "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406" + "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918" + "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151" + "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03" + "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F" + "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" + "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B" + "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632" + "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E" + "6DBE115974A3926F12FEE5E438777CB6A932DF8CD8BEC4D073B931BA" + "3BC832B68D9DD300741FA7BF8AFC47ED2576F6936BA424663AAB639C" + "5AE4F5683423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9" + "22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B4BCBC886" + "2F8385DDFA9D4B7FA2C087E879683303ED5BDD3A062B3CF5B3A278A6" + "6D2A13F83F44F82DDF310EE074AB6A364597E899A0255DC164F31CC5" + "0846851DF9AB48195DED7EA1B1D510BD7EE74D73FAF36BC31ECFA268" + "359046F4EB879F924009438B481C6CD7889A002ED5EE382BC9190DA6" + "FC026E479558E4475677E9AA9E3050E2765694DFC81F56E880B96E71" + "60C980DD98EDD3DFFFFFFFFFFFFFFFFF", + "13"}, + {0, 0} /* null sentinel */ }; static void delete_ng(NGConstant *ng) @@ -199,7 +201,8 @@ static NGConstant *new_ng(SRP_NGType ng_type, const char *n_hex, const char *g_h { NGConstant *ng = (NGConstant *)srp_alloc(sizeof(NGConstant)); - if (!ng) return 0; + if (!ng) + return 0; mpz_init(ng->N); mpz_init(ng->g); @@ -221,13 +224,15 @@ static NGConstant *new_ng(SRP_NGType ng_type, const char *n_hex, const char *g_h return ng; } -typedef union { +typedef union +{ SHA_CTX sha; SHA256_CTX sha256; // SHA512_CTX sha512; } HashCTX; -struct SRPVerifier { +struct SRPVerifier +{ SRP_HashAlgorithm hash_alg; NGConstant *ng; @@ -240,7 +245,8 @@ struct SRPVerifier { unsigned char session_key[SHA512_DIGEST_LENGTH]; }; -struct SRPUser { +struct SRPUser +{ SRP_HashAlgorithm hash_alg; NGConstant *ng; @@ -376,7 +382,7 @@ inline static void mpz_from_bin(const unsigned char *s, size_t len, mpz_t ret) // set op to (op1 * op2) mod d, using tmp for the calculation inline static void mpz_mulm( - mpz_t op, const mpz_t op1, const mpz_t op2, const mpz_t d, mpz_t tmp) + mpz_t op, const mpz_t op1, const mpz_t op2, const mpz_t d, mpz_t tmp) { mpz_mul(tmp, op1, op2); mpz_mod(op, tmp, d); @@ -384,7 +390,7 @@ inline static void mpz_mulm( // set op to (op1 + op2) mod d, using tmp for the calculation inline static void mpz_addm( - mpz_t op, const mpz_t op1, const mpz_t op2, const mpz_t d, mpz_t tmp) + mpz_t op, const mpz_t op1, const mpz_t op2, const mpz_t d, mpz_t tmp) { mpz_add(tmp, op1, op2); mpz_mod(op, tmp, d); @@ -392,14 +398,14 @@ inline static void mpz_addm( // set op to (op1 - op2) mod d, using tmp for the calculation inline static void mpz_subm( - mpz_t op, const mpz_t op1, const mpz_t op2, const mpz_t d, mpz_t tmp) + mpz_t op, const mpz_t op1, const mpz_t op2, const mpz_t d, mpz_t tmp) { mpz_sub(tmp, op1, op2); mpz_mod(op, tmp, d); } -static SRP_Result H_nn( - mpz_t result, SRP_HashAlgorithm alg, const mpz_t N, const mpz_t n1, const mpz_t n2) +static SRP_Result H_nn(mpz_t result, SRP_HashAlgorithm alg, const mpz_t N, const mpz_t n1, + const mpz_t n2) { unsigned char buff[SHA512_DIGEST_LENGTH]; size_t len_N = mpz_num_bytes(N); @@ -407,7 +413,8 @@ static SRP_Result H_nn( size_t len_n2 = mpz_num_bytes(n2); size_t nbytes = len_N + len_N; unsigned char *bin = (unsigned char *)srp_alloc(nbytes); - if (!bin) return SRP_ERR; + if (!bin) + return SRP_ERR; if (len_n1 > len_N || len_n2 > len_N) { srp_free(bin); return SRP_ERR; @@ -422,12 +429,13 @@ static SRP_Result H_nn( } static SRP_Result H_ns(mpz_t result, SRP_HashAlgorithm alg, const unsigned char *n, - size_t len_n, const unsigned char *bytes, uint32_t len_bytes) + size_t len_n, const unsigned char *bytes, uint32_t len_bytes) { unsigned char buff[SHA512_DIGEST_LENGTH]; size_t nbytes = len_n + len_bytes; unsigned char *bin = (unsigned char *)srp_alloc(nbytes); - if (!bin) return SRP_ERR; + if (!bin) + return SRP_ERR; memcpy(bin, n, len_n); memcpy(bin + len_n, bytes, len_bytes); hash(alg, bin, nbytes, buff); @@ -437,8 +445,8 @@ static SRP_Result H_ns(mpz_t result, SRP_HashAlgorithm alg, const unsigned char } static int calculate_x(mpz_t result, SRP_HashAlgorithm alg, const unsigned char *salt, - size_t salt_len, const char *username, const unsigned char *password, - size_t password_len) + size_t salt_len, const char *username, const unsigned char *password, + size_t password_len) { unsigned char ucp_hash[SHA512_DIGEST_LENGTH]; HashCTX ctx; @@ -459,7 +467,8 @@ static SRP_Result update_hash_n(SRP_HashAlgorithm alg, HashCTX *ctx, const mpz_t { size_t len = mpz_num_bytes(n); unsigned char *n_bytes = (unsigned char *)srp_alloc(len); - if (!n_bytes) return SRP_ERR; + if (!n_bytes) + return SRP_ERR; mpz_to_bin(n, n_bytes); hash_update(alg, ctx, n_bytes, len); srp_free(n_bytes); @@ -470,7 +479,8 @@ static SRP_Result hash_num(SRP_HashAlgorithm alg, const mpz_t n, unsigned char * { int nbytes = mpz_num_bytes(n); unsigned char *bin = (unsigned char *)srp_alloc(nbytes); - if (!bin) return SRP_ERR; + if (!bin) + return SRP_ERR; mpz_to_bin(n, bin); hash(alg, bin, nbytes, dest); srp_free(bin); @@ -478,8 +488,8 @@ static SRP_Result hash_num(SRP_HashAlgorithm alg, const mpz_t n, unsigned char * } static SRP_Result calculate_M(SRP_HashAlgorithm alg, NGConstant *ng, unsigned char *dest, - const char *I, const unsigned char *s_bytes, size_t s_len, const mpz_t A, - const mpz_t B, const unsigned char *K) + const char *I, const unsigned char *s_bytes, size_t s_len, const mpz_t A, + const mpz_t B, const unsigned char *K) { unsigned char H_N[SHA512_DIGEST_LENGTH]; unsigned char H_g[SHA512_DIGEST_LENGTH]; @@ -489,8 +499,10 @@ static SRP_Result calculate_M(SRP_HashAlgorithm alg, NGConstant *ng, unsigned ch size_t i = 0; size_t hash_len = hash_length(alg); - if (!hash_num(alg, ng->N, H_N)) return SRP_ERR; - if (!hash_num(alg, ng->g, H_g)) return SRP_ERR; + if (!hash_num(alg, ng->N, H_N)) + return SRP_ERR; + if (!hash_num(alg, ng->g, H_g)) + return SRP_ERR; hash(alg, (const unsigned char *)I, strlen(I), H_I); @@ -502,8 +514,10 @@ static SRP_Result calculate_M(SRP_HashAlgorithm alg, NGConstant *ng, unsigned ch hash_update(alg, &ctx, H_xor, hash_len); hash_update(alg, &ctx, H_I, hash_len); hash_update(alg, &ctx, s_bytes, s_len); - if (!update_hash_n(alg, &ctx, A)) return SRP_ERR; - if (!update_hash_n(alg, &ctx, B)) return SRP_ERR; + if (!update_hash_n(alg, &ctx, A)) + return SRP_ERR; + if (!update_hash_n(alg, &ctx, B)) + return SRP_ERR; hash_update(alg, &ctx, K, hash_len); hash_final(alg, &ctx, dest); @@ -511,13 +525,14 @@ static SRP_Result calculate_M(SRP_HashAlgorithm alg, NGConstant *ng, unsigned ch } static SRP_Result calculate_H_AMK(SRP_HashAlgorithm alg, unsigned char *dest, - const mpz_t A, const unsigned char *M, const unsigned char *K) + const mpz_t A, const unsigned char *M, const unsigned char *K) { HashCTX ctx; hash_init(alg, &ctx); - if (!update_hash_n(alg, &ctx, A)) return SRP_ERR; + if (!update_hash_n(alg, &ctx, A)) + return SRP_ERR; hash_update(alg, &ctx, M, hash_length(alg)); hash_update(alg, &ctx, K, hash_length(alg)); @@ -539,16 +554,23 @@ static SRP_Result fill_buff() if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) return SRP_ERR; - if (!CryptGenRandom(wctx, sizeof(g_rand_buff), (BYTE *)g_rand_buff)) return SRP_ERR; - if (!CryptReleaseContext(wctx, 0)) return SRP_ERR; + if (!CryptGenRandom(wctx, sizeof(g_rand_buff), (BYTE *)g_rand_buff)) + return SRP_ERR; + if (!CryptReleaseContext(wctx, 0)) + return SRP_ERR; #else fp = fopen("/dev/urandom", "r"); - if (!fp) return SRP_ERR; + if (!fp) + return SRP_ERR; - if (fread(g_rand_buff, sizeof(g_rand_buff), 1, fp) != 1) { fclose(fp); return SRP_ERR; } - if (fclose(fp)) return SRP_ERR; + if (fread(g_rand_buff, sizeof(g_rand_buff), 1, fp) != 1) { + fclose(fp); + return SRP_ERR; + } + if (fclose(fp)) + return SRP_ERR; #endif return SRP_OK; } @@ -557,7 +579,8 @@ static SRP_Result mpz_fill_random(mpz_t num) { // was call: BN_rand(num, 256, -1, 0); if (RAND_BUFF_MAX - g_rand_idx < 32) - if (fill_buff() != SRP_OK) return SRP_ERR; + if (fill_buff() != SRP_OK) + return SRP_ERR; mpz_from_bin((const unsigned char *)(&g_rand_buff[g_rand_idx]), 32, num); g_rand_idx += 32; return SRP_OK; @@ -565,7 +588,8 @@ static SRP_Result mpz_fill_random(mpz_t num) static SRP_Result init_random() { - if (g_initialized) return SRP_OK; + if (g_initialized) + return SRP_OK; SRP_Result ret = fill_buff(); g_initialized = (ret == SRP_OK); return ret; @@ -604,7 +628,8 @@ SRP_Result srp_create_salted_verification_key( SRP_HashAlgorithm alg, NGConstant *ng = new_ng(ng_type, n_hex, g_hex); - if (!ng) goto error_and_exit; + if (!ng) + goto error_and_exit; if (init_random() != SRP_OK) /* Only happens once */ goto error_and_exit; @@ -613,15 +638,17 @@ SRP_Result srp_create_salted_verification_key( SRP_HashAlgorithm alg, size_t size_to_fill = 16; *len_s = size_to_fill; if (RAND_BUFF_MAX - g_rand_idx < size_to_fill) - if (fill_buff() != SRP_OK) goto error_and_exit; + if (fill_buff() != SRP_OK) + goto error_and_exit; *bytes_s = (unsigned char *)srp_alloc(size_to_fill); - if (!*bytes_s) goto error_and_exit; + if (!*bytes_s) + goto error_and_exit; memcpy(*bytes_s, &g_rand_buff[g_rand_idx], size_to_fill); g_rand_idx += size_to_fill; } - if (!calculate_x( - x, alg, *bytes_s, *len_s, username_for_verifier, password, len_password)) + if (!calculate_x(x, alg, *bytes_s, *len_s, username_for_verifier, password, + len_password)) goto error_and_exit; srp_dbg_num(x, "Server calculated x: "); @@ -632,7 +659,8 @@ SRP_Result srp_create_salted_verification_key( SRP_HashAlgorithm alg, *bytes_v = (unsigned char *)srp_alloc(*len_v); - if (!*bytes_v) goto error_and_exit; + if (!*bytes_v) + goto error_and_exit; mpz_to_bin(v, *bytes_v); @@ -679,11 +707,13 @@ struct SRPVerifier *srp_verifier_new(SRP_HashAlgorithm alg, *len_B = 0; *bytes_B = 0; - if (!ng) goto cleanup_and_exit; + if (!ng) + goto cleanup_and_exit; ver = (struct SRPVerifier *)srp_alloc(sizeof(struct SRPVerifier)); - if (!ver) goto cleanup_and_exit; + if (!ver) + goto cleanup_and_exit; if (init_random() != SRP_OK) { /* Only happens once */ srp_free(ver); @@ -711,17 +741,20 @@ struct SRPVerifier *srp_verifier_new(SRP_HashAlgorithm alg, if (bytes_b) { mpz_from_bin(bytes_b, len_b, b); } else { - if (!mpz_fill_random(b)) goto ver_cleanup_and_exit; + if (!mpz_fill_random(b)) + goto ver_cleanup_and_exit; } - if (!H_nn(k, alg, ng->N, ng->N, ng->g)) goto ver_cleanup_and_exit; + if (!H_nn(k, alg, ng->N, ng->N, ng->g)) + goto ver_cleanup_and_exit; /* B = kv + g^b */ mpz_mulm(tmp1, k, v, ng->N, tmp3); mpz_powm(tmp2, ng->g, b, ng->N); mpz_addm(B, tmp1, tmp2, ng->N, tmp3); - if (!H_nn(u, alg, ng->N, A, B)) goto ver_cleanup_and_exit; + if (!H_nn(u, alg, ng->N, A, B)) + goto ver_cleanup_and_exit; srp_dbg_num(u, "Server calculated u: "); @@ -730,10 +763,11 @@ struct SRPVerifier *srp_verifier_new(SRP_HashAlgorithm alg, mpz_mulm(tmp2, A, tmp1, ng->N, tmp3); mpz_powm(S, tmp2, b, ng->N); - if (!hash_num(alg, S, ver->session_key)) goto ver_cleanup_and_exit; + if (!hash_num(alg, S, ver->session_key)) + goto ver_cleanup_and_exit; - if (!calculate_M( - alg, ng, ver->M, username, bytes_s, len_s, A, B, ver->session_key)) { + if (!calculate_M(alg, ng, ver->M, username, bytes_s, len_s, A, B, + ver->session_key)) { goto ver_cleanup_and_exit; } if (!calculate_H_AMK(alg, ver->H_AMK, A, ver->M, ver->session_key)) { @@ -797,9 +831,10 @@ const char *srp_verifier_get_username(struct SRPVerifier *ver) } const unsigned char *srp_verifier_get_session_key( - struct SRPVerifier *ver, size_t *key_length) + struct SRPVerifier *ver, size_t *key_length) { - if (key_length) *key_length = hash_length(ver->hash_alg); + if (key_length) + *key_length = hash_length(ver->hash_alg); return ver->session_key; } @@ -809,8 +844,8 @@ size_t srp_verifier_get_session_key_length(struct SRPVerifier *ver) } /* user_M must be exactly SHA512_DIGEST_LENGTH bytes in size */ -void srp_verifier_verify_session( - struct SRPVerifier *ver, const unsigned char *user_M, unsigned char **bytes_HAMK) +void srp_verifier_verify_session(struct SRPVerifier *ver, const unsigned char *user_M, + unsigned char **bytes_HAMK) { if (memcmp(ver->M, user_M, hash_length(ver->hash_alg)) == 0) { ver->authenticated = 1; @@ -822,15 +857,16 @@ void srp_verifier_verify_session( /*******************************************************************************/ struct SRPUser *srp_user_new(SRP_HashAlgorithm alg, SRP_NGType ng_type, - const char *username, const char *username_for_verifier, - const unsigned char *bytes_password, size_t len_password, const char *n_hex, - const char *g_hex) + const char *username, const char *username_for_verifier, + const unsigned char *bytes_password, size_t len_password, + const char *n_hex, const char *g_hex) { struct SRPUser *usr = (struct SRPUser *)srp_alloc(sizeof(struct SRPUser)); size_t ulen = strlen(username) + 1; size_t uvlen = strlen(username_for_verifier) + 1; - if (!usr) goto err_exit; + if (!usr) + goto err_exit; if (init_random() != SRP_OK) /* Only happens once */ goto err_exit; @@ -842,14 +878,16 @@ struct SRPUser *srp_user_new(SRP_HashAlgorithm alg, SRP_NGType ng_type, mpz_init(usr->A); mpz_init(usr->S); - if (!usr->ng) goto err_exit; + if (!usr->ng) + goto err_exit; usr->username = (char *)srp_alloc(ulen); usr->username_verifier = (char *)srp_alloc(uvlen); usr->password = (unsigned char *)srp_alloc(len_password); usr->password_len = len_password; - if (!usr->username || !usr->password || !usr->username_verifier) goto err_exit; + if (!usr->username || !usr->password || !usr->username_verifier) + goto err_exit; memcpy(usr->username, username, ulen); memcpy(usr->username_verifier, username_for_verifier, uvlen); @@ -894,7 +932,8 @@ void srp_user_delete(struct SRPUser *usr) srp_free(usr->username_verifier); srp_free(usr->password); - if (usr->bytes_A) srp_free(usr->bytes_A); + if (usr->bytes_A) + srp_free(usr->bytes_A); memset(usr, 0, sizeof(*usr)); srp_free(usr); @@ -913,7 +952,8 @@ const char *srp_user_get_username(struct SRPUser *usr) const unsigned char *srp_user_get_session_key(struct SRPUser *usr, size_t *key_length) { - if (key_length) *key_length = hash_length(usr->hash_alg); + if (key_length) + *key_length = hash_length(usr->hash_alg); return usr->session_key; } @@ -932,7 +972,8 @@ SRP_Result srp_user_start_authentication(struct SRPUser *usr, char **username, if (bytes_a) { mpz_from_bin(bytes_a, len_a, usr->a); } else { - if (!mpz_fill_random(usr->a)) goto error_and_exit; + if (!mpz_fill_random(usr->a)) + goto error_and_exit; } mpz_powm(usr->A, usr->ng->g, usr->a, usr->ng->N); @@ -940,12 +981,14 @@ SRP_Result srp_user_start_authentication(struct SRPUser *usr, char **username, *len_A = mpz_num_bytes(usr->A); *bytes_A = (unsigned char *)srp_alloc(*len_A); - if (!*bytes_A) goto error_and_exit; + if (!*bytes_A) + goto error_and_exit; mpz_to_bin(usr->A, *bytes_A); usr->bytes_A = *bytes_A; - if (username) *username = usr->username; + if (username) + *username = usr->username; return SRP_OK; @@ -977,12 +1020,13 @@ void srp_user_process_challenge(struct SRPUser *usr, *len_M = 0; *bytes_M = 0; - if (!H_nn(u, usr->hash_alg, usr->ng->N, usr->A, B)) goto cleanup_and_exit; + if (!H_nn(u, usr->hash_alg, usr->ng->N, usr->A, B)) + goto cleanup_and_exit; srp_dbg_num(u, "Client calculated u: "); if (!calculate_x(x, usr->hash_alg, bytes_s, len_s, usr->username_verifier, - usr->password, usr->password_len)) + usr->password, usr->password_len)) goto cleanup_and_exit; srp_dbg_num(x, "Client calculated x: "); @@ -1006,19 +1050,23 @@ void srp_user_process_challenge(struct SRPUser *usr, mpz_powm(usr->S, tmp1, tmp2, usr->ng->N); // clang-format on - if (!hash_num(usr->hash_alg, usr->S, usr->session_key)) goto cleanup_and_exit; + if (!hash_num(usr->hash_alg, usr->S, usr->session_key)) + goto cleanup_and_exit; - if (!calculate_M(usr->hash_alg, usr->ng, usr->M, usr->username, bytes_s, len_s, - usr->A, B, usr->session_key)) + if (!calculate_M(usr->hash_alg, usr->ng, usr->M, usr->username, bytes_s, + len_s, usr->A, B, usr->session_key)) goto cleanup_and_exit; - if (!calculate_H_AMK(usr->hash_alg, usr->H_AMK, usr->A, usr->M, usr->session_key)) + if (!calculate_H_AMK(usr->hash_alg, usr->H_AMK, usr->A, usr->M, + usr->session_key)) goto cleanup_and_exit; *bytes_M = usr->M; - if (len_M) *len_M = hash_length(usr->hash_alg); + if (len_M) + *len_M = hash_length(usr->hash_alg); } else { *bytes_M = NULL; - if (len_M) *len_M = 0; + if (len_M) + *len_M = 0; } cleanup_and_exit: diff --git a/src/util/srp.h b/src/util/srp.h index cf2bdec50..be795c2f8 100644 --- a/src/util/srp.h +++ b/src/util/srp.h @@ -58,7 +58,8 @@ struct SRPVerifier; struct SRPUser; -typedef enum { +typedef enum +{ SRP_NG_1024, SRP_NG_2048, SRP_NG_4096, @@ -66,7 +67,8 @@ typedef enum { SRP_NG_CUSTOM } SRP_NGType; -typedef enum { +typedef enum +{ /*SRP_SHA1,*/ /*SRP_SHA224,*/ SRP_SHA256, @@ -74,7 +76,8 @@ typedef enum { SRP_SHA512*/ } SRP_HashAlgorithm; -typedef enum { +typedef enum +{ SRP_ERR, SRP_OK, } SRP_Result; @@ -141,23 +144,23 @@ const char *srp_verifier_get_username(struct SRPVerifier *ver); /* key_length may be null */ const unsigned char *srp_verifier_get_session_key( - struct SRPVerifier *ver, size_t *key_length); + struct SRPVerifier *ver, size_t *key_length); size_t srp_verifier_get_session_key_length(struct SRPVerifier *ver); /* Verifies session, on success, it writes bytes_HAMK. * user_M must be exactly srp_verifier_get_session_key_length() bytes in size */ -void srp_verifier_verify_session( - struct SRPVerifier *ver, const unsigned char *user_M, unsigned char **bytes_HAMK); +void srp_verifier_verify_session(struct SRPVerifier *ver, const unsigned char *user_M, + unsigned char **bytes_HAMK); /*******************************************************************************/ /* The n_hex and g_hex parameters should be 0 unless SRP_NG_CUSTOM is used for ng_type */ struct SRPUser *srp_user_new(SRP_HashAlgorithm alg, SRP_NGType ng_type, - const char *username, const char *username_for_verifier, - const unsigned char *bytes_password, size_t len_password, const char *n_hex, - const char *g_hex); + const char *username, const char *username_for_verifier, + const unsigned char *bytes_password, size_t len_password, + const char *n_hex, const char *g_hex); void srp_user_delete(struct SRPUser *usr); diff --git a/src/util/strfnd.h b/src/util/strfnd.h index 96cf1b458..92fbbaf07 100644 --- a/src/util/strfnd.h +++ b/src/util/strfnd.h @@ -21,14 +21,19 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <string> -template <typename T> -class BasicStrfnd { +template <typename T> class BasicStrfnd +{ typedef std::basic_string<T> String; String str; size_t pos; + public: BasicStrfnd(const String &s) : str(s), pos(0) {} - void start(const String &s) { str = s; pos = 0; } + void start(const String &s) + { + str = s; + pos = 0; + } size_t where() { return pos; } void to(size_t i) { pos = i; } bool at_end() { return pos >= str.size(); } @@ -48,8 +53,9 @@ public: return ret; } - // Returns substr up to the next occurence of sep that isn't escaped with esc ('\\') - String next_esc(const String &sep, T esc=static_cast<T>('\\')) + // Returns substr up to the next occurence of sep that isn't escaped with esc + // ('\\') + String next_esc(const String &sep, T esc = static_cast<T>('\\')) { if (pos >= str.size()) return String(); diff --git a/src/util/string.cpp b/src/util/string.cpp index 6e1db798c..347bb12b1 100644 --- a/src/util/string.cpp +++ b/src/util/string.cpp @@ -32,15 +32,16 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <map> #ifndef _WIN32 - #include <iconv.h> +#include <iconv.h> #else - #define _WIN32_WINNT 0x0501 - #include <windows.h> +#define _WIN32_WINNT 0x0501 +#include <windows.h> #endif -#if defined(_ICONV_H_) && (defined(__FreeBSD__) || defined(__NetBSD__) || \ - defined(__OpenBSD__) || defined(__DragonFly__)) - #define BSD_ICONV_USED +#if defined(_ICONV_H_) && \ + (defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \ + defined(__DragonFly__)) +#define BSD_ICONV_USED #endif static bool parseHexColorString(const std::string &value, video::SColor &color, @@ -49,8 +50,8 @@ static bool parseNamedColorString(const std::string &value, video::SColor &color #ifndef _WIN32 -bool convert(const char *to, const char *from, char *outbuf, - size_t outbuf_size, char *inbuf, size_t inbuf_size) +bool convert(const char *to, const char *from, char *outbuf, size_t outbuf_size, + char *inbuf, size_t inbuf_size) { iconv_t cd = iconv_open(to, from); @@ -98,13 +99,14 @@ std::wstring utf8_to_wide(const std::string &input) memset(outbuf, 0, outbuf_size); #ifdef __ANDROID__ - // Android need manual caring to support the full character set possible with wchar_t + // Android need manual caring to support the full character set possible with + // wchar_t SANITY_CHECK(sizeof(wchar_t) == 4); #endif if (!convert(DEFAULT_ENCODING, "UTF-8", outbuf, outbuf_size, inbuf, inbuf_size)) { infostream << "Couldn't convert UTF-8 string 0x" << hex_encode(input) - << " into wstring" << std::endl; + << " into wstring" << std::endl; delete[] inbuf; delete[] outbuf; return L"<invalid UTF-8 string>"; @@ -129,8 +131,9 @@ std::string wide_to_utf8(const std::wstring &input) memset(outbuf, 0, outbuf_size); if (!convert("UTF-8", DEFAULT_ENCODING, outbuf, outbuf_size, inbuf, inbuf_size)) { - infostream << "Couldn't convert wstring 0x" << hex_encode(inbuf, inbuf_size) - << " into UTF-8 string" << std::endl; + infostream << "Couldn't convert wstring 0x" + << hex_encode(inbuf, inbuf_size) << " into UTF-8 string" + << std::endl; delete[] inbuf; delete[] outbuf; return "<invalid wstring>"; @@ -150,8 +153,7 @@ std::wstring utf8_to_wide(const std::string &input) size_t outbuf_size = input.size() + 1; wchar_t *outbuf = new wchar_t[outbuf_size]; memset(outbuf, 0, outbuf_size * sizeof(wchar_t)); - MultiByteToWideChar(CP_UTF8, 0, input.c_str(), input.size(), - outbuf, outbuf_size); + MultiByteToWideChar(CP_UTF8, 0, input.c_str(), input.size(), outbuf, outbuf_size); std::wstring out(outbuf); delete[] outbuf; return out; @@ -162,8 +164,8 @@ std::string wide_to_utf8(const std::wstring &input) size_t outbuf_size = (input.size() + 1) * 6; char *outbuf = new char[outbuf_size]; memset(outbuf, 0, outbuf_size); - WideCharToMultiByte(CP_UTF8, 0, input.c_str(), input.size(), - outbuf, outbuf_size, NULL, NULL); + WideCharToMultiByte(CP_UTF8, 0, input.c_str(), input.size(), outbuf, outbuf_size, + NULL, NULL); std::string out(outbuf); delete[] outbuf; return out; @@ -189,12 +191,12 @@ wchar_t *narrow_to_wide_c(const char *str) { wchar_t *nstr = nullptr; #if defined(_WIN32) - int nResult = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR) str, -1, 0, 0); + int nResult = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)str, -1, 0, 0); if (nResult == 0) { - errorstream<<"gettext: MultiByteToWideChar returned null"<<std::endl; + errorstream << "gettext: MultiByteToWideChar returned null" << std::endl; } else { nstr = new wchar_t[nResult]; - MultiByteToWideChar(CP_UTF8, 0, (LPCSTR) str, -1, (WCHAR *) nstr, nResult); + MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)str, -1, (WCHAR *)nstr, nResult); } #else size_t len = strlen(str); @@ -208,7 +210,8 @@ wchar_t *narrow_to_wide_c(const char *str) return nstr; } -std::wstring narrow_to_wide(const std::string &mbs) { +std::wstring narrow_to_wide(const std::string &mbs) +{ #ifdef __ANDROID__ return utf8_to_wide(mbs); #else @@ -222,14 +225,13 @@ std::wstring narrow_to_wide(const std::string &mbs) { #endif } - std::string wide_to_narrow(const std::wstring &wcs) { #ifdef __ANDROID__ return wide_to_utf8(wcs); #else size_t mbl = wcs.size() * 4; - SharedBuffer<char> mbs(mbl+1); + SharedBuffer<char> mbs(mbl + 1); size_t len = wcstombs(*mbs, wcs.c_str(), mbl); if (len == (size_t)(-1)) return "Character conversion failed!"; @@ -239,7 +241,6 @@ std::string wide_to_narrow(const std::wstring &wcs) #endif } - std::string urlencode(const std::string &str) { // Encodes non-unreserved URI characters by a percent sign @@ -250,9 +251,8 @@ std::string urlencode(const std::string &str) if (isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') { oss << c; } else { - oss << "%" - << url_hex_chars[(c & 0xf0) >> 4] - << url_hex_chars[c & 0x0f]; + oss << "%" << url_hex_chars[(c & 0xf0) >> 4] + << url_hex_chars[c & 0x0f]; } } return oss.str(); @@ -264,10 +264,9 @@ std::string urldecode(const std::string &str) std::ostringstream oss(std::ios::binary); for (u32 i = 0; i < str.size(); i++) { unsigned char highvalue, lowvalue; - if (str[i] == '%' && - hex_digit_decode(str[i+1], highvalue) && - hex_digit_decode(str[i+2], lowvalue)) { - oss << (char) ((highvalue << 4) | lowvalue); + if (str[i] == '%' && hex_digit_decode(str[i + 1], highvalue) && + hex_digit_decode(str[i + 2], lowvalue)) { + oss << (char)((highvalue << 4) | lowvalue); i += 2; } else { oss << str[i]; @@ -335,7 +334,7 @@ std::string writeFlagString(u32 flags, const FlagDesc *flagdesc, u32 flagmask) size_t mystrlcpy(char *dst, const char *src, size_t size) { - size_t srclen = strlen(src) + 1; + size_t srclen = strlen(src) + 1; size_t copylen = MYMIN(srclen, size); if (copylen > 0) { @@ -407,7 +406,7 @@ bool parseColorString(const std::string &value, video::SColor &color, bool quiet static bool parseHexColorString(const std::string &value, video::SColor &color, unsigned char default_alpha) { - unsigned char components[] = { 0x00, 0x00, 0x00, default_alpha }; // R,G,B,A + unsigned char components[] = {0x00, 0x00, 0x00, default_alpha}; // R,G,B,A if (value[0] != '#') return false; @@ -436,12 +435,12 @@ static bool parseHexColorString(const std::string &value, video::SColor &color, } else { unsigned char d1, d2; if (!hex_digit_decode(value[pos], d1) || - !hex_digit_decode(value[pos+1], d2)) { + !hex_digit_decode(value[pos + 1], d2)) { success = false; break; } components[cc] = (d1 & 0xf) << 4 | (d2 & 0xf); - pos++; // skip the second digit -- it's already used + pos++; // skip the second digit -- it's already used } } @@ -455,161 +454,161 @@ static bool parseHexColorString(const std::string &value, video::SColor &color, return success; } -struct ColorContainer { +struct ColorContainer +{ ColorContainer(); std::map<const std::string, u32> colors; }; ColorContainer::ColorContainer() { - colors["aliceblue"] = 0xf0f8ff; - colors["antiquewhite"] = 0xfaebd7; - colors["aqua"] = 0x00ffff; - colors["aquamarine"] = 0x7fffd4; - colors["azure"] = 0xf0ffff; - colors["beige"] = 0xf5f5dc; - colors["bisque"] = 0xffe4c4; - colors["black"] = 00000000; - colors["blanchedalmond"] = 0xffebcd; - colors["blue"] = 0x0000ff; - colors["blueviolet"] = 0x8a2be2; - colors["brown"] = 0xa52a2a; - colors["burlywood"] = 0xdeb887; - colors["cadetblue"] = 0x5f9ea0; - colors["chartreuse"] = 0x7fff00; - colors["chocolate"] = 0xd2691e; - colors["coral"] = 0xff7f50; - colors["cornflowerblue"] = 0x6495ed; - colors["cornsilk"] = 0xfff8dc; - colors["crimson"] = 0xdc143c; - colors["cyan"] = 0x00ffff; - colors["darkblue"] = 0x00008b; - colors["darkcyan"] = 0x008b8b; - colors["darkgoldenrod"] = 0xb8860b; - colors["darkgray"] = 0xa9a9a9; - colors["darkgreen"] = 0x006400; - colors["darkgrey"] = 0xa9a9a9; - colors["darkkhaki"] = 0xbdb76b; - colors["darkmagenta"] = 0x8b008b; - colors["darkolivegreen"] = 0x556b2f; - colors["darkorange"] = 0xff8c00; - colors["darkorchid"] = 0x9932cc; - colors["darkred"] = 0x8b0000; - colors["darksalmon"] = 0xe9967a; - colors["darkseagreen"] = 0x8fbc8f; - colors["darkslateblue"] = 0x483d8b; - colors["darkslategray"] = 0x2f4f4f; - colors["darkslategrey"] = 0x2f4f4f; - colors["darkturquoise"] = 0x00ced1; - colors["darkviolet"] = 0x9400d3; - colors["deeppink"] = 0xff1493; - colors["deepskyblue"] = 0x00bfff; - colors["dimgray"] = 0x696969; - colors["dimgrey"] = 0x696969; - colors["dodgerblue"] = 0x1e90ff; - colors["firebrick"] = 0xb22222; - colors["floralwhite"] = 0xfffaf0; - colors["forestgreen"] = 0x228b22; - colors["fuchsia"] = 0xff00ff; - colors["gainsboro"] = 0xdcdcdc; - colors["ghostwhite"] = 0xf8f8ff; - colors["gold"] = 0xffd700; - colors["goldenrod"] = 0xdaa520; - colors["gray"] = 0x808080; - colors["green"] = 0x008000; - colors["greenyellow"] = 0xadff2f; - colors["grey"] = 0x808080; - colors["honeydew"] = 0xf0fff0; - colors["hotpink"] = 0xff69b4; - colors["indianred"] = 0xcd5c5c; - colors["indigo"] = 0x4b0082; - colors["ivory"] = 0xfffff0; - colors["khaki"] = 0xf0e68c; - colors["lavender"] = 0xe6e6fa; - colors["lavenderblush"] = 0xfff0f5; - colors["lawngreen"] = 0x7cfc00; - colors["lemonchiffon"] = 0xfffacd; - colors["lightblue"] = 0xadd8e6; - colors["lightcoral"] = 0xf08080; - colors["lightcyan"] = 0xe0ffff; - colors["lightgoldenrodyellow"] = 0xfafad2; - colors["lightgray"] = 0xd3d3d3; - colors["lightgreen"] = 0x90ee90; - colors["lightgrey"] = 0xd3d3d3; - colors["lightpink"] = 0xffb6c1; - colors["lightsalmon"] = 0xffa07a; - colors["lightseagreen"] = 0x20b2aa; - colors["lightskyblue"] = 0x87cefa; - colors["lightslategray"] = 0x778899; - colors["lightslategrey"] = 0x778899; - colors["lightsteelblue"] = 0xb0c4de; - colors["lightyellow"] = 0xffffe0; - colors["lime"] = 0x00ff00; - colors["limegreen"] = 0x32cd32; - colors["linen"] = 0xfaf0e6; - colors["magenta"] = 0xff00ff; - colors["maroon"] = 0x800000; - colors["mediumaquamarine"] = 0x66cdaa; - colors["mediumblue"] = 0x0000cd; - colors["mediumorchid"] = 0xba55d3; - colors["mediumpurple"] = 0x9370db; - colors["mediumseagreen"] = 0x3cb371; - colors["mediumslateblue"] = 0x7b68ee; - colors["mediumspringgreen"] = 0x00fa9a; - colors["mediumturquoise"] = 0x48d1cc; - colors["mediumvioletred"] = 0xc71585; - colors["midnightblue"] = 0x191970; - colors["mintcream"] = 0xf5fffa; - colors["mistyrose"] = 0xffe4e1; - colors["moccasin"] = 0xffe4b5; - colors["navajowhite"] = 0xffdead; - colors["navy"] = 0x000080; - colors["oldlace"] = 0xfdf5e6; - colors["olive"] = 0x808000; - colors["olivedrab"] = 0x6b8e23; - colors["orange"] = 0xffa500; - colors["orangered"] = 0xff4500; - colors["orchid"] = 0xda70d6; - colors["palegoldenrod"] = 0xeee8aa; - colors["palegreen"] = 0x98fb98; - colors["paleturquoise"] = 0xafeeee; - colors["palevioletred"] = 0xdb7093; - colors["papayawhip"] = 0xffefd5; - colors["peachpuff"] = 0xffdab9; - colors["peru"] = 0xcd853f; - colors["pink"] = 0xffc0cb; - colors["plum"] = 0xdda0dd; - colors["powderblue"] = 0xb0e0e6; - colors["purple"] = 0x800080; - colors["red"] = 0xff0000; - colors["rosybrown"] = 0xbc8f8f; - colors["royalblue"] = 0x4169e1; - colors["saddlebrown"] = 0x8b4513; - colors["salmon"] = 0xfa8072; - colors["sandybrown"] = 0xf4a460; - colors["seagreen"] = 0x2e8b57; - colors["seashell"] = 0xfff5ee; - colors["sienna"] = 0xa0522d; - colors["silver"] = 0xc0c0c0; - colors["skyblue"] = 0x87ceeb; - colors["slateblue"] = 0x6a5acd; - colors["slategray"] = 0x708090; - colors["slategrey"] = 0x708090; - colors["snow"] = 0xfffafa; - colors["springgreen"] = 0x00ff7f; - colors["steelblue"] = 0x4682b4; - colors["tan"] = 0xd2b48c; - colors["teal"] = 0x008080; - colors["thistle"] = 0xd8bfd8; - colors["tomato"] = 0xff6347; - colors["turquoise"] = 0x40e0d0; - colors["violet"] = 0xee82ee; - colors["wheat"] = 0xf5deb3; - colors["white"] = 0xffffff; - colors["whitesmoke"] = 0xf5f5f5; - colors["yellow"] = 0xffff00; - colors["yellowgreen"] = 0x9acd32; - + colors["aliceblue"] = 0xf0f8ff; + colors["antiquewhite"] = 0xfaebd7; + colors["aqua"] = 0x00ffff; + colors["aquamarine"] = 0x7fffd4; + colors["azure"] = 0xf0ffff; + colors["beige"] = 0xf5f5dc; + colors["bisque"] = 0xffe4c4; + colors["black"] = 00000000; + colors["blanchedalmond"] = 0xffebcd; + colors["blue"] = 0x0000ff; + colors["blueviolet"] = 0x8a2be2; + colors["brown"] = 0xa52a2a; + colors["burlywood"] = 0xdeb887; + colors["cadetblue"] = 0x5f9ea0; + colors["chartreuse"] = 0x7fff00; + colors["chocolate"] = 0xd2691e; + colors["coral"] = 0xff7f50; + colors["cornflowerblue"] = 0x6495ed; + colors["cornsilk"] = 0xfff8dc; + colors["crimson"] = 0xdc143c; + colors["cyan"] = 0x00ffff; + colors["darkblue"] = 0x00008b; + colors["darkcyan"] = 0x008b8b; + colors["darkgoldenrod"] = 0xb8860b; + colors["darkgray"] = 0xa9a9a9; + colors["darkgreen"] = 0x006400; + colors["darkgrey"] = 0xa9a9a9; + colors["darkkhaki"] = 0xbdb76b; + colors["darkmagenta"] = 0x8b008b; + colors["darkolivegreen"] = 0x556b2f; + colors["darkorange"] = 0xff8c00; + colors["darkorchid"] = 0x9932cc; + colors["darkred"] = 0x8b0000; + colors["darksalmon"] = 0xe9967a; + colors["darkseagreen"] = 0x8fbc8f; + colors["darkslateblue"] = 0x483d8b; + colors["darkslategray"] = 0x2f4f4f; + colors["darkslategrey"] = 0x2f4f4f; + colors["darkturquoise"] = 0x00ced1; + colors["darkviolet"] = 0x9400d3; + colors["deeppink"] = 0xff1493; + colors["deepskyblue"] = 0x00bfff; + colors["dimgray"] = 0x696969; + colors["dimgrey"] = 0x696969; + colors["dodgerblue"] = 0x1e90ff; + colors["firebrick"] = 0xb22222; + colors["floralwhite"] = 0xfffaf0; + colors["forestgreen"] = 0x228b22; + colors["fuchsia"] = 0xff00ff; + colors["gainsboro"] = 0xdcdcdc; + colors["ghostwhite"] = 0xf8f8ff; + colors["gold"] = 0xffd700; + colors["goldenrod"] = 0xdaa520; + colors["gray"] = 0x808080; + colors["green"] = 0x008000; + colors["greenyellow"] = 0xadff2f; + colors["grey"] = 0x808080; + colors["honeydew"] = 0xf0fff0; + colors["hotpink"] = 0xff69b4; + colors["indianred"] = 0xcd5c5c; + colors["indigo"] = 0x4b0082; + colors["ivory"] = 0xfffff0; + colors["khaki"] = 0xf0e68c; + colors["lavender"] = 0xe6e6fa; + colors["lavenderblush"] = 0xfff0f5; + colors["lawngreen"] = 0x7cfc00; + colors["lemonchiffon"] = 0xfffacd; + colors["lightblue"] = 0xadd8e6; + colors["lightcoral"] = 0xf08080; + colors["lightcyan"] = 0xe0ffff; + colors["lightgoldenrodyellow"] = 0xfafad2; + colors["lightgray"] = 0xd3d3d3; + colors["lightgreen"] = 0x90ee90; + colors["lightgrey"] = 0xd3d3d3; + colors["lightpink"] = 0xffb6c1; + colors["lightsalmon"] = 0xffa07a; + colors["lightseagreen"] = 0x20b2aa; + colors["lightskyblue"] = 0x87cefa; + colors["lightslategray"] = 0x778899; + colors["lightslategrey"] = 0x778899; + colors["lightsteelblue"] = 0xb0c4de; + colors["lightyellow"] = 0xffffe0; + colors["lime"] = 0x00ff00; + colors["limegreen"] = 0x32cd32; + colors["linen"] = 0xfaf0e6; + colors["magenta"] = 0xff00ff; + colors["maroon"] = 0x800000; + colors["mediumaquamarine"] = 0x66cdaa; + colors["mediumblue"] = 0x0000cd; + colors["mediumorchid"] = 0xba55d3; + colors["mediumpurple"] = 0x9370db; + colors["mediumseagreen"] = 0x3cb371; + colors["mediumslateblue"] = 0x7b68ee; + colors["mediumspringgreen"] = 0x00fa9a; + colors["mediumturquoise"] = 0x48d1cc; + colors["mediumvioletred"] = 0xc71585; + colors["midnightblue"] = 0x191970; + colors["mintcream"] = 0xf5fffa; + colors["mistyrose"] = 0xffe4e1; + colors["moccasin"] = 0xffe4b5; + colors["navajowhite"] = 0xffdead; + colors["navy"] = 0x000080; + colors["oldlace"] = 0xfdf5e6; + colors["olive"] = 0x808000; + colors["olivedrab"] = 0x6b8e23; + colors["orange"] = 0xffa500; + colors["orangered"] = 0xff4500; + colors["orchid"] = 0xda70d6; + colors["palegoldenrod"] = 0xeee8aa; + colors["palegreen"] = 0x98fb98; + colors["paleturquoise"] = 0xafeeee; + colors["palevioletred"] = 0xdb7093; + colors["papayawhip"] = 0xffefd5; + colors["peachpuff"] = 0xffdab9; + colors["peru"] = 0xcd853f; + colors["pink"] = 0xffc0cb; + colors["plum"] = 0xdda0dd; + colors["powderblue"] = 0xb0e0e6; + colors["purple"] = 0x800080; + colors["red"] = 0xff0000; + colors["rosybrown"] = 0xbc8f8f; + colors["royalblue"] = 0x4169e1; + colors["saddlebrown"] = 0x8b4513; + colors["salmon"] = 0xfa8072; + colors["sandybrown"] = 0xf4a460; + colors["seagreen"] = 0x2e8b57; + colors["seashell"] = 0xfff5ee; + colors["sienna"] = 0xa0522d; + colors["silver"] = 0xc0c0c0; + colors["skyblue"] = 0x87ceeb; + colors["slateblue"] = 0x6a5acd; + colors["slategray"] = 0x708090; + colors["slategrey"] = 0x708090; + colors["snow"] = 0xfffafa; + colors["springgreen"] = 0x00ff7f; + colors["steelblue"] = 0x4682b4; + colors["tan"] = 0xd2b48c; + colors["teal"] = 0x008080; + colors["thistle"] = 0xd8bfd8; + colors["tomato"] = 0xff6347; + colors["turquoise"] = 0x40e0d0; + colors["violet"] = 0xee82ee; + colors["wheat"] = 0xf5deb3; + colors["white"] = 0xffffff; + colors["whitesmoke"] = 0xf5f5f5; + colors["yellow"] = 0xffff00; + colors["yellowgreen"] = 0x9acd32; } static const ColorContainer named_colors; @@ -653,12 +652,12 @@ static bool parseNamedColorString(const std::string &value, video::SColor &color return false; unsigned char d1, d2; - if (!hex_digit_decode(alpha_string.at(0), d1) - || !hex_digit_decode(alpha_string.at(1), d2)) + if (!hex_digit_decode(alpha_string.at(0), d1) || + !hex_digit_decode(alpha_string.at(1), d2)) return false; color_temp |= ((d1 & 0xf) << 4 | (d2 & 0xf)) << 24; } else { - color_temp |= 0xff << 24; // Fully opaque + color_temp |= 0xff << 24; // Fully opaque } color = video::SColor(color_temp); @@ -686,15 +685,14 @@ void str_replace(std::string &str, char from, char to) * For instance, suppose we have a string such as "@1 Wool" with the argument "White" * The string will be sent as "\x1bT\x1bF\x1bTWhite\x1bE\x1bE Wool\x1bE" * To translate this string, we extract what is inside \x1bT/\x1bE tags. - * When we notice the \x1bF tag, we recursively extract what is there up to the \x1bE end tag, - * translating it as well. - * We get the argument "White", translated, and create a template string with "@1" instead of it. - * We finally get the template "@1 Wool" that was used in the beginning, which we translate - * before filling it again. + * When we notice the \x1bF tag, we recursively extract what is there up to the \x1bE end + * tag, translating it as well. We get the argument "White", translated, and create a + * template string with "@1" instead of it. We finally get the template "@1 Wool" that was + * used in the beginning, which we translate before filling it again. */ -void translate_all(const std::wstring &s, size_t &i, - Translations *translations, std::wstring &res); +void translate_all(const std::wstring &s, size_t &i, Translations *translations, + std::wstring &res); void translate_string(const std::wstring &s, Translations *translations, const std::wstring &textdomain, size_t &i, std::wstring &res) @@ -743,14 +741,18 @@ void translate_string(const std::wstring &s, Translations *translations, // The escape sequence is now reconstructed. std::vector<std::wstring> parts = split(escape_sequence, L'@'); if (parts[0] == L"E") { - // "End of translation" escape sequence. We are done locating the string to translate. + // "End of translation" escape sequence. We are done locating the + // string to translate. break; } else if (parts[0] == L"F") { // "Start of argument" escape sequence. - // Recursively translate the argument, and add it to the argument list. - // Add an "@n" instead of the argument to the template to translate. + // Recursively translate the argument, and add it to the argument + // list. Add an "@n" instead of the argument to the template to + // translate. if (arg_number >= 10) { - errorstream << "Ignoring too many arguments to translation" << std::endl; + errorstream << "Ignoring too many arguments to " + "translation" + << std::endl; std::wstring arg; translate_all(s, i, translations, arg); args.push_back(arg); @@ -763,17 +765,19 @@ void translate_string(const std::wstring &s, Translations *translations, translate_all(s, i, translations, arg); args.push_back(arg); } else { - // This is an escape sequence *inside* the template string to translate itself. - // This should not happen, show an error message. - errorstream << "Ignoring escape sequence '" << wide_to_narrow(escape_sequence) << "' in translation" << std::endl; + // This is an escape sequence *inside* the template string to + // translate itself. This should not happen, show an error + // message. + errorstream << "Ignoring escape sequence '" + << wide_to_narrow(escape_sequence) + << "' in translation" << std::endl; } } std::wstring toutput; // Translate the template. if (translations != nullptr) - toutput = translations->getTranslation( - textdomain, output.str()); + toutput = translations->getTranslation(textdomain, output.str()); else toutput = output.str(); @@ -796,21 +800,24 @@ void translate_string(const std::wstring &s, Translations *translations, continue; } - // Here we have an argument; get its index and add the translated argument to the output. + // Here we have an argument; get its index and add the translated argument + // to the output. int arg_index = toutput[j] - L'1'; ++j; if (0 <= arg_index && (size_t)arg_index < args.size()) { result << args[arg_index]; } else { // This is not allowed: show an error message - errorstream << "Ignoring out-of-bounds argument escape sequence in translation" << std::endl; + errorstream << "Ignoring out-of-bounds argument escape sequence " + "in translation" + << std::endl; } } res = result.str(); } -void translate_all(const std::wstring &s, size_t &i, - Translations *translations, std::wstring &res) +void translate_all(const std::wstring &s, size_t &i, Translations *translations, + std::wstring &res) { std::wostringstream output; while (i < s.length()) { diff --git a/src/util/string.h b/src/util/string.h index 185fb55e2..ee7b0f17f 100644 --- a/src/util/string.h +++ b/src/util/string.h @@ -37,29 +37,26 @@ class Translations; #define TOSTRING(x) STRINGIFY(x) // Checks whether a value is an ASCII printable character -#define IS_ASCII_PRINTABLE_CHAR(x) \ - (((unsigned int)(x) >= 0x20) && \ - ( (unsigned int)(x) <= 0x7e)) +#define IS_ASCII_PRINTABLE_CHAR(x) \ + (((unsigned int)(x) >= 0x20) && ((unsigned int)(x) <= 0x7e)) // Checks whether a byte is an inner byte for an utf-8 multibyte sequence -#define IS_UTF8_MULTB_INNER(x) \ - (((unsigned char)(x) >= 0x80) && \ - ( (unsigned char)(x) <= 0xbf)) +#define IS_UTF8_MULTB_INNER(x) \ + (((unsigned char)(x) >= 0x80) && ((unsigned char)(x) <= 0xbf)) // Checks whether a byte is a start byte for an utf-8 multibyte sequence -#define IS_UTF8_MULTB_START(x) \ - (((unsigned char)(x) >= 0xc2) && \ - ( (unsigned char)(x) <= 0xf4)) +#define IS_UTF8_MULTB_START(x) \ + (((unsigned char)(x) >= 0xc2) && ((unsigned char)(x) <= 0xf4)) // Given a start byte x for an utf-8 multibyte sequence // it gives the length of the whole sequence in bytes. -#define UTF8_MULTB_START_LEN(x) \ - (((unsigned char)(x) < 0xe0) ? 2 : \ - (((unsigned char)(x) < 0xf0) ? 3 : 4)) +#define UTF8_MULTB_START_LEN(x) \ + (((unsigned char)(x) < 0xe0) ? 2 : (((unsigned char)(x) < 0xf0) ? 3 : 4)) typedef std::unordered_map<std::string, std::string> StringMap; -struct FlagDesc { +struct FlagDesc +{ const char *name; u32 flag; }; @@ -91,7 +88,6 @@ u64 read_seed(const char *str); bool parseColorString(const std::string &value, video::SColor &color, bool quiet, unsigned char default_alpha = 0xff); - /** * Returns a copy of \p str with spaces inserted at the right hand side to ensure * that the string is \p len characters in length. If \p str is <= \p len then the @@ -116,8 +112,7 @@ inline std::string padStringRight(std::string str, size_t len) * * @return If no end could be removed then "" is returned. */ -inline std::string removeStringEnd(const std::string &str, - const char *ends[]) +inline std::string removeStringEnd(const std::string &str, const char *ends[]) { const char **p = ends; @@ -132,7 +127,6 @@ inline std::string removeStringEnd(const std::string &str, return ""; } - /** * Check two strings for equivalence. If \p case_insensitive is true * then the case of the strings is ignored (default is false). @@ -143,8 +137,7 @@ inline std::string removeStringEnd(const std::string &str, * @return true if the strings match */ template <typename T> -inline bool str_equal(const std::basic_string<T> &s1, - const std::basic_string<T> &s2, +inline bool str_equal(const std::basic_string<T> &s1, const std::basic_string<T> &s2, bool case_insensitive = false) { if (!case_insensitive) @@ -154,13 +147,12 @@ inline bool str_equal(const std::basic_string<T> &s1, return false; for (size_t i = 0; i < s1.size(); ++i) - if(tolower(s1[i]) != tolower(s2[i])) + if (tolower(s1[i]) != tolower(s2[i])) return false; return true; } - /** * Check whether \p str begins with the string prefix. If \p case_insensitive * is true then the check is case insensitve (default is false; i.e. case is @@ -173,8 +165,7 @@ inline bool str_equal(const std::basic_string<T> &s1, */ template <typename T> inline bool str_starts_with(const std::basic_string<T> &str, - const std::basic_string<T> &prefix, - bool case_insensitive = false) + const std::basic_string<T> &prefix, bool case_insensitive = false) { if (str.size() < prefix.size()) return false; @@ -199,15 +190,12 @@ inline bool str_starts_with(const std::basic_string<T> &str, * @return true if the str begins with prefix */ template <typename T> -inline bool str_starts_with(const std::basic_string<T> &str, - const T *prefix, +inline bool str_starts_with(const std::basic_string<T> &str, const T *prefix, bool case_insensitive = false) { - return str_starts_with(str, std::basic_string<T>(prefix), - case_insensitive); + return str_starts_with(str, std::basic_string<T>(prefix), case_insensitive); } - /** * Check whether \p str ends with the string suffix. If \p case_insensitive * is true then the check is case insensitve (default is false; i.e. case is @@ -220,8 +208,7 @@ inline bool str_starts_with(const std::basic_string<T> &str, */ template <typename T> inline bool str_ends_with(const std::basic_string<T> &str, - const std::basic_string<T> &suffix, - bool case_insensitive = false) + const std::basic_string<T> &suffix, bool case_insensitive = false) { if (str.size() < suffix.size()) return false; @@ -236,7 +223,6 @@ inline bool str_ends_with(const std::basic_string<T> &str, return true; } - /** * Check whether \p str ends with the string suffix. If \p case_insensitive * is true then the check is case insensitve (default is false; i.e. case is @@ -248,15 +234,12 @@ inline bool str_ends_with(const std::basic_string<T> &str, * @return true if the str begins with suffix */ template <typename T> -inline bool str_ends_with(const std::basic_string<T> &str, - const T *suffix, +inline bool str_ends_with(const std::basic_string<T> &str, const T *suffix, bool case_insensitive = false) { - return str_ends_with(str, std::basic_string<T>(suffix), - case_insensitive); + return str_ends_with(str, std::basic_string<T>(suffix), case_insensitive); } - /** * Splits a string into its component parts separated by the character * \p delimiter. @@ -264,11 +247,10 @@ inline bool str_ends_with(const std::basic_string<T> &str, * @return An std::vector<std::basic_string<T> > of the component parts */ template <typename T> -inline std::vector<std::basic_string<T> > str_split( - const std::basic_string<T> &str, - T delimiter) +inline std::vector<std::basic_string<T>> str_split( + const std::basic_string<T> &str, T delimiter) { - std::vector<std::basic_string<T> > parts; + std::vector<std::basic_string<T>> parts; std::basic_stringstream<T> sstr(str); std::basic_string<T> part; @@ -278,7 +260,6 @@ inline std::vector<std::basic_string<T> > str_split( return parts; } - /** * @param str * @return A copy of \p str converted to all lowercase characters. @@ -295,7 +276,6 @@ inline std::string lowercase(const std::string &str) return s2; } - /** * @param str * @return A copy of \p str with leading and trailing whitespace removed. @@ -314,7 +294,6 @@ inline std::string trim(const std::string &str) return str.substr(front, back - front); } - /** * Returns whether \p str should be regarded as (bool) true. Case and leading * and trailing whitespace are ignored. Values that will return @@ -328,7 +307,6 @@ inline bool is_yes(const std::string &str) return s2 == "y" || s2 == "yes" || s2 == "true" || atoi(s2.c_str()) != 0; } - /** * Converts the string \p str to a signed 32-bit integer. The converted value * is constrained so that min <= value <= max. @@ -353,11 +331,9 @@ inline s32 mystoi(const std::string &str, s32 min, s32 max) return i; } - // MSVC2010 includes it's own versions of these //#if !defined(_MSC_VER) || _MSC_VER < 1600 - /** * Returns a 32-bit value reprensented by the string \p str (decimal). * @see atoi(3) for further limitations @@ -367,7 +343,6 @@ inline s32 mystoi(const std::string &str) return atoi(str.c_str()); } - /** * Returns s 32-bit value represented by the wide string \p str (decimal). * @see atoi(3) for further limitations @@ -377,7 +352,6 @@ inline s32 mystoi(const std::wstring &str) return mystoi(wide_to_narrow(str)); } - /** * Returns a float reprensented by the string \p str (decimal). * @see atof(3) @@ -393,8 +367,7 @@ inline float mystof(const std::string &str) #define stof mystof /// Returns a value represented by the string \p val. -template <typename T> -inline T from_string(const std::string &str) +template <typename T> inline T from_string(const std::string &str) { std::stringstream tmp(str); T t; @@ -403,28 +376,28 @@ inline T from_string(const std::string &str) } /// Returns a 64-bit signed value represented by the string \p str (decimal). -inline s64 stoi64(const std::string &str) { return from_string<s64>(str); } +inline s64 stoi64(const std::string &str) +{ + return from_string<s64>(str); +} #if __cplusplus < 201103L -namespace std { +namespace std +{ /// Returns a string representing the value \p val. -template <typename T> -inline string to_string(T val) +template <typename T> inline string to_string(T val) { ostringstream oss; oss << val; return oss.str(); } -#define DEFINE_STD_TOSTRING_FLOATINGPOINT(T) \ - template <> \ - inline string to_string<T>(T val) \ - { \ - ostringstream oss; \ - oss << std::fixed \ - << std::setprecision(6) \ - << val; \ - return oss.str(); \ +#define DEFINE_STD_TOSTRING_FLOATINGPOINT(T) \ + template <> inline string to_string<T>(T val) \ + { \ + ostringstream oss; \ + oss << std::fixed << std::setprecision(6) << val; \ + return oss.str(); \ } DEFINE_STD_TOSTRING_FLOATINGPOINT(float) DEFINE_STD_TOSTRING_FLOATINGPOINT(double) @@ -433,18 +406,23 @@ DEFINE_STD_TOSTRING_FLOATINGPOINT(long double) #undef DEFINE_STD_TOSTRING_FLOATINGPOINT /// Returns a wide string representing the value \p val -template <typename T> -inline wstring to_wstring(T val) +template <typename T> inline wstring to_wstring(T val) { - return utf8_to_wide(to_string(val)); + return utf8_to_wide(to_string(val)); } } #endif /// Returns a string representing the decimal value of the 32-bit value \p i. -inline std::string itos(s32 i) { return std::to_string(i); } +inline std::string itos(s32 i) +{ + return std::to_string(i); +} /// Returns a string representing the decimal value of the 64-bit value \p i. -inline std::string i64tos(s64 i) { return std::to_string(i); } +inline std::string i64tos(s64 i) +{ + return std::to_string(i); +} // std::to_string uses the '%.6f' conversion, which is inconsistent with // std::ostream::operator<<() and impractical too. ftos() uses the @@ -457,7 +435,6 @@ inline std::string ftos(float f) return oss.str(); } - /** * Replace all occurrences of \p pattern in \p str with \p replacement. * @@ -496,7 +473,6 @@ inline void str_formspec_escape(std::string &str) */ void str_replace(std::string &str, char from, char to); - /** * Check that a string only contains whitelisted characters. This is the * opposite of string_allowed_blacklist(). @@ -512,7 +488,6 @@ inline bool string_allowed(const std::string &str, const std::string &allowed_ch return str.find_first_not_of(allowed_chars) == str.npos; } - /** * Check that a string contains no blacklisted characters. This is the * opposite of string_allowed(). @@ -523,13 +498,12 @@ inline bool string_allowed(const std::string &str, const std::string &allowed_ch * @see string_allowed() */ -inline bool string_allowed_blacklist(const std::string &str, - const std::string &blacklisted_chars) +inline bool string_allowed_blacklist( + const std::string &str, const std::string &blacklisted_chars) { return str.find_first_of(blacklisted_chars) == str.npos; } - /** * Create a string based on \p from where a newline is forcefully inserted * every \p row_len characters. @@ -545,8 +519,7 @@ inline bool string_allowed_blacklist(const std::string &str, * @param row_len The row length (in characters). * @return A new string with the wrapping applied. */ -inline std::string wrap_rows(const std::string &from, - unsigned row_len) +inline std::string wrap_rows(const std::string &from, unsigned row_len) { std::string to; @@ -564,7 +537,6 @@ inline std::string wrap_rows(const std::string &from, return to; } - /** * Removes backslashes from an escaped string (FormSpec strings) */ @@ -599,7 +571,8 @@ std::basic_string<T> unescape_enriched(const std::basic_string<T> &s) while (i < s.length()) { if (s[i] == '\x1b') { ++i; - if (i == s.length()) continue; + if (i == s.length()) + continue; if (s[i] == '(') { ++i; while (i < s.length() && s[i] != ')') { @@ -621,9 +594,9 @@ std::basic_string<T> unescape_enriched(const std::basic_string<T> &s) } template <typename T> -std::vector<std::basic_string<T> > split(const std::basic_string<T> &s, T delim) +std::vector<std::basic_string<T>> split(const std::basic_string<T> &s, T delim) { - std::vector<std::basic_string<T> > tokens; + std::vector<std::basic_string<T>> tokens; std::basic_string<T> current; bool last_was_escape = false; @@ -646,7 +619,7 @@ std::vector<std::basic_string<T> > split(const std::basic_string<T> &s, T delim) } } } - //push last element + // push last element tokens.push_back(current); return tokens; @@ -656,7 +629,8 @@ std::wstring translate_string(const std::wstring &s, Translations *translations) std::wstring translate_string(const std::wstring &s); -inline std::wstring unescape_translate(const std::wstring &s) { +inline std::wstring unescape_translate(const std::wstring &s) +{ return unescape_enriched(translate_string(s)); } @@ -676,7 +650,6 @@ inline bool is_number(const std::string &to_check) return !to_check.empty(); } - /** * Returns a C-string, either "true" or "false", corresponding to \p val. * @@ -715,8 +688,8 @@ inline const std::string duration_to_string(int sec) * * @return A std::string */ -inline std::string str_join(const std::vector<std::string> &list, - const std::string &delimiter) +inline std::string str_join( + const std::vector<std::string> &list, const std::string &delimiter) { std::ostringstream oss; bool first = true; @@ -738,9 +711,9 @@ inline std::string stringw_to_utf8(const irr::core::stringw &input) return wide_to_utf8(str); } - /** - * Create a irr::core:stringw from a UTF8 std::string. - */ +/** + * Create a irr::core:stringw from a UTF8 std::string. + */ inline irr::core::stringw utf8_to_stringw(const std::string &input) { std::wstring str = utf8_to_wide(input); diff --git a/src/util/thread.h b/src/util/thread.h index 73e9beb80..4633de310 100644 --- a/src/util/thread.h +++ b/src/util/thread.h @@ -26,13 +26,10 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "log.h" #include "container.h" -template<typename T> -class MutexedVariable +template <typename T> class MutexedVariable { public: - MutexedVariable(const T &value): - m_value(value) - {} + MutexedVariable(const T &value) : m_value(value) {} T get() { @@ -48,6 +45,7 @@ public: // You pretty surely want to grab the lock when accessing this T m_value; + private: std::mutex m_mutex; }; @@ -55,38 +53,37 @@ private: /* A single worker thread - multiple client threads queue framework. */ -template<typename Key, typename T, typename Caller, typename CallerData> -class GetResult { +template <typename Key, typename T, typename Caller, typename CallerData> class GetResult +{ public: Key key; T item; std::pair<Caller, CallerData> caller; }; -template<typename Key, typename T, typename Caller, typename CallerData> -class ResultQueue : public MutexedQueue<GetResult<Key, T, Caller, CallerData> > { +template <typename Key, typename T, typename Caller, typename CallerData> +class ResultQueue : public MutexedQueue<GetResult<Key, T, Caller, CallerData>> +{ }; -template<typename Caller, typename Data, typename Key, typename T> -class CallerInfo { +template <typename Caller, typename Data, typename Key, typename T> class CallerInfo +{ public: Caller caller; Data data; ResultQueue<Key, T, Caller, Data> *dest; }; -template<typename Key, typename T, typename Caller, typename CallerData> -class GetRequest { +template <typename Key, typename T, typename Caller, typename CallerData> class GetRequest +{ public: GetRequest() = default; ~GetRequest() = default; - GetRequest(const Key &a_key): key(a_key) - { - } + GetRequest(const Key &a_key) : key(a_key) {} Key key; - std::list<CallerInfo<Caller, CallerData, Key, T> > callers; + std::list<CallerInfo<Caller, CallerData, Key, T>> callers; }; /** @@ -96,32 +93,33 @@ public: * @param Caller unique id of calling thread * @param CallerData data passed back to caller */ -template<typename Key, typename T, typename Caller, typename CallerData> -class RequestQueue { +template <typename Key, typename T, typename Caller, typename CallerData> +class RequestQueue +{ public: - bool empty() - { - return m_queue.empty(); - } + bool empty() { return m_queue.empty(); } void add(const Key &key, Caller caller, CallerData callerdata, - ResultQueue<Key, T, Caller, CallerData> *dest) + ResultQueue<Key, T, Caller, CallerData> *dest) { - typename std::deque<GetRequest<Key, T, Caller, CallerData> >::iterator i; - typename std::list<CallerInfo<Caller, CallerData, Key, T> >::iterator j; + typename std::deque<GetRequest<Key, T, Caller, CallerData>>::iterator i; + typename std::list<CallerInfo<Caller, CallerData, Key, T>>::iterator j; { MutexAutoLock lock(m_queue.getMutex()); /* - If the caller is already on the list, only update CallerData + If the caller is already on the list, only update + CallerData */ - for (i = m_queue.getQueue().begin(); i != m_queue.getQueue().end(); ++i) { + for (i = m_queue.getQueue().begin(); + i != m_queue.getQueue().end(); ++i) { GetRequest<Key, T, Caller, CallerData> &request = *i; if (request.key != key) continue; - for (j = request.callers.begin(); j != request.callers.end(); ++j) { + for (j = request.callers.begin(); + j != request.callers.end(); ++j) { CallerInfo<Caller, CallerData, Key, T> &ca = *j; if (ca.caller == caller) { ca.data = callerdata; @@ -158,19 +156,16 @@ public: return m_queue.pop_front(timeout_ms); } - GetRequest<Key, T, Caller, CallerData> pop() - { - return m_queue.pop_frontNoEx(); - } + GetRequest<Key, T, Caller, CallerData> pop() { return m_queue.pop_frontNoEx(); } void pushResult(GetRequest<Key, T, Caller, CallerData> req, T res) { - for (typename std::list<CallerInfo<Caller, CallerData, Key, T> >::iterator - i = req.callers.begin(); + for (typename std::list<CallerInfo<Caller, CallerData, Key, T>>::iterator + i = req.callers.begin(); i != req.callers.end(); ++i) { CallerInfo<Caller, CallerData, Key, T> &ca = *i; - GetResult<Key,T,Caller,CallerData> result; + GetResult<Key, T, Caller, CallerData> result; result.key = req.key; result.item = res; @@ -182,7 +177,7 @@ public: } private: - MutexedQueue<GetRequest<Key, T, Caller, CallerData> > m_queue; + MutexedQueue<GetRequest<Key, T, Caller, CallerData>> m_queue; }; class UpdateThread : public Thread @@ -208,9 +203,11 @@ public: while (!stopRequested()) { m_update_sem.wait(); // Set semaphore to 0 - while (m_update_sem.wait(0)); + while (m_update_sem.wait(0)) + ; - if (stopRequested()) break; + if (stopRequested()) + break; doUpdate(); } diff --git a/src/util/timetaker.cpp b/src/util/timetaker.cpp index 717449c6d..34bc38871 100644 --- a/src/util/timetaker.cpp +++ b/src/util/timetaker.cpp @@ -39,15 +39,14 @@ u64 TimeTaker::stop(bool quiet) (*m_result) += dtime; } else { if (!quiet) { - static const char* const units[] = { - "s" /* PRECISION_SECONDS */, - "ms" /* PRECISION_MILLI */, - "us" /* PRECISION_MICRO */, - "ns" /* PRECISION_NANO */, + static const char *const units[] = { + "s" /* PRECISION_SECONDS */, + "ms" /* PRECISION_MILLI */, + "us" /* PRECISION_MICRO */, + "ns" /* PRECISION_NANO */, }; - infostream << m_name << " took " - << dtime << units[m_precision] - << std::endl; + infostream << m_name << " took " << dtime + << units[m_precision] << std::endl; } } m_running = false; @@ -60,4 +59,3 @@ u64 TimeTaker::getTimerTime() { return porting::getTime(m_precision) - m_time1; } - diff --git a/src/util/timetaker.h b/src/util/timetaker.h index bc3d4a88d..0abf9baa5 100644 --- a/src/util/timetaker.h +++ b/src/util/timetaker.h @@ -29,15 +29,12 @@ with this program; if not, write to the Free Software Foundation, Inc., class TimeTaker { public: - TimeTaker(const std::string &name, u64 *result=nullptr, - TimePrecision prec=PRECISION_MILLI); + TimeTaker(const std::string &name, u64 *result = nullptr, + TimePrecision prec = PRECISION_MILLI); - ~TimeTaker() - { - stop(); - } + ~TimeTaker() { stop(); } - u64 stop(bool quiet=false); + u64 stop(bool quiet = false); u64 getTimerTime(); |