| 1 | // Copyright (C) 2020-2025 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-do run { target c++14 } } |
| 19 | |
| 20 | #include <charconv> |
| 21 | #include <string> |
| 22 | #include <testsuite_hooks.h> |
| 23 | |
| 24 | #ifdef DEBUG |
| 25 | #include <stdio.h> |
| 26 | #endif |
| 27 | |
| 28 | long long |
| 29 | read(const char* first, const char* last, int base) |
| 30 | { |
| 31 | long long val = 0; |
| 32 | unsigned long long place = 1; |
| 33 | while (last > first) |
| 34 | { |
| 35 | val += (*--last - '0') * place; |
| 36 | place *= base; |
| 37 | } |
| 38 | return val; |
| 39 | } |
| 40 | |
| 41 | void |
| 42 | test01() |
| 43 | { |
| 44 | std::from_chars_result res; |
| 45 | long long val; |
| 46 | for (auto s : { "10001", "10010", "10011", "10101", "10110", "10111", |
| 47 | "11001", "11010", "11011", "11101", "11110", "11111" }) |
| 48 | { |
| 49 | std::string ss[2] = { s, std::string(64, '0') + s }; |
| 50 | for (const auto& str : ss) |
| 51 | { |
| 52 | const char* first = str.data(); |
| 53 | for (int base = 2; base < 37; ++base) |
| 54 | { |
| 55 | const char* last = str.data() + str.length(); |
| 56 | for (size_t n = 0; n < ss[0].length(); ++n) |
| 57 | { |
| 58 | #ifdef DEBUG |
| 59 | printf("Parsing \"%.*s\" in base %d\n", int(last - first), first, |
| 60 | base); |
| 61 | #endif |
| 62 | res = std::from_chars(first, last, val, base); |
| 63 | VERIFY( res.ptr == last ); |
| 64 | VERIFY( res.ec == std::errc{} ); |
| 65 | VERIFY( val == read(first, last, base) ); |
| 66 | // Test again with shorter string to check from_chars doesn't read |
| 67 | // the digits past the last pointer. |
| 68 | --last; |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | int |
| 76 | main() |
| 77 | { |
| 78 | test01(); |
| 79 | } |