Path: blob/main/system/lib/llvm-libc/src/stdlib/l64a.cpp
6175 views
//===-- Implementation of l64a --------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "src/stdlib/l64a.h"9#include "hdr/types/size_t.h"10#include "src/__support/common.h"11#include "src/__support/ctype_utils.h"12#include "src/__support/libc_assert.h"13#include "src/__support/macros/config.h"1415#include <stdint.h>1617namespace LIBC_NAMESPACE_DECL {1819// 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];2425constexpr 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]."29LIBC_ASSERT(num < 64);30if (num == 0)31return '.';32if (num == 1)33return '/';34if (num < 38)35return static_cast<char>(36internal::toupper(internal::int_to_b36_char(num - 2)));3738// this tolower is technically unnecessary, but it provides safety if we39// change the default behavior of int_to_b36_char. Also the compiler40// completely elides it so there's no performance penalty, see:41// https://godbolt.org/z/o5ennv7fc42return static_cast<char>(43internal::tolower(internal::int_to_b36_char(num - 2 - 26)));44}4546// This function takes a long and converts the low 32 bits of it into at most 647// characters. It's returned as a pointer to a static buffer.48LLVM_LIBC_FUNCTION(char *, l64a, (long value)) {49// static cast to uint32_t to get just the low 32 bits in a consistent way.50// The standard says negative values are undefined, so I'm just defining them51// to be treated as unsigned.52uint32_t cur_value = static_cast<uint32_t>(value);53for (size_t i = 0; i < MAX_BASE64_LENGTH; ++i) {54uint32_t cur_char = cur_value % 64;55BASE64_BUFFER[i] = b64_int_to_char(cur_char);56cur_value /= 64;57}5859BASE64_BUFFER[MAX_BASE64_LENGTH] = '\0'; // force null termination.60return BASE64_BUFFER;61}6263} // namespace LIBC_NAMESPACE_DECL646566