namespace BlurHash; /// /// Contains methods to encode or decode integers to Base83-Strings /// internal static class Base83 { internal const string _Charset = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~"; private static readonly IReadOnlyDictionary _ReverseLookup; static Base83() { // Build inverse lookup table for fast decoding Dictionary charIndices = []; int index = 0; foreach (char c in _Charset) { charIndices[c] = index; index++; } _ReverseLookup = charIndices; } /// /// Encodes a number into its Base83-representation /// /// The number to encode /// The data buffer to put the result data into /// The Base83-representation of the number public static void EncodeBase83(this int number, Span output) { int length = output.Length; for (int i = 0; i < length; i++) { int digit = number % 83; number /= 83; output[length - i - 1] = _Charset[digit]; } } /// /// Decodes an IEnumerable of Base83-characters into the integral value it represents /// /// The characters to decode /// The decoded value as integer public static int DecodeBase83(this ReadOnlySpan base83Data) { int result = 0; foreach (char c in base83Data) { if (!_ReverseLookup.TryGetValue(c, out int digit)) { throw new ArgumentException("The given string contains invalid characters.", nameof(base83Data)); } result *= 83; result += digit; } return result; } }