diff --git a/docs/ru/base-HashMap.md b/docs/ru/base-HashMap.md index 5ad0c53..3e802f6 100644 --- a/docs/ru/base-HashMap.md +++ b/docs/ru/base-HashMap.md @@ -128,6 +128,11 @@ String toJSON() const; ``` Сериализует содержимое таблицы в формат JSON-строки. +Пустая таблица возвращает `{}`. Строковые ключи и значения экранируются +по правилам JSON, включая управляющие символы и встроенный нулевой байт. +Числа и логические значения сохраняют свой тип; `NaN`, бесконечности и +нулевой указатель C-строки сериализуются как `null`. + ### HashMap.toString() ```cpp String toString() const; @@ -146,6 +151,9 @@ const V& at(const K& key) const; ``` Возвращает значение по ключу. Если ключ не найден, метод возвращает значение первого элемента таблицы. +При отсутствии ключа таблица должна быть непустой: для пустой таблицы +первого элемента нет. Перед вызовом проверяйте `empty()` или `has()`. + ## ncpp::HashSet `HashSet` — хэш-таблица, хранящая только ключи. Является легковесной альтернативой `std::unordered_set` (C++11). @@ -154,4 +162,8 @@ HashSet(); HashSet(const HashSet& s); ``` -Все методы `HashSet` аналогичны `HashMap`. \ No newline at end of file +Все методы `HashSet` аналогичны `HashMap`. + +В общей реализации `HashSet` значение совпадает с ключом. Поэтому +`toJSON()` возвращает объект с одинаковыми ключами и значениями +(например, `{"7":7}`), а не массив. `assign()` объединяет ключи множеств. diff --git a/src/base/HashMap.cpp b/src/base/HashMap.cpp index dfff9e6..f25076a 100644 --- a/src/base/HashMap.cpp +++ b/src/base/HashMap.cpp @@ -1,5 +1,7 @@ //Rigtorp HashMap Modified (Linear Probing) O(~1) //MIT: https://github.com/rigtorp/HashMap +#include +#include namespace ncpp { uint32_t Fnv1a(const char* data, size_t len){ uint32_t hash = 2166136261u; for(size_t i = 0; i < len; ++i) hash ^= (uint8_t)data[i], hash *= 16777619u; return hash; } @@ -13,6 +15,61 @@ uint32_t hash(const String& s){ return Fnv1a(s.c_str(), s.size()); } uint32_t hash(const CString& cs){ return Fnv1a(cs.c_str(), cs.size()); } uint32_t hash(const Buffer& bf){ return Fnv1a((const char*)bf.data(), bf.size()); } +namespace hash_detail { + String quote(const String& input){ + String result("\""); const char* hex = "0123456789abcdef"; + for(size_t i = 0; i < input.size(); ++i){ + unsigned char ch = (unsigned char)input[i]; + switch(ch){ + case '"': result += "\\\""; break; + case '\\': result += "\\\\"; break; + case '\b': result += "\\b"; break; + case '\f': result += "\\f"; break; + case '\n': result += "\\n"; break; + case '\r': result += "\\r"; break; + case '\t': result += "\\t"; break; + default: + if(ch < 0x20){ result += "\\u00"; result += hex[ch >> 4]; result += hex[ch & 15]; } + else result += (char)ch; + } + } + result += '"'; return result; + } + String integer(unsigned long long magnitude, bool negative){ + char digits[21]; size_t size = 0; + do { digits[size++] = (char)('0' + magnitude % 10); magnitude /= 10; } while(magnitude); + if(negative) digits[size++] = '-'; reverse(digits, digits + size); + return String(digits, size); + } + template String text(const T& item){ String result; result << item; return result; } + String text(unsigned long long item){ return integer(item, false); } + String text(long long item){ + unsigned long long magnitude = (unsigned long long)item; + if(item < 0) magnitude = 0ULL - magnitude; + return integer(magnitude, item < 0); + } + String text(long item){ return text((long long)item); } + String text(unsigned long item){ return text((unsigned long long)item); } + String text(bool item){ return item ? "true" : "false"; } + String floating(double item, int precision){ + if(isNaN(item)) return "null"; // JSON has no NaN or infinity literals. + char buffer[64]; int size = snprintf(buffer, sizeof(buffer), "%.*g", precision, item); + if(size < 0 || (size_t)size >= sizeof(buffer)) return "null"; + String result(buffer, (size_t)size); + const char* point = localeconv()->decimal_point; + if(point && *point && strcmp(point, ".") != 0) result = result.replaceAll(point, "."); + return result; + } + String text(double item){ return floating(item, 17); } + String text(float item){ return floating(item, 9); } + template String value(const T& item){ return text(item); } + String value(const String& item){ return quote(item); } + String value(const CString& item){ return quote(String(item)); } + String value(const char* item){ return item ? quote(String(item)) : String("null"); } + String value(char* item){ return value((const char*)item); } + template String key(const T& item){ return quote(text(item)); } +} + //template <> struct hash{ size_t operator()(int val) const { return val; } } template @@ -55,7 +112,7 @@ class _HashTable { IterDerived& operator++(){ do{ ++idx; }while(idx < tbl->size() && !(*tbl)[idx].occupied); return (IterDerived&)*this; } //prefix ++it IterDerived operator++(int){ IterDerived it0=IterDerived(tbl, idx); ++(*this); return it0; } //postfix it++ - IterDerived& operator--(){ if(idx == 0) return *this; do { --idx; }while(idx > 0 && !(*tbl)[idx].occupied); return (IterDerived&)*this; } //prefix --it + IterDerived& operator--(){ if(idx == 0) return (IterDerived&)*this; do { --idx; }while(idx > 0 && !(*tbl)[idx].occupied); return (IterDerived&)*this; } //prefix --it IterDerived operator--(int){ IterDerived it0=IterDerived(tbl, idx); --(*this); return it0; } //postfix it-- }; @@ -111,19 +168,23 @@ public: typedef _HashTable MapT; //typedef _HashTable Map // == == //typedef typename MapType::iterator iterator; typedef typename MapType::const_iterator const_iterator; - Array keys() const { Array keys; for(typename MapT::ConstIter it = begin(); it != end(); ++it){ keys.push(it->first); } return keys; } + Array keys() const { Array keys; for(typename MapT::ConstIter it = begin(); it != end(); ++it){ keys.push(it->key()); } return keys; } bool has(const K& key) const { return this->find(key) != this->end(); } static Derived& assign(Derived& target, const Derived& map2){ - for(ConstIter it = map2.begin(); it != map2.end(); ++it){ target[it->first]=it->second; } return target; } + for(ConstIter it = map2.begin(); it != map2.end(); ++it){ target[it->key()]=it->value(); } return target; } static Derived& assign(Derived& target, const Array& maps){ for(size_t i=0;ibegin(); it != this->end(); ++it){ ss << "\n \"" << it->first << "\": " << it->second << ", "; } ss+="}"; return ss; } - String toJSON() const { String ss("{"); for(ConstIter it = this->begin(); it != this->end(); ++it){ ss << "\"" << it->first << "\":" << it->second<<","; } - ss.resize(ss.size()-1); ss << "}"; return ss; } + for(ConstIter it = this->begin(); it != this->end(); ++it){ ss << "\n \"" << it->key() << "\": " << it->value() << ", "; } ss+="}"; return ss; } + String toJSON() const { String ss("{"); bool first = true; + for(ConstIter it = this->begin(); it != this->end(); ++it){ + if(!first) ss += ','; first = false; + ss << hash_detail::key(it->key()) << ":" << hash_detail::value(it->value()); + } + ss += '}'; return ss; } String toString() const { return cout(); } String type() const { return "map"; } // unsafe - const V& at(const K& key) const { ConstIter it = this->find(key); if(it == this->end()){ return begin()->second; } return it->second; } + const V& at(const K& key) const { ConstIter it = this->find(key); if(it == this->end()){ return begin()->value(); } return it->value(); } //const V& operator[](const K& key) const; }; @@ -142,4 +203,4 @@ typedef HashMap LLMap; template void print(const HashMap& map){ print(map.cout()); } template void print(const HashSet& set){ print(set.cout()); } -} \ No newline at end of file +} diff --git a/tests/make_test.bat b/tests/make_test.bat index 39d3986..07d83ef 100644 --- a/tests/make_test.bat +++ b/tests/make_test.bat @@ -1,98 +1,142 @@ -@echo off -set currCD=%CD% -set gccpath= -::set clangpath= -::set msvcpath= - -::set gccpath="D:\Progs\IDE\MinGW\gcc-4.9.2-tdm\bin" -::set gccpath="D:\Progs\IDE\MinGW\gcc-10.3.0-tdm\bin" -::set gccpath="D:\Progs\IDE\MinGW\i686-13.1.0-posix-dwarf-msvcrt\bin" -::set gccpath="D:\Progs\IDE\MinGW\i686-15.2.0-posix-dwarf-msvcrt\bin" -::set clangpath="D:\Progs\IDE\MinGW\llvm-mingw-20250910-msvcrt-x86_64\bin" -::set clangpath="D:\Progs\IDE\MinGW\llvm-mingw-20190920-9.0.0-x86_64\bin" - -set COMPILER=GCC -set CBIN=g++ -if "%~1"=="GCC" (set "COMPILER=GCC" & set "CBIN=g++" & shift) -::if "%~1"=="CLANG" (set "COMPILER=CLANG" & set "CBIN=i686-w64-mingw32-clang++" & set "gccpath=%clangpath%" & shift) -if "%~1"=="CLANG" (set "COMPILER=CLANG" & set "CBIN=clang++" & set "gccpath=%clangpath%" & shift) -if "%~1"=="MSVC" (set "COMPILER=MSVC" & set "CBIN=cl" & set "gccpath=%msvcpath%" & shift) - -set STDCXX=c++98 -if "%~1"=="C++98" (set "STDCXX=c++98" & shift) -if "%~1"=="C++11" (set "STDCXX=c++11" & shift) -if "%~1"=="C++17" (set "STDCXX=c++17" & shift) -if "%~1"=="C++23" (set "STDCXX=c++23" & shift) - -set ARCH_FLAG=-m32 -set WL_ENTRY_FNAME=__start -if "%~1"=="x64" (set "ARCH_FLAG=-m64" & set "WL_ENTRY_FNAME=_start" & shift) -if "%~1"=="x32" (set "ARCH_FLAG=-m32" & set "WL_ENTRY_FNAME=__start" & shift) -::if "%ARCH_FLAG%"=="-m64" if "%COMPILER%"=="CLANG" (set "ARCH_FLAG=-target x86_64-w64-mingw32 %ARCH_FLAG%") -::if "%ARCH_FLAG%"=="-m32" if "%COMPILER%"=="CLANG" (set "ARCH_FLAG=-target i686-w64-mingw32 %ARCH_FLAG%") - -set WARN_FLAGS=-Wall -Wno-misleading-indentation -set FNO_FLAGS=-fno-exceptions -fno-rtti -set FNO_FLAGS_WH=%FNO_FLAGS% -fwhole-program -::if "%COMPILER%"=="CLANG" (set "FNO_FLAGS_WH=%FNO_FLAGS% -flto=full -fvisibility=hidden -Wl,/OPT:REF -Wl,/OPT:ICF") -set OPT_FLAGS=-O2 -std=%STDCXX% %FNO_FLAGS_WH% - -set DBG_LNK_FLAGS=%ARCH_FLAG% -lws2_32 -lpsapi -liphlpapi -::if "%COMPILER%"=="GCC" set DBG_LNK_FLAGS=%ARCH_FLAG% -nodefaultlibs -lws2_32 -lpsapi -liphlpapi -lsupc++ -lpthread -lmingw32 -lmingwex -lmsvcrt -lgcc -ladvapi32 -lkernel32 -::if "%COMPILER%"=="CLANG" set DBG_LNK_FLAGS=%ARCH_FLAG% -nodefaultlibs -lws2_32 -lpsapi -liphlpapi -lpthread -lc++ -lclang_rt.builtins-i386 -lmingw32 -lmingwex -lmsvcrt -ladvapi32 -luser32 -lkernel32 -if "%COMPILER%"=="CLANG" (set "DBG_LNK_FLAGS=-target i686-w64-mingw32 %DBG_LNK_FLAGS% -pthread") - -set GCC_LIBS=-static-libgcc -static-libstdc++ -set D_LNK_FLAGS=-s %GCC_LIBS% %DBG_LNK_FLAGS% -set LNK_FLAGS=-static %D_LNK_FLAGS% - -set AUDIO_LIBS=-lwinmm -set IMAGE_LIBS=-lgdiplus -lgdi32 -lole32 - -set mode= -if "%~1"=="LIB" (set "mode=%~1") -if "%~1"=="LIB_DLL" (set "mode=%~1") -if "%~1"=="LIB_SO" (set "mode=LIB_DLL") -if "%~1"=="FAST" (set "mode=%~1") -if "%~1"=="SAN" (set "mode=%~1") -if "%~1"=="DBG" (set "mode=%~1") -if "%~1"=="SDBG" (set "mode=DBG") -if "%~1"=="GUI" (set "mode=%~1") -if "%~1"=="SGUI" (set "mode=GUI") -if "%~1"=="GL" (set "mode=%~1") -if "%~1"=="EXP" (set "mode=%~1") -if "%~1"=="NOCRT" (set "mode=%~1") -if "%~1"=="DLNK" (set "mode=%~1") -if "%1"=="DEF" (shift) -if not "%mode%"=="" (shift) - -if "%~1"=="" (set fname=tests) else (set fname=%1) -set cppfile=%CD%\%fname%.cpp -set exefile=%CD%\%fname%.exe -set start_time=%TIME% - -if not "%gccpath%"=="" (cd /d "%gccpath%") - -if "%mode%"=="LIB" echo Make via ncpp.a... & %CBIN% -D NCPP_LIB_USE %WARN_FLAGS% %OPT_FLAGS% %cppfile% -o %exefile% -L"%currCD%\..\lib" -lncpp %LNK_FLAGS% -if "%mode%"=="LIB_DLL" echo Make via ncpp.dll... & %CBIN% -D NCPP_LIB_USE %WARN_FLAGS% %OPT_FLAGS% %cppfile% -o %exefile% -L"%currCD%\..\lib" -lncpp %D_LNK_FLAGS% -if "%mode%"=="FAST" echo Make with -O3 -march=native... & %CBIN% %WARN_FLAGS% -O3 -std=$STDCXX %FNO_FLAGS_WH% %cppfile% -o %exefile% -march=native -mtune=native -flto -funroll-loops -fipa-cp-clone -ffast-math -fomit-frame-pointer %LNK_FLAGS% -if "%mode%"=="DBG" echo Make debug -g -Og... & %CBIN% %WARN_FLAGS% -g -Og -std=%STDCXX% %FNO_FLAGS_WH% %cppfile% -o %exefile% %DBG_LNK_FLAGS% -if "%mode%"=="SAN" echo Make using sanitizers... & %CBIN% %WARN_FLAGS% -g -Og -std=%STDCXX% %FNO_FLAGS_WH% %cppfile% -o %exefile% %D_LNK_FLAGS% -fsanitize=address,undefined -if "%mode%"=="GUI" echo Make for GUI... & %CBIN% -DUSE_GUI -DNOUSE_GL %WARN_FLAGS% %OPT_FLAGS% %cppfile% -o %exefile% %LNK_FLAGS% -lgdi32 -if "%mode%"=="GL" echo Make for GL... & %CBIN% -DUSE_GUI %WARN_FLAGS% %OPT_FLAGS% %cppfile% -o %exefile% %LNK_FLAGS% -lopengl32 -lgdi32 -if "%mode%"=="EXP" echo Make for Experimental... & %CBIN% -DUSE_GUI -DUSE_EXPERIMENTAL %WARN_FLAGS% %OPT_FLAGS% %cppfile% -o %exefile% %LNK_FLAGS% -lopengl32 %IMAGE_LIBS% %AUDIO_LIBS% -if "%mode%"=="NOCRT" echo Make NOCRT... & %CBIN% -DNCPP_NOCRT %WARN_FLAGS% -O2 -std=%STDCXX% %FNO_FLAGS% %cppfile% -o %exefile% %ARCH_FLAG% -Wl,--entry=%WL_ENTRY_FNAME% -s -static -nostdlib -lkernel32 -if "%mode%"=="DLNK" echo Make DLNK (Dynamic Lnk)... & %CBIN% %WARN_FLAGS% %OPT_FLAGS% %cppfile% -o %exefile% %D_LNK_FLAGS% -if "%mode%"=="" echo Make (default)... & %CBIN% %WARN_FLAGS% %OPT_FLAGS% %cppfile% -o %exefile% %LNK_FLAGS% - -if not "%gccpath%"=="" (cd /d "%currCD%") - -:: === Time calc === -set end_time=%TIME% -set /A startMS=((1%start_time:~0,2%-100)*3600000)+((1%start_time:~3,2%-100)*60000)+(1%start_time:~6,2%*1000)+(1%start_time:~9,2%) -set /A endMS=((1%end_time:~0,2%-100)*3600000)+((1%end_time:~3,2%-100)*60000)+(1%end_time:~6,2%*1000)+(1%end_time:~9,2%) -set /A durationMS=endMS-startMS -set /A durationS=durationMS/1000 -set /A durationMS=durationMS%%1000 -echo Build Time: %durationS%.%durationMS% sec. -pause \ No newline at end of file +@echo off +set currCD=%CD% +set gccpath= +::set clangpath= +::set msvcpath= + +::set gccpath="D:\Progs\IDE\MinGW\gcc-4.9.2-tdm\bin" +::set gccpath="D:\Progs\IDE\MinGW\gcc-10.3.0-tdm\bin" +::set gccpath="D:\Progs\IDE\MinGW\i686-13.1.0-posix-dwarf-msvcrt\bin" +::set gccpath="D:\Progs\IDE\MinGW\i686-15.2.0-posix-dwarf-msvcrt\bin" +::set clangpath="D:\Progs\IDE\MinGW\llvm-mingw-20250910-msvcrt-x86_64\bin" +::set clangpath="D:\Progs\IDE\MinGW\llvm-mingw-20190920-9.0.0-x86_64\bin" + +set COMPILER=GCC +set CBIN=g++ +if "%~1"=="GCC" (set "COMPILER=GCC" & set "CBIN=g++" & shift) +::if "%~1"=="CLANG" (set "COMPILER=CLANG" & set "CBIN=i686-w64-mingw32-clang++" & set "gccpath=%clangpath%" & shift) +if "%~1"=="CLANG" (set "COMPILER=CLANG" & set "CBIN=clang++" & set "gccpath=%clangpath%" & shift) +if "%~1"=="MSVC" (set "COMPILER=MSVC" & set "CBIN=cl" & set "gccpath=%msvcpath%" & shift) + +set STDCXX=c++98 +if "%~1"=="C++98" (set "STDCXX=c++98" & shift) +if "%~1"=="C++11" (set "STDCXX=c++11" & shift) +if "%~1"=="C++17" (set "STDCXX=c++17" & shift) +if "%~1"=="C++23" (set "STDCXX=c++23" & shift) + +set ARCH_FLAG=-m32 +set WL_ENTRY_FNAME=__start +if "%~1"=="x64" (set "ARCH_FLAG=-m64" & set "WL_ENTRY_FNAME=_start" & shift) +if "%~1"=="x32" (set "ARCH_FLAG=-m32" & set "WL_ENTRY_FNAME=__start" & shift) +::if "%ARCH_FLAG%"=="-m64" if "%COMPILER%"=="CLANG" (set "ARCH_FLAG=-target x86_64-w64-mingw32 %ARCH_FLAG%") +::if "%ARCH_FLAG%"=="-m32" if "%COMPILER%"=="CLANG" (set "ARCH_FLAG=-target i686-w64-mingw32 %ARCH_FLAG%") + +set WARN_FLAGS=-Wall -Wno-misleading-indentation +set FNO_FLAGS=-fno-exceptions -fno-rtti +set FNO_FLAGS_WH=%FNO_FLAGS% -fwhole-program +if "%COMPILER%"=="CLANG" (set "FNO_FLAGS_WH=%FNO_FLAGS% -fvisibility=hidden") +set OPT_FLAGS=-O2 -std=%STDCXX% %FNO_FLAGS_WH% + +set DBG_LNK_FLAGS=%ARCH_FLAG% -lws2_32 -lpsapi -liphlpapi +::if "%COMPILER%"=="GCC" set DBG_LNK_FLAGS=%ARCH_FLAG% -nodefaultlibs -lws2_32 -lpsapi -liphlpapi -lsupc++ -lpthread -lmingw32 -lmingwex -lmsvcrt -lgcc -ladvapi32 -lkernel32 +::if "%COMPILER%"=="CLANG" set DBG_LNK_FLAGS=%ARCH_FLAG% -nodefaultlibs -lws2_32 -lpsapi -liphlpapi -lpthread -lc++ -lclang_rt.builtins-i386 -lmingw32 -lmingwex -lmsvcrt -ladvapi32 -luser32 -lkernel32 +if "%COMPILER%"=="CLANG" (set "DBG_LNK_FLAGS=-target i686-w64-mingw32 %DBG_LNK_FLAGS% -pthread") + +set GCC_LIBS=-static-libgcc -static-libstdc++ +set D_LNK_FLAGS=-s %GCC_LIBS% %DBG_LNK_FLAGS% +set LNK_FLAGS=-static %D_LNK_FLAGS% + +set AUDIO_LIBS=-lwinmm +set IMAGE_LIBS=-lgdiplus -lgdi32 -lole32 + +set mode= +if "%~1"=="LIB" (set "mode=%~1") +if "%~1"=="LIB_DLL" (set "mode=%~1") +if "%~1"=="LIB_SO" (set "mode=LIB_DLL") +if "%~1"=="FAST" (set "mode=%~1") +if "%~1"=="SAN" (set "mode=%~1") +if "%~1"=="DBG" (set "mode=%~1") +if "%~1"=="SDBG" (set "mode=DBG") +if "%~1"=="GUI" (set "mode=%~1") +if "%~1"=="SGUI" (set "mode=GUI") +if "%~1"=="GL" (set "mode=%~1") +if "%~1"=="EXP" (set "mode=%~1") +if "%~1"=="NOCRT" (set "mode=%~1") +if "%~1"=="DLNK" (set "mode=%~1") +if "%1"=="DEF" (shift) +if not "%mode%"=="" (shift) + +if "%~1"=="" (set fname=tests) else (set fname=%1) +set cppfile=%CD%\%fname%.cpp +set exefile=%CD%\%fname%.exe +set start_time=%TIME% + +if not "%gccpath%"=="" (cd /d "%gccpath%") + +if "%mode%"=="LIB" ( + echo Make via ncpp.a... + %CBIN% -D NCPP_LIB_USE %WARN_FLAGS% %OPT_FLAGS% "%cppfile%" -o "%exefile%" -L"%currCD%\..\lib" -lncpp %LNK_FLAGS% + if errorlevel 1 exit /b 1 +) +if "%mode%"=="LIB_DLL" ( + echo Make via ncpp.dll... + %CBIN% -D NCPP_LIB_USE %WARN_FLAGS% %OPT_FLAGS% "%cppfile%" -o "%exefile%" -L"%currCD%\..\lib" -lncpp %D_LNK_FLAGS% + if errorlevel 1 exit /b 1 +) +if "%mode%"=="FAST" ( + echo Make with -O3 -march=native... + %CBIN% %WARN_FLAGS% -O3 -std=%STDCXX% %FNO_FLAGS_WH% "%cppfile%" -o "%exefile%" -march=native -mtune=native -flto -funroll-loops -fipa-cp-clone -ffast-math -fomit-frame-pointer %LNK_FLAGS% + if errorlevel 1 exit /b 1 +) +if "%mode%"=="DBG" ( + echo Make debug -g -Og... + %CBIN% %WARN_FLAGS% -g -Og -std=%STDCXX% %FNO_FLAGS_WH% "%cppfile%" -o "%exefile%" %DBG_LNK_FLAGS% + if errorlevel 1 exit /b 1 +) +if "%mode%"=="SAN" ( + echo Make using sanitizers... + %CBIN% %WARN_FLAGS% -g -Og -std=%STDCXX% %FNO_FLAGS_WH% "%cppfile%" -o "%exefile%" %D_LNK_FLAGS% -fsanitize=address,undefined + if errorlevel 1 exit /b 1 +) +if "%mode%"=="GUI" ( + echo Make for GUI... + %CBIN% -DUSE_GUI -DNOUSE_GL %WARN_FLAGS% %OPT_FLAGS% "%cppfile%" -o "%exefile%" %LNK_FLAGS% -lgdi32 + if errorlevel 1 exit /b 1 +) +if "%mode%"=="GL" ( + echo Make for GL... + %CBIN% -DUSE_GUI %WARN_FLAGS% %OPT_FLAGS% "%cppfile%" -o "%exefile%" %LNK_FLAGS% -lopengl32 -lgdi32 + if errorlevel 1 exit /b 1 +) +if "%mode%"=="EXP" ( + echo Make for Experimental... + %CBIN% -DUSE_GUI -DUSE_EXPERIMENTAL %WARN_FLAGS% %OPT_FLAGS% "%cppfile%" -o "%exefile%" %LNK_FLAGS% -lopengl32 %IMAGE_LIBS% %AUDIO_LIBS% + if errorlevel 1 exit /b 1 +) +if "%mode%"=="NOCRT" ( + echo Make NOCRT... + %CBIN% -DNCPP_NOCRT %WARN_FLAGS% -O2 -std=%STDCXX% %FNO_FLAGS% "%cppfile%" -o "%exefile%" %ARCH_FLAG% -Wl,--entry=%WL_ENTRY_FNAME% -s -static -nostdlib -lkernel32 + if errorlevel 1 exit /b 1 +) +if "%mode%"=="DLNK" ( + echo Make DLNK ^(Dynamic Lnk^)... + %CBIN% %WARN_FLAGS% %OPT_FLAGS% "%cppfile%" -o "%exefile%" %D_LNK_FLAGS% + if errorlevel 1 exit /b 1 +) +if "%mode%"=="" ( + echo Make ^(default^)... + %CBIN% %WARN_FLAGS% %OPT_FLAGS% "%cppfile%" -o "%exefile%" %LNK_FLAGS% + if errorlevel 1 exit /b 1 +) + +if not "%gccpath%"=="" (cd /d "%currCD%") + +:: === Time calc === +set end_time=%TIME% +set /A startMS=((1%start_time:~0,2%-100)*3600000)+((1%start_time:~3,2%-100)*60000)+(1%start_time:~6,2%*1000)+(1%start_time:~9,2%) +set /A endMS=((1%end_time:~0,2%-100)*3600000)+((1%end_time:~3,2%-100)*60000)+(1%end_time:~6,2%*1000)+(1%end_time:~9,2%) +set /A durationMS=endMS-startMS +set /A durationS=durationMS/1000 +set /A durationMS=durationMS%%1000 +echo Build Time: %durationS%.%durationMS% sec. +exit /b 0 \ No newline at end of file diff --git a/tests/units/hashmap-test.cpp b/tests/units/hashmap-test.cpp new file mode 100644 index 0000000..2656803 --- /dev/null +++ b/tests/units/hashmap-test.cpp @@ -0,0 +1,286 @@ +// Coverage for the complete public unit documented in docs/ru/base-HashMap.md. +// Keep the original runner and its failure accounting; do not depend on hash order. +void HashTestName(const char* container, const char* operation){ + String name(container); name += "."; name += operation; NextTest(name); +} + +template +void HashContainer_test(const char* name, bool isSet){ + HashTestName(name, "construct/empty/size/begin/end"); + Table table; const Table& constant = table; + TEST_EQ(table.empty(), true); TEST_EQ(table.size(), (size_t)0); + TEST_EQ(table.begin(), table.end()); TEST_EQ(constant.begin(), constant.end()); + TEST_EQ(table.find(7), table.end()); TEST_EQ(constant.find(7), constant.end()); + TEST_EQ(table.has(7), false); + TEST_EQ(table.keys().size(), (size_t)0); + + HashTestName(name, "insert explicit/default/duplicate"); + Pair result = table.insert(0, 40); + TEST_EQ(result.second, true); TEST_NE(result.first, table.end()); + if(result.first != table.end()) TEST_EQ(result.first->value(), isSet ? 0 : 40); + TEST_EQ(table.empty(), false); TEST_EQ(table.size(), (size_t)1); + result = table.insert(0, 99); TEST_EQ(result.second, false); + TEST_EQ(table.size(), (size_t)1); TEST_EQ(constant.at(0), isSet ? 0 : 40); + result = table.insert(8); TEST_EQ(result.second, true); + if(result.first != table.end()) TEST_EQ(result.first->value(), isSet ? 8 : 0); + table.insert(16, 160); // Same initial bucket: exercise linear probing. + TEST_EQ(table.has(16), true); TEST_EQ(table.has(24), false); + + HashTestName(name, "find mutable/const/at missing"); + typename Table::Iter found = table.find(16); + TEST_NE(found, table.end()); + if(found != table.end()) TEST_EQ(found->value(), isSet ? 16 : 160); + typename Table::ConstIter cfound = constant.find(16); + TEST_NE(cfound, constant.end()); + if(cfound != constant.end()) TEST_EQ((*cfound).value(), isSet ? 16 : 160); + TEST_EQ(table.find(32), table.end()); TEST_EQ(constant.find(32), constant.end()); + // at() explicitly falls back to the FIRST element, but needs a nonempty table. + TEST_EQ(constant.at(999), constant.begin()->value()); + TEST_EQ(table.size(), (size_t)3); + + HashTestName(name, "iterator prefix/postfix/conversion"); + typename Table::Iter it = table.begin(); + typename Table::ConstIter converted = it; + TEST_EQ(converted, constant.begin()); TEST_EQ((*it).key(), it->key()); + typename Table::Iter previous = it++; + TEST_NE(previous, it); TEST_EQ(previous, table.begin()); + typename Table::Iter& advanced = ++it; TEST_EQ(&advanced, &it); + TEST_NE(it, table.end()); ++it; TEST_EQ(it, table.end()); + typename Table::Iter last = table.end(); + typename Table::Iter& reversed = --last; TEST_EQ(&reversed, &last); + TEST_NE(last, table.end()); + typename Table::Iter oldLast = last--; TEST_NE(oldLast, last); + --last; TEST_EQ(last, table.begin()); + typename Table::ConstIter clast = constant.end(); + --clast; TEST_EQ(clast->key(), oldLast->key()); + typename Table::ConstIter coldLast = clast--; TEST_NE(coldLast, clast); + --clast; TEST_EQ(clast, constant.begin()); + Table other; TEST_NE(table.end(), other.end()); + size_t visited = 0; int sum = 0; + for(typename Table::ConstIter scan = constant.begin(); scan != constant.end(); ++scan){ + ++visited; sum += scan->key(); + } + TEST_EQ(visited, (size_t)3); TEST_EQ(sum, 24); + + HashTestName(name, "keys/copy construction/copy assignment"); + Array keys = table.keys(); TEST_EQ(keys.size(), (size_t)3); + TEST_NE(keys.indexOf(0), NPOS); TEST_NE(keys.indexOf(8), NPOS); + TEST_NE(keys.indexOf(16), NPOS); TEST_EQ(keys.indexOf(999), NPOS); + Table copy(table); TEST_EQ(copy.size(), table.size()); + TEST_EQ(copy.erase(8), true); TEST_EQ(copy.has(8), false); + TEST_EQ(table.has(8), true); + Table assigned; assigned.insert(99); assigned = table; + TEST_EQ(assigned.has(99), false); TEST_EQ(assigned.size(), (size_t)3); + assigned.clear(); TEST_EQ(table.size(), (size_t)3); + Table emptyCopy(assigned); TEST_EQ(emptyCopy.empty(), true); + + HashTestName(name, "erase key/iterator/collision chain"); + TEST_EQ(table.erase(8), true); TEST_EQ(table.erase(8), false); + TEST_EQ(table.has(0), true); TEST_EQ(table.has(16), true); + TEST_EQ(table.size(), (size_t)2); + TEST_EQ(table.erase(table.end()), table.end()); + other.insert(5); TEST_EQ(table.erase(other.begin()), table.end()); + TEST_EQ(table.size(), (size_t)2); + typename Table::Iter next = table.erase(table.find(0)); + TEST_EQ(table.has(0), false); TEST_EQ(table.has(16), true); + TEST_NE(next, table.end()); + if(next != table.end()) TEST_EQ(next->key(), 16); + table.erase(next); TEST_EQ(table.empty(), true); + TEST_EQ(table.erase(100), false); + + HashTestName(name, "operator[] existing/default insertion"); + table.insert(4, 40); TEST_EQ(table[4], isSet ? 4 : 40); + TEST_EQ(table[12], isSet ? 12 : 0); TEST_EQ(table.size(), (size_t)2); + TEST_EQ(table[12], isSet ? 12 : 0); TEST_EQ(table.size(), (size_t)2); + if(!isSet){ table[4] = 41; TEST_EQ(constant.at(4), 41); } + TEST_EQ(table.has(12), true); + + HashTestName(name, "assign one/multiple/empty/self"); + Table source; source.insert(4, 400); source.insert(7, 70); + Table& merged = Table::assign(table, source); TEST_EQ(&merged, &table); + TEST_EQ(table.at(4), isSet ? 4 : 400); TEST_EQ(table.has(7), true); + Table emptySource; Table::assign(table, emptySource); + TEST_EQ(table.size(), (size_t)3); + Table::assign(table, table); TEST_EQ(table.size(), (size_t)3); + Array sources; Table::assign(table, sources); + TEST_EQ(table.size(), (size_t)3); + Table source2; source2.insert(4, 444); source2.insert(9, 90); + sources.push(source); sources.push(source2); + Table& multiMerged = Table::assign(table, sources); TEST_EQ(&multiMerged, &table); + TEST_EQ(table.at(4), isSet ? 4 : 444); TEST_EQ(table.has(9), true); + TEST_EQ(table.size(), (size_t)4); + + HashTestName(name, "clear/reuse/debug/type"); + TEST_EQ(table.toString(), table.cout()); TEST_EQ(table.type(), "map"); + TEST_NE(table.cout(), "{}"); + table.clear(); TEST_EQ(table.size(), (size_t)0); TEST_EQ(table.empty(), true); + TEST_EQ(table.begin(), table.end()); TEST_EQ(table.keys().empty(), true); + TEST_EQ(table.cout(), "{}"); TEST_EQ(table.toString(), "{}"); + TEST_EQ(table.type(), "map"); TEST_EQ(table.has(4), false); + table.clear(); TEST_EQ(table.empty(), true); + table.insert(22, 220); TEST_EQ(table.size(), (size_t)1); + TEST_EQ(table.at(22), isSet ? 22 : 220); + + HashTestName(name, "rehash and wrapped collision deletion"); + table.clear(); + for(int i = 0; i < 100; ++i) TEST_EQ(table.insert(i * 8 + 7, i + 1).second, true); + TEST_EQ(table.size(), (size_t)100); + for(int i = 0; i < 100; ++i){ + TEST_EQ(table.has(i * 8 + 7), true); + TEST_EQ(table.at(i * 8 + 7), isSet ? i * 8 + 7 : i + 1); + } + for(int i = 0; i < 100; i += 2) TEST_EQ(table.erase(i * 8 + 7), true); + TEST_EQ(table.size(), (size_t)50); + for(int i = 0; i < 100; ++i) TEST_EQ(table.has(i * 8 + 7), i % 2 == 1); + table.clear(); table.insert(7); table.insert(15); table.insert(23); + TEST_EQ(table.erase(7), true); TEST_EQ(table.has(15), true); + TEST_EQ(table.has(23), true); TEST_EQ(table.has(7), false); + + HashTestName(name, "deterministic mixed operations against reference model"); + table.clear(); bool present[31] = {false}; int values[31] = {0}; + for(int step = 0; step < 350; ++step){ + int index = (step * 17) % 31, key = index * 8, value = step + 10; + switch(step % 4){ + case 0: { + bool fresh = !present[index]; + TEST_EQ(table.insert(key, value).second, fresh); + if(fresh){ present[index] = true; values[index] = isSet ? key : value; } + break; + } + case 1: TEST_EQ(table.erase(key), present[index]); present[index] = false; break; + case 2: + if(!present[index]){ present[index] = true; values[index] = isSet ? key : 0; } + TEST_EQ(table[key], values[index]); + if(!isSet){ table[key] = value; values[index] = value; } + break; + default: TEST_EQ(table.find(key) != table.end(), present[index]); break; + } + size_t expected = 0; + for(int j = 0; j < 31; ++j){ + TEST_EQ(table.has(j * 8), present[j]); + if(present[j]){ ++expected; TEST_EQ(table.at(j * 8), values[j]); } + } + TEST_EQ(table.size(), expected); + if(step % 67 == 66){ table.clear(); for(int j = 0; j < 31; ++j) present[j] = false; } + } +} + +struct HashTrackedValue { + static int alive; int value; + HashTrackedValue(int v = 0) : value(v){ ++alive; } + HashTrackedValue(const HashTrackedValue& other) : value(other.value){ ++alive; } + ~HashTrackedValue(){ --alive; } + HashTrackedValue& operator=(const HashTrackedValue& other){ value = other.value; return *this; } +}; +int HashTrackedValue::alive = 0; + +void HashMap_test(){ + NextTest("hash/Fnv1a published vectors and length-aware binary inputs"); + TEST_EQ(Fnv1a("", 0), 2166136261U); TEST_EQ(Fnv1a("a", 1), 0xe40c292cU); + TEST_EQ(Fnv1a("foobar", 6), 0xbf9cf968U); + TEST_EQ(Fnv1a_64("", 0), 14695981039346656037ULL); + TEST_EQ(Fnv1a_64("a", 1), 0xaf63dc4c8601ec8cULL); + TEST_EQ(Fnv1a_64("foobar", 6), 0x85944171f73967e8ULL); + const char binary[] = {'a', 0, 'b'}; + TEST_EQ(Fnv1a(binary, 3), 0x10f3abd2U); + TEST_EQ(Fnv1a_64(binary, 3), 0xe5d29919042666b2ULL); + TEST_EQ(ncpp::hash("hello"), 0x4f9f2cabU); + TEST_EQ(ncpp::hash(String("hello")), 0x4f9f2cabU); + TEST_EQ(ncpp::hash(CString("hello")), 0x4f9f2cabU); + TEST_EQ(ncpp::hash(Buffer("hello")), 0x4f9f2cabU); + TEST_EQ(ncpp::hash(String(binary, 3)), 0x10f3abd2U); + TEST_EQ(ncpp::hash(CString(binary, 3)), 0x10f3abd2U); + TEST_EQ(ncpp::hash(Buffer(binary, 3)), 0x10f3abd2U); + TEST_NE(ncpp::hash(String(binary, 3)), ncpp::hash("a")); + TEST_EQ(ncpp::hash(String()), 2166136261U); + TEST_EQ(ncpp::hash(CString()), 2166136261U); + TEST_EQ(ncpp::hash(Buffer()), 2166136261U); + TEST_EQ(ncpp::hash(0), 0U); TEST_EQ(ncpp::hash(-1), 0xffffffffU); + int number = 0; int* pointer = &number; int* nullPointer = NULL; + TEST_EQ(ncpp::hash(pointer), ncpp::hash(&number)); + TEST_EQ(ncpp::hash(nullPointer), 0U); + + HashContainer_test >("HashMap", false); + HashContainer_test >("HashSet", true); + + NextTest("HashMap/HashSet toJSON empty and nonempty objects"); + HashMap numbers; TEST_EQ(numbers.toJSON(), "{}"); + numbers.insert("answer", 42); TEST_EQ(numbers.toJSON(), "{\"answer\":42}"); + numbers.clear(); TEST_EQ(numbers.toJSON(), "{}"); + HashSet set; TEST_EQ(set.toJSON(), "{}"); + set.insert(7); TEST_EQ(set.toJSON(), "{\"7\":7}"); + numbers.insert("other", -2); + String multiple = numbers.toJSON(); + TEST_EQ(multiple == "{\"other\":-2}" , true); + numbers.insert("answer", 42); multiple = numbers.toJSON(); + TEST_EQ(multiple == "{\"answer\":42,\"other\":-2}" || + multiple == "{\"other\":-2,\"answer\":42}", true); + + NextTest("HashMap toJSON string escaping and embedded NUL"); + StringMap strings; strings.insert("a\"b\\c", "line\n\t\r\b\f\"\\"); + TEST_EQ(strings.toJSON(), "{\"a\\\"b\\\\c\":\"line\\n\\t\\r\\b\\f\\\"\\\\\"}"); + strings.clear(); strings.insert(String(binary, 3), String("\x01\x1f", 2)); + TEST_EQ(strings.toJSON(), "{\"a\\u0000b\":\"\\u0001\\u001f\"}"); + HashSet stringSet; stringSet.insert("x\"y"); + TEST_EQ(stringSet.toJSON(), "{\"x\\\"y\":\"x\\\"y\"}"); + + NextTest("HashMap toJSON native booleans and fractional values"); + HashMap flags; flags.insert("ok", true); + TEST_EQ(flags.toJSON(), "{\"ok\":true}"); flags["ok"] = false; + TEST_EQ(flags.toJSON(), "{\"ok\":false}"); + DoubleMap decimals; decimals.insert("value", 1.25); + TEST_EQ(decimals.toJSON(), "{\"value\":1.25}"); + decimals["value"] = 1e30; + TEST_EQ(decimals.toJSON(), "{\"value\":1e+30}"); + HashMap floats; floats.insert("value", -1.25f); + TEST_EQ(floats.toJSON(), "{\"value\":-1.25}"); + floats["value"] = 0.0f; TEST_EQ(floats.toJSON(), "{\"value\":0}"); + union { unsigned long long bits; double number; } nonfinite; + nonfinite.bits = D_NAN; decimals["value"] = nonfinite.number; + TEST_EQ(decimals.toJSON(), "{\"value\":null}"); + nonfinite.bits = D_INF; decimals["value"] = nonfinite.number; + TEST_EQ(decimals.toJSON(), "{\"value\":null}"); + nonfinite.bits = D_NINF; decimals["value"] = nonfinite.number; + TEST_EQ(decimals.toJSON(), "{\"value\":null}"); + + NextTest("HashMap toJSON integer limits, CString and null C string"); + ULLMap maximum; maximum.insert("value", ULLONG_MAX); + TEST_EQ(maximum.toJSON(), "{\"value\":18446744073709551615}"); + LLMap minimum; minimum.insert("value", LLONG_MIN); + TEST_EQ(minimum.toJSON(), "{\"value\":-9223372036854775808}"); + HashMap views; views.insert("view", CString("a\"b")); + TEST_EQ(views.toJSON(), "{\"view\":\"a\\\"b\"}"); + HashMap pointers; pointers.insert("value", (const char*)NULL); + TEST_EQ(pointers.toJSON(), "{\"value\":null}"); + pointers["value"] = "text"; + TEST_EQ(pointers.toJSON(), "{\"value\":\"text\"}"); + char mutableText[] = "a\"b"; + HashMap mutablePointers; mutablePointers.insert("value", mutableText); + TEST_EQ(mutablePointers.toJSON(), "{\"value\":\"a\\\"b\"}"); + mutablePointers["value"] = NULL; TEST_EQ(mutablePointers.toJSON(), "{\"value\":null}"); + HashMap longs; longs.insert("value", LONG_MIN); + TEST_EQ(longs.toJSON(), sizeof(long) == 8 ? "{\"value\":-9223372036854775808}" : + "{\"value\":-2147483648}"); + + NextTest("HashMap/HashSet string-key assignment and missing at fallback"); + StringMap left, right; left.insert("old", "keep"); right.insert("new", "value"); + StringMap::assign(left, right); TEST_EQ(left.at("old"), "keep"); + TEST_EQ(left.at("new"), "value"); TEST_EQ(left.has("missing"), false); + TEST_EQ(left.at("missing"), left.begin()->value()); + HashSet setLeft, setRight; setLeft.insert("old"); setRight.insert("new"); + HashSet::assign(setLeft, setRight); TEST_EQ(setLeft.has("old"), true); + TEST_EQ(setLeft.has("new"), true); TEST_EQ(setLeft.has("missing"), false); + TEST_EQ(setLeft.at("missing"), setLeft.begin()->value()); + + NextTest("HashMap value lifetime through rehash/copy/erase/clear"); + int baseline = HashTrackedValue::alive; + { + HashMap tracked; + for(int i = 0; i < 40; ++i) tracked.insert(i, HashTrackedValue(i)); + HashMap copy(tracked); + TEST_EQ(copy.at(17).value, 17); copy.erase(17); + TEST_EQ(tracked.has(17), true); tracked.clear(); + TEST_EQ(tracked.empty(), true); copy.clear(); + } + TEST_EQ(HashTrackedValue::alive, baseline); +} diff --git a/tests/units/module-base.cpp b/tests/units/module-base.cpp index 7413ca5..6bac710 100644 --- a/tests/units/module-base.cpp +++ b/tests/units/module-base.cpp @@ -442,11 +442,13 @@ void Date_test(){ } +#include "hashmap-test.cpp" + void Module_Base_test(){ Array_test(); String_test(); ///Dtos_test(); Buffer_test(); - ///HashMap_test(); + HashMap_test(); Date_test(); -} \ No newline at end of file +}