From f42d83709bd7223776397a6de5924d1396d9bbfd Mon Sep 17 00:00:00 2001 From: forgotthepen Date: Fri, 6 Sep 2024 20:18:37 +0300 Subject: [PATCH] test clear() --- str-to-num.hpp | 15 ++++++++------- test/test.cpp | 15 +++++++++++++++ 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/str-to-num.hpp b/str-to-num.hpp index 2cc76b2..952a680 100644 --- a/str-to-num.hpp +++ b/str-to-num.hpp @@ -210,7 +210,8 @@ class s2n_basic { TOut m_data{}; public: - // use a container since TConverter::to_str() will return an array + // container for the decrypted/restored string + // using a container since TConverter::to_str() will return an array struct str_container { constexpr static s2n_sz_t count = str_count; TChar data[str_count + 1]{}; @@ -218,13 +219,13 @@ class s2n_basic { constexpr void clear() { for (s2n_sz_t idx = 0; idx < str_count; ++idx) { // data[idx] = TChar(); // easy to detect - data[idx] += str_count ^ (idx + 1); - data[idx] *= idx + 2; + data[idx] += str_count ^ (idx + 3); + data[idx] *= idx + 3; data[idx] ^= idx + 3; } - data[str_count] = str_count * (data[0] + 1); - data[str_count] ^= (data[0] - 1); + data[str_count] = str_count * (data[0] + 3); + data[str_count] ^= (data[0] - 3); } // constant destruction is available since C++20: https://en.cppreference.com/w/cpp/language/constexpr @@ -282,7 +283,7 @@ namespace s2n_cvt { constexpr static void to_num(TChar (&dst) [StrCount], const TStr& src) noexcept { for (s2n_sz_t src_idx = 0; src_idx < StrCount; ++src_idx) { const auto key2 = (StrCount << (src_idx + 3)) | (src_idx + 3); - dst[src_idx] = src[src_idx] ^ static_cast(VKey ^ src_idx) ^ static_cast(key2); + dst[src_idx] = static_cast(src[src_idx] ^ VKey ^ (src_idx + 12) ^ key2); } } @@ -290,7 +291,7 @@ namespace s2n_cvt { constexpr static void to_str(TChar (&dst) [StrCount + 1], const TChar (&src) [StrCount]) noexcept { for (s2n_sz_t src_idx = 0; src_idx < StrCount; ++src_idx) { const auto key2 = (StrCount << (src_idx + 3)) | (src_idx + 3); - dst[src_idx] = src[src_idx] ^ static_cast(VKey ^ src_idx) ^ static_cast(key2); + dst[src_idx] = static_cast(src[src_idx] ^ VKey ^ (src_idx + 12) ^ key2); } } }; diff --git a/test/test.cpp b/test/test.cpp index e64bb96..58e3f8c 100644 --- a/test/test.cpp +++ b/test/test.cpp @@ -89,6 +89,21 @@ int main() std::cout << std::hex << "FNV 1a = 0x" << smsm33.data() << std::endl; } + { + constexpr auto clear_me_after_use = s2n("my super secret"); + + { + constexpr auto actual_str_constexpr = clear_me_after_use.str(); + static_assert(same_str_data(actual_str_constexpr.data, "my super secret"), "error"); + } + + auto actual_str = clear_me_after_use.str(); + std::cout << std::hex << "actual str = [" << actual_str.data << "]" << std::endl; + actual_str.clear(); // CANNOT BE RECOVERED + // invalid use, we have to call .str() again to get a new instance + // std::cout << std::hex << "actual str = [" << actual_str.data << "]" << std::endl; + } + using tt1 = str_char_t; using tt2 = str_char_t;