Read-only mirrors. Development, issues and pull requests are on GitHub.

summaryrefslogtreecommitdiffhomepage
path: root/src/catch2/internal/catch_parse_numbers.cpp
blob: 390b8c872a7eb7f2793c8d6ce5859bd57ba135f9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

//              Copyright Catch2 Authors
// Distributed under the Boost Software License, Version 1.0.
//   (See accompanying file LICENSE.txt or copy at
//        https://www.boost.org/LICENSE_1_0.txt)

// SPDX-License-Identifier: BSL-1.0

#include <catch2/internal/catch_parse_numbers.hpp>

#include <catch2/internal/catch_compiler_capabilities.hpp>
#include <catch2/internal/catch_string_manip.hpp>

#include <limits>

namespace Catch {

    Optional<unsigned int> parseUInt(std::string const& input, int base) {
        auto trimmed = trim( input );
        // std::stoull is annoying and accepts numbers starting with '-',
        // it just negates them into unsigned int
        if ( trimmed.empty() || trimmed[0] == '-' ) {
            return {};
        }

        CATCH_TRY {
            size_t pos = 0;
            const auto ret = std::stoull( trimmed, &pos, base );

            // We did not consume the whole input, so there is an issue
            // This can be bunch of different stuff, like multiple numbers
            // in the input, or invalid digits/characters and so on. Either
            // way, we do not want to return the partially parsed result.
            if ( pos != trimmed.size() ) {
                return {};
            }
            // Too large
            if ( ret > std::numeric_limits<unsigned int>::max() ) {
                return {};
            }
            return static_cast<unsigned int>(ret);
        } CATCH_CATCH_ANON( std::exception const& ) {
            // There was a larger issue with the input, e.g. the parsed
            // number would be too large to fit within ull.
            return {};
        }
    }

} // namespace Catch