From fb1518484889bdf532ba29727c80b23fecb77d68 Mon Sep 17 00:00:00 2001 From: SEK1RO Date: Sun, 29 Sep 2024 13:33:38 +0300 Subject: [PATCH] feat(baseN): digitsMap --- Makefile | 1 + include/basen/baseN.hpp | 7 +++++++ src/baseN.cpp | 12 ++++++++++++ test/test-baseN.cpp | 8 ++++++++ 4 files changed, 28 insertions(+) diff --git a/Makefile b/Makefile index b309bad..25f730f 100644 --- a/Makefile +++ b/Makefile @@ -83,6 +83,7 @@ docs: cover: ${DIRS} ${patsubst %, ${BINDIR}/%${-g}-cov, ${TESTS}} rm -f **/*.gcda ${patsubst %, ./${BINDIR}/%${-g}-cov;, ${TESTS}} + mkdir cov gcovr --html-nested cov/index.html --txt --exclude-throw-branches ${OBJDIR}/%${-g}-cov.o: ${SRCDIR}/%.cpp ${INCDIR}/${LIB}/%.hpp diff --git a/include/basen/baseN.hpp b/include/basen/baseN.hpp index fe8a9d3..ced5997 100644 --- a/include/basen/baseN.hpp +++ b/include/basen/baseN.hpp @@ -7,6 +7,13 @@ namespace baseN { + /** + * @param digits char[base] array of digits + * @param digits_size size of digits array. Equals to base + * @param map [out] int8_t[256] array, where at an index equal to the value of the symbol is the index of this symbol in the digits array. -1 if there is no symbol + * @throw std::logic_error if alphabet contain same chars + */ + void digitsMap(const char *digits, uint8_t digits_size, int8_t *map); /** * @param str [in] pointer to string * @param str_size diff --git a/src/baseN.cpp b/src/baseN.cpp index c3b2349..e38ca30 100644 --- a/src/baseN.cpp +++ b/src/baseN.cpp @@ -9,6 +9,18 @@ static constexpr auto log256 = std::log(256); namespace baseN { + void digitsMap(const char *digits, uint8_t digits_size, int8_t *map) + { + std::fill(map, map + 256, -1); + for (uint8_t i = 0; i < digits_size; i++) + { + if (map[(int8_t)digits[i]] != -1) + { + throw std::logic_error("baseN::digitsMap: alphabet contain same chars"); + } + map[(int8_t)digits[i]] = i; + } + } bool isValid(const char *str, uint64_t str_size, const int8_t *map) noexcept { return std::all_of(str, str + str_size, [map](char ch) diff --git a/test/test-baseN.cpp b/test/test-baseN.cpp index e8e4834..10a35d5 100644 --- a/test/test-baseN.cpp +++ b/test/test-baseN.cpp @@ -7,6 +7,14 @@ using namespace baseN; +TEST(baseN, digitsMap) +{ + int8_t map[256]; + digitsMap(base58::digits, 58, map); + EXPECT_TRUE(std::equal(map, map + 256, base58::map)); + + EXPECT_THROW(digitsMap("11", 2, map), std::logic_error); +} TEST(baseN, isValid) { std::vector> tests = {