mirror of https://github.com/dnomd343/klotski.git
Dnomd343
6 months ago
6 changed files with 56 additions and 40 deletions
@ -1,34 +1,38 @@ |
|||||
|
#include <ranges> |
||||
|
|
||||
#include "serialize_chars.h" |
#include "serialize_chars.h" |
||||
#include "short_code/short_code.h" |
#include "short_code/short_code.h" |
||||
|
|
||||
using klotski::codec::ShortCode; |
using klotski::codec::ShortCode; |
||||
|
using klotski::cases::ALL_CASES_NUM_; |
||||
|
|
||||
std::string ShortCode::string_encode(uint32_t short_code) { |
std::string ShortCode::string_encode(uint32_t short_code) { |
||||
char result[5]; |
KLSK_ASSUME(short_code < ALL_CASES_NUM_); |
||||
for (int n = 0; n < 5; ++n) { |
std::array<char, 5> arr {}; |
||||
result[4 - n] = SHORT_CODE_TABLE[short_code & 0b11111]; |
for (auto &c : arr | std::views::reverse) { |
||||
|
c = SHORT_CODE_TABLE[short_code & 0b11111]; // table convert
|
||||
short_code >>= 5; |
short_code >>= 5; |
||||
} |
} |
||||
return {result, result + 5}; |
return {arr.begin(), arr.end()}; |
||||
} |
} |
||||
|
|
||||
std::optional<uint32_t> ShortCode::string_decode(const std::string_view short_code) { |
std::optional<uint32_t> ShortCode::string_decode(const std::string_view short_code) { |
||||
if (short_code.length() != 5) { |
if (short_code.length() != 5) { |
||||
return std::nullopt; // invalid string length
|
return std::nullopt; // invalid string length
|
||||
} |
} |
||||
uint32_t result = 0; |
uint32_t code = 0; |
||||
for (auto bit : short_code) { |
for (const uint8_t bit : short_code) { |
||||
if (bit < '1' || bit > 'z') { // invalid characters
|
if (bit > 'z') { // invalid characters
|
||||
return std::nullopt; |
return std::nullopt; |
||||
} |
} |
||||
result <<= 5; |
if (const auto val = SHORT_CODE_TABLE_REV[bit]; val != -1) { |
||||
result += (bit = SHORT_CODE_TABLE_REV[bit - 49]); // table convert
|
(code <<= 5) += val; |
||||
if (bit == -1) { // invalid character
|
continue; |
||||
return std::nullopt; |
|
||||
} |
} |
||||
|
return std::nullopt; // invalid character
|
||||
} |
} |
||||
if (!check(result)) { // check converted short code
|
if (!check(code)) { // check converted short code
|
||||
return std::nullopt; |
return std::nullopt; |
||||
} |
} |
||||
return result; // apply convert result
|
return code; // apply convert result
|
||||
} |
} |
||||
|
Loading…
Reference in new issue