[libc][NFC] Move aligned access implementations to separate header
[llvm-project.git] / libc / src / __support / FPUtil / fpbits_str.h
blob475b582d0508210b17706a8a07b3d44c5dd24c01
1 //===------ Pretty print function for FPBits --------------------*- C++ -*-===//
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 //===----------------------------------------------------------------------===//
9 #ifndef LLVM_LIBC_SRC_SUPPORT_FPUTIL_FP_BITS_STR_H
10 #define LLVM_LIBC_SRC_SUPPORT_FPUTIL_FP_BITS_STR_H
12 #include "src/__support/CPP/string.h"
13 #include "src/__support/CPP/type_traits.h"
14 #include "src/__support/FPUtil/FPBits.h"
15 #include "src/__support/FPUtil/FloatProperties.h"
16 #include "src/__support/integer_to_string.h"
17 #include "src/__support/macros/attributes.h"
19 namespace __llvm_libc {
21 // Converts the bits to a string in the following format:
22 // "0x<NNN...N> = S: N, E: 0xNNNN, M:0xNNN...N"
23 // 1. N is a hexadecimal digit.
24 // 2. The hexadecimal number on the LHS is the raw numerical representation
25 // of the bits.
26 // 3. The exponent is always 16 bits wide irrespective of the type of the
27 // floating encoding.
28 template <typename T> LIBC_INLINE cpp::string str(fputil::FPBits<T> x) {
29 using UIntType = typename fputil::FPBits<T>::UIntType;
31 if (x.is_nan())
32 return "(NaN)";
33 if (x.is_inf())
34 return x.get_sign() ? "(-Infinity)" : "(+Infinity)";
36 auto zerofill = [](char *arr, size_t n) {
37 for (size_t i = 0; i < n; ++i)
38 arr[i] = '0';
41 cpp::string s("0x");
42 char bitsbuf[IntegerToString::hex_bufsize<UIntType>()];
43 zerofill(bitsbuf, sizeof(bitsbuf));
44 IntegerToString::hex(x.bits, bitsbuf, false);
45 s += cpp::string(bitsbuf, sizeof(bitsbuf));
47 s += " = (";
48 s += cpp::string("S: ") + (x.get_sign() ? "1" : "0");
50 char expbuf[IntegerToString::hex_bufsize<uint16_t>()];
51 zerofill(expbuf, sizeof(expbuf));
52 IntegerToString::hex(x.get_unbiased_exponent(), expbuf, false);
53 s += cpp::string(", E: 0x") + cpp::string(expbuf, sizeof(expbuf));
55 if constexpr (cpp::is_same_v<T, long double> &&
56 fputil::FloatProperties<long double>::MANTISSA_WIDTH == 63) {
57 s += cpp::string(", I: ") + (x.get_implicit_bit() ? "1" : "0");
60 char mantbuf[IntegerToString::hex_bufsize<UIntType>()] = {'0'};
61 zerofill(mantbuf, sizeof(mantbuf));
62 IntegerToString::hex(x.get_mantissa(), mantbuf, false);
63 s += cpp::string(", M: 0x") + cpp::string(mantbuf, sizeof(mantbuf));
65 s += ")";
66 return s;
69 } // namespace __llvm_libc
71 #endif // LLVM_LIBC_SRC_SUPPORT_FPUTIL_FP_BITS_STR_H