1// Copyright 2020 The Pigweed Authors 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); you may not 4// use this file except in compliance with the License. You may obtain a copy of 5// the License at 6// 7// https://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12// License for the specific language governing permissions and limitations under 13// the License. 14#pragma once 15 16#include <limits.h> 17 18#include "pw_polyfill/standard_library/namespace.h" 19 20_PW_POLYFILL_BEGIN_NAMESPACE_STD 21 22template <typename T> 23struct numeric_limits { 24 static constexpr bool is_specialized = false; 25 static constexpr int digits = 0; 26}; 27 28// Only a few of the numeric_limits methods are implemented. 29#define _PW_LIMITS_SPECIALIZATION( \ 30 type, val_signed, val_int, min_value, max_value, digits_value) \ 31 template <> \ 32 struct numeric_limits<type> { \ 33 static constexpr bool is_specialized = true; \ 34 \ 35 static constexpr bool is_signed = (val_signed); \ 36 static constexpr bool is_integer = (val_int); \ 37 \ 38 static constexpr int digits = (digits_value); \ 39 \ 40 static constexpr type min() noexcept { return (min_value); } \ 41 static constexpr type max() noexcept { return (max_value); } \ 42 } 43 44#define _PW_INTEGRAL_LIMIT(type, sname, uname) \ 45 _PW_LIMITS_SPECIALIZATION(signed type, \ 46 true, \ 47 true, \ 48 sname##_MIN, \ 49 sname##_MAX, \ 50 CHAR_BIT * sizeof(type)); \ 51 _PW_LIMITS_SPECIALIZATION(unsigned type, \ 52 false, \ 53 true, \ 54 0u, \ 55 uname##_MAX, \ 56 CHAR_BIT * sizeof(type) - 1) 57 58_PW_LIMITS_SPECIALIZATION(bool, false, true, false, true, 1); 59_PW_LIMITS_SPECIALIZATION( 60 char, char(-1) < char(0), true, CHAR_MIN, CHAR_MAX, 1); 61 62_PW_INTEGRAL_LIMIT(char, SCHAR, UCHAR); 63_PW_INTEGRAL_LIMIT(short, SHRT, USHRT); 64_PW_INTEGRAL_LIMIT(int, INT, UINT); 65_PW_INTEGRAL_LIMIT(long, LONG, ULONG); 66 67#ifndef LLONG_MIN 68#define LLONG_MIN ((long long)(~0ull ^ (~0ull >> 1))) 69#define LLONG_MAX ((long long)(~0ull >> 1)) 70 71#define ULLONG_MIN (0ull) 72#define ULLONG_MAX (~0ull) 73#endif // LLONG_MIN 74 75_PW_INTEGRAL_LIMIT(long long, LLONG, ULLONG); 76 77#undef _PW_LIMITS_SPECIALIZATION 78#undef _PW_INTEGRAL_LIMIT 79 80_PW_POLYFILL_END_NAMESPACE_STD 81