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