1 //===-- StringConvert.cpp ---------------------------------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include <stdlib.h>
11
12 #include "lldb/Host/StringConvert.h"
13
14 namespace lldb_private {
15 namespace StringConvert {
16
ToSInt32(const char * s,int32_t fail_value,int base,bool * success_ptr)17 int32_t ToSInt32(const char *s, int32_t fail_value, int base,
18 bool *success_ptr) {
19 if (s && s[0]) {
20 char *end = nullptr;
21 const long sval = ::strtol(s, &end, base);
22 if (*end == '\0') {
23 if (success_ptr)
24 *success_ptr = ((sval <= INT32_MAX) && (sval >= INT32_MIN));
25 return (int32_t)sval; // All characters were used, return the result
26 }
27 }
28 if (success_ptr)
29 *success_ptr = false;
30 return fail_value;
31 }
32
ToUInt32(const char * s,uint32_t fail_value,int base,bool * success_ptr)33 uint32_t ToUInt32(const char *s, uint32_t fail_value, int base,
34 bool *success_ptr) {
35 if (s && s[0]) {
36 char *end = nullptr;
37 const unsigned long uval = ::strtoul(s, &end, base);
38 if (*end == '\0') {
39 if (success_ptr)
40 *success_ptr = (uval <= UINT32_MAX);
41 return (uint32_t)uval; // All characters were used, return the result
42 }
43 }
44 if (success_ptr)
45 *success_ptr = false;
46 return fail_value;
47 }
48
ToSInt64(const char * s,int64_t fail_value,int base,bool * success_ptr)49 int64_t ToSInt64(const char *s, int64_t fail_value, int base,
50 bool *success_ptr) {
51 if (s && s[0]) {
52 char *end = nullptr;
53 int64_t uval = ::strtoll(s, &end, base);
54 if (*end == '\0') {
55 if (success_ptr)
56 *success_ptr = true;
57 return uval; // All characters were used, return the result
58 }
59 }
60 if (success_ptr)
61 *success_ptr = false;
62 return fail_value;
63 }
64
ToUInt64(const char * s,uint64_t fail_value,int base,bool * success_ptr)65 uint64_t ToUInt64(const char *s, uint64_t fail_value, int base,
66 bool *success_ptr) {
67 if (s && s[0]) {
68 char *end = nullptr;
69 uint64_t uval = ::strtoull(s, &end, base);
70 if (*end == '\0') {
71 if (success_ptr)
72 *success_ptr = true;
73 return uval; // All characters were used, return the result
74 }
75 }
76 if (success_ptr)
77 *success_ptr = false;
78 return fail_value;
79 }
80
ToDouble(const char * s,double fail_value,bool * success_ptr)81 double ToDouble(const char *s, double fail_value, bool *success_ptr) {
82 if (s && s[0]) {
83 char *end = nullptr;
84 double val = strtod(s, &end);
85 if (*end == '\0') {
86 if (success_ptr)
87 *success_ptr = true;
88 return val; // All characters were used, return the result
89 }
90 }
91 if (success_ptr)
92 *success_ptr = false;
93 return fail_value;
94 }
95 }
96 }
97