]> git.ipfire.org Git - thirdparty/gcc.git/blob - libstdc++-v3/testsuite/20_util/from_chars/1.cc
Update copyright years.
[thirdparty/gcc.git] / libstdc++-v3 / testsuite / 20_util / from_chars / 1.cc
1 // Copyright (C) 2017-2020 Free Software Foundation, Inc.
2 //
3 // This file is part of the GNU ISO C++ Library. This library is free
4 // software; you can redistribute it and/or modify it under the
5 // terms of the GNU General Public License as published by the
6 // Free Software Foundation; either version 3, or (at your option)
7 // any later version.
8
9 // This library is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
13
14 // You should have received a copy of the GNU General Public License along
15 // with this library; see the file COPYING3. If not see
16 // <http://www.gnu.org/licenses/>.
17
18 // { dg-options "-std=gnu++17" }
19 // { dg-do run { target c++17 } }
20
21 #include <charconv>
22 #include <string_view>
23
24 template<typename I>
25 bool
26 check_from_chars(I expected, std::string_view s, int base = 0, char term = '\0')
27 {
28 I val;
29 std::from_chars_result r = base == 0
30 ? std::from_chars(s.begin(), s.end(), val)
31 : std::from_chars(s.begin(), s.end(), val, base);
32 return r.ec == std::errc{} && (r.ptr == s.end() || *r.ptr == term) && val == expected;
33 }
34
35 #include <climits>
36 #include <testsuite_hooks.h>
37
38 void
39 test01()
40 {
41 // Using base 10
42 VERIFY( check_from_chars(123, "123") );
43 VERIFY( check_from_chars(-123, "-123") );
44 VERIFY( check_from_chars(123, "123a", 10, 'a') );
45 VERIFY( check_from_chars(123, "0000000000000000000000000000123") );
46 VERIFY( check_from_chars(123, "0000000000000000000000000000123a", 10, 'a') );
47 }
48
49 void
50 test02()
51 {
52 // "0x" parsed as "0" not as hex prefix:
53 VERIFY( check_from_chars(0, "0x1", 10, 'x') );
54 VERIFY( check_from_chars(0, "0X1", 10, 'X') );
55 VERIFY( check_from_chars(0, "0x1", 16, 'x') );
56 VERIFY( check_from_chars(0, "0X1", 16, 'X') );
57
58 VERIFY( check_from_chars(1155, "xx", 34) );
59 VERIFY( check_from_chars(1155, "XX", 34) );
60 VERIFY( check_from_chars(1155, "Xx", 34) );
61 VERIFY( check_from_chars(1224, "yy", 35) );
62 VERIFY( check_from_chars(1224, "YY", 35) );
63 VERIFY( check_from_chars(1224, "yY", 35) );
64 VERIFY( check_from_chars(1295, "zz", 36) );
65 VERIFY( check_from_chars(1295, "ZZ", 36) );
66 VERIFY( check_from_chars(1295, "Zz", 36) );
67
68 // Parsing stops at first invalid digit for the given base:
69 VERIFY( check_from_chars(1, "01234", 2, '2') );
70 VERIFY( check_from_chars(27, "1234", 4, '4') );
71 VERIFY( check_from_chars(1155, "xxy", 34, 'y') );
72 VERIFY( check_from_chars(1224, "yyz", 35, 'z') );
73 }
74
75 int
76 main()
77 {
78 test01();
79 test02();
80 }