1 //===-- Shared Converter Utilities for printf -------------------*- 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 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLVM_LIBC_SRC_STDIO_PRINTF_CORE_CONVERTER_UTILS_H
10 #define LLVM_LIBC_SRC_STDIO_PRINTF_CORE_CONVERTER_UTILS_H
11 
12 #include "src/__support/CPP/Limits.h"
13 #include "src/stdio/printf_core/core_structs.h"
14 
15 #include <inttypes.h>
16 #include <stddef.h>
17 
18 namespace __llvm_libc {
19 namespace printf_core {
20 
apply_length_modifier(uintmax_t num,LengthModifier lm)21 inline uintmax_t apply_length_modifier(uintmax_t num, LengthModifier lm) {
22   switch (lm) {
23   case LengthModifier::none:
24     return num & cpp::NumericLimits<unsigned int>::max();
25   case LengthModifier::l:
26     return num & cpp::NumericLimits<unsigned long>::max();
27   case LengthModifier::ll:
28   case LengthModifier::L:
29     return num & cpp::NumericLimits<unsigned long long>::max();
30   case LengthModifier::h:
31     return num & cpp::NumericLimits<unsigned short>::max();
32   case LengthModifier::hh:
33     return num & cpp::NumericLimits<unsigned char>::max();
34   case LengthModifier::z:
35     return num & cpp::NumericLimits<size_t>::max();
36   case LengthModifier::t:
37     // We don't have unsigned ptrdiff so uintptr_t is used, since we need an
38     // unsigned type and ptrdiff is usually the same size as a pointer.
39     static_assert(sizeof(ptrdiff_t) == sizeof(uintptr_t));
40     return num & cpp::NumericLimits<uintptr_t>::max();
41   case LengthModifier::j:
42     return num; // j is intmax, so no mask is necessary.
43   }
44 }
45 
46 #define RET_IF_RESULT_NEGATIVE(func)                                           \
47   {                                                                            \
48     int result = (func);                                                       \
49     if (result < 0)                                                            \
50       return result;                                                           \
51   }
52 
53 } // namespace printf_core
54 } // namespace __llvm_libc
55 
56 #endif // LLVM_LIBC_SRC_STDIO_PRINTF_CORE_CONVERTER_UTILS_H
57