1// Copyright 2008 Google Inc. All Rights Reserved.
2//
3// Architecture-neutral plug compatible replacements for strtol() friends.
4// See strtoint.h for details on how to use this component.
5//
6
7#include <errno.h>
8#include "base/port.h"
9#include "base/basictypes.h"
10#include "base/strtoint.h"
11
12// Replacement strto[u]l functions that have identical overflow and underflow
13// characteristics for both ILP-32 and LP-64 platforms, including errno
14// preservation for error-free calls.
15int32 strto32_adapter(const char *nptr, char **endptr, int base) {
16 const int saved_errno = errno;
17 errno = 0;
18 const long result = strtol(nptr, endptr, base);
19 if (errno == ERANGE && result == LONG_MIN) {
20 return kint32min;
21 } else if (errno == ERANGE && result == LONG_MAX) {
22 return kint32max;
23 } else if (errno == 0 && result < kint32min) {
24 errno = ERANGE;
25 return kint32min;
26 } else if (errno == 0 && result > kint32max) {
27 errno = ERANGE;
28 return kint32max;
29 }
30 if (errno == 0)
31 errno = saved_errno;
32 return static_cast<int32>(result);
33}
34
35uint32 strtou32_adapter(const char *nptr, char **endptr, int base) {
36 const int saved_errno = errno;
37 errno = 0;
38 const unsigned long result = strtoul(nptr, endptr, base);
39 if (errno == ERANGE && result == ULONG_MAX) {
40 return kuint32max;
41 } else if (errno == 0 && result > kuint32max) {
42 errno = ERANGE;
43 return kuint32max;
44 }
45 if (errno == 0)
46 errno = saved_errno;
47 return static_cast<uint32>(result);
48}
49