blob: 06ac9e9acdac77bca5de456b5138395f1cfb4394 [file] [log] [blame]
ossua280f7c2017-04-06 02:02:15 -07001/*
2 * Copyright 2017 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Danil Chapovalov6e9d8952018-04-09 20:30:51 +020011#include "rtc_base/string_to_number.h"
12
hugoh6baee782017-06-08 16:38:40 -070013#include <cerrno>
ossua280f7c2017-04-06 02:02:15 -070014#include <cstdlib>
15
Danil Chapovalov6e9d8952018-04-09 20:30:51 +020016#include "rtc_base/checks.h"
ossua280f7c2017-04-06 02:02:15 -070017
18namespace rtc {
19namespace string_to_number_internal {
20
Danil Chapovalov0a1d1892018-06-21 11:48:25 +020021absl::optional<signed_type> ParseSigned(const char* str, int base) {
ossua280f7c2017-04-06 02:02:15 -070022 RTC_DCHECK(str);
23 if (isdigit(str[0]) || str[0] == '-') {
24 char* end = nullptr;
25 errno = 0;
26 const signed_type value = std::strtoll(str, &end, base);
27 if (end && *end == '\0' && errno == 0) {
Oskar Sundbom9c780582017-11-27 10:28:22 +010028 return value;
ossua280f7c2017-04-06 02:02:15 -070029 }
30 }
Danil Chapovalov0a1d1892018-06-21 11:48:25 +020031 return absl::nullopt;
ossua280f7c2017-04-06 02:02:15 -070032}
33
Danil Chapovalov0a1d1892018-06-21 11:48:25 +020034absl::optional<unsigned_type> ParseUnsigned(const char* str, int base) {
ossua280f7c2017-04-06 02:02:15 -070035 RTC_DCHECK(str);
36 if (isdigit(str[0]) || str[0] == '-') {
37 // Explicitly discard negative values. std::strtoull parsing causes unsigned
38 // wraparound. We cannot just reject values that start with -, though, since
39 // -0 is perfectly fine, as is -0000000000000000000000000000000.
40 const bool is_negative = str[0] == '-';
41 char* end = nullptr;
42 errno = 0;
43 const unsigned_type value = std::strtoull(str, &end, base);
44 if (end && *end == '\0' && errno == 0 && (value == 0 || !is_negative)) {
Oskar Sundbom9c780582017-11-27 10:28:22 +010045 return value;
ossua280f7c2017-04-06 02:02:15 -070046 }
47 }
Danil Chapovalov0a1d1892018-06-21 11:48:25 +020048 return absl::nullopt;
ossua280f7c2017-04-06 02:02:15 -070049}
50
51} // namespace string_to_number_internal
52} // namespace rtc