1 //===----------------------------------------------------------------------===//
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 #include <cassert>
10 #include <limits>
11 #include <sstream>
12 #include <string>
13 #include <type_traits>
14 
15 #include "test_macros.h"
16 
17 template <class T>
check_stream_failed(std::string const & val)18 bool check_stream_failed(std::string const& val) {
19     std::istringstream ss(val);
20     T result;
21     return !(ss >> result);
22 }
23 
24 template<typename T>
check_limits()25 void check_limits()
26 {
27     const bool is_unsigned = std::is_unsigned<T>::value;
28     T minv = std::numeric_limits<T>::min();
29     T maxv = std::numeric_limits<T>::max();
30 
31     std::ostringstream miniss, maxiss;
32     assert(miniss << minv);
33     assert(maxiss << maxv);
34     std::string mins = miniss.str();
35     std::string maxs = maxiss.str();
36 
37     std::istringstream maxoss(maxs), minoss(mins);
38 
39     T new_minv, new_maxv;
40     assert(maxoss >> new_maxv);
41     assert(minoss >> new_minv);
42 
43     assert(new_minv == minv);
44     assert(new_maxv == maxv);
45 
46     maxs[maxs.size() - 1]++;
47     assert(check_stream_failed<T>(maxs));
48     if (!is_unsigned) {
49         mins[mins.size() - 1]++;
50         assert(check_stream_failed<T>(mins));
51     }
52 }
53 
main(int,char **)54 int main(int, char**)
55 {
56     check_limits<short>();
57     check_limits<unsigned short>();
58     check_limits<int>();
59     check_limits<unsigned int>();
60     check_limits<long>();
61     check_limits<unsigned long>();
62     check_limits<long long>();
63     check_limits<unsigned long long>();
64 
65   return 0;
66 }
67