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