65 lines · cpp
1//===-- Implementation of a64l --------------------------------------------===//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/a64l.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/macros/config.h"15 16namespace LIBC_NAMESPACE_DECL {17 18// I'm not sure this should go in ctype_utils since the specific ordering of19// base64 is so very implementation specific, and also this set is unusual.20// Returns -1 on any char without a specified value.21constexpr static int32_t b64_char_to_int(char ch) {22 // from the standard: "The characters used to represent digits are '.' (dot)23 // for 0, '/' for 1, '0' through '9' for [2,11], 'A' through 'Z' for [12,37],24 // and 'a' through 'z' for [38,63]."25 if (ch == '.')26 return 0;27 if (ch == '/')28 return 1;29 30 // handle the case of an unspecified char.31 if (!internal::isalnum(ch))32 return -1;33 34 bool is_lower = internal::islower(ch);35 // add 2 to account for '.' and '/', then b36_char_to_int is case insensitive36 // so add case sensitivity back.37 return internal::b36_char_to_int(ch) + 2 + (is_lower ? 26 : 0);38}39 40// This function takes a base 64 string and writes it to the low 32 bits of a41// long.42// TODO: use LIBC_ADD_NULL_CHECKS for checking if the input is a null pointer.43LLVM_LIBC_FUNCTION(long, a64l, (const char *s)) {44 // the standard says to only use up to 6 characters.45 constexpr size_t MAX_LENGTH = 6;46 int32_t result = 0;47 48 for (size_t i = 0; i < MAX_LENGTH && s[i] != '\0'; ++i) {49 int32_t cur_val = b64_char_to_int(s[i]);50 // The standard says what happens on an unspecified character is undefined,51 // here we treat it as the end of the string.52 if (cur_val == -1)53 break;54 55 // the first digit is the least significant, so for each subsequent digit we56 // shift it more. 6 bits since 2^6 = 6457 result += (cur_val << (6 * i));58 }59 60 // standard says to sign extend from 32 bits.61 return static_cast<long>(result);62}63 64} // namespace LIBC_NAMESPACE_DECL65