| 1 | //===-- Implementation of l64a --------------------------------------------===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | #include "src/stdlib/l64a.h" |
| 10 | #include "hdr/types/size_t.h" |
| 11 | #include "src/__support/common.h" |
| 12 | #include "src/__support/ctype_utils.h" |
| 13 | #include "src/__support/libc_assert.h" |
| 14 | #include "src/__support/macros/config.h" |
| 15 | |
| 16 | #include <stdint.h> |
| 17 | |
| 18 | namespace LIBC_NAMESPACE_DECL { |
| 19 | |
| 20 | // the standard says to only use up to 6 characters. Null terminator is |
| 21 | // unnecessary, but we'll add it for ease-of-use. Also going from 48 -> 56 bits |
| 22 | // probably won't matter since it's likely 32-bit aligned anyways. |
| 23 | constexpr size_t MAX_BASE64_LENGTH = 6; |
| 24 | LIBC_THREAD_LOCAL char BASE64_BUFFER[MAX_BASE64_LENGTH + 1]; |
| 25 | |
| 26 | constexpr static char b64_int_to_char(uint32_t num) { |
| 27 | // from the standard: "The characters used to represent digits are '.' (dot) |
| 28 | // for 0, '/' for 1, '0' through '9' for [2,11], 'A' through 'Z' for [12,37], |
| 29 | // and 'a' through 'z' for [38,63]." |
| 30 | LIBC_ASSERT(num < 64); |
| 31 | if (num == 0) |
| 32 | return '.'; |
| 33 | if (num == 1) |
| 34 | return '/'; |
| 35 | if (num < 38) |
| 36 | return static_cast<char>( |
| 37 | internal::toupper(internal::int_to_b36_char(num - 2))); |
| 38 | |
| 39 | // this tolower is technically unnecessary, but it provides safety if we |
| 40 | // change the default behavior of int_to_b36_char. Also the compiler |
| 41 | // completely elides it so there's no performance penalty, see: |
| 42 | // https://godbolt.org/z/o5ennv7fc |
| 43 | return static_cast<char>( |
| 44 | internal::tolower(internal::int_to_b36_char(num - 2 - 26))); |
| 45 | } |
| 46 | |
| 47 | // This function takes a long and converts the low 32 bits of it into at most 6 |
| 48 | // characters. It's returned as a pointer to a static buffer. |
| 49 | LLVM_LIBC_FUNCTION(char *, l64a, (long value)) { |
| 50 | // static cast to uint32_t to get just the low 32 bits in a consistent way. |
| 51 | // The standard says negative values are undefined, so I'm just defining them |
| 52 | // to be treated as unsigned. |
| 53 | uint32_t cur_value = static_cast<uint32_t>(value); |
| 54 | for (size_t i = 0; i < MAX_BASE64_LENGTH; ++i) { |
| 55 | uint32_t cur_char = cur_value % 64; |
| 56 | BASE64_BUFFER[i] = b64_int_to_char(num: cur_char); |
| 57 | cur_value /= 64; |
| 58 | } |
| 59 | |
| 60 | BASE64_BUFFER[MAX_BASE64_LENGTH] = '\0'; // force null termination. |
| 61 | return BASE64_BUFFER; |
| 62 | } |
| 63 | |
| 64 | } // namespace LIBC_NAMESPACE_DECL |
| 65 | |