/root/bitcoin/src/univalue/lib/univalue_get.cpp
Line | Count | Source |
1 | | // Copyright 2014 BitPay Inc. |
2 | | // Copyright 2015 Bitcoin Core Developers |
3 | | // Distributed under the MIT software license, see the accompanying |
4 | | // file COPYING or https://opensource.org/licenses/mit-license.php. |
5 | | |
6 | | #include <univalue.h> |
7 | | |
8 | | #include <cstring> |
9 | | #include <locale> |
10 | | #include <sstream> |
11 | | #include <stdexcept> |
12 | | #include <string> |
13 | | #include <vector> |
14 | | |
15 | | namespace |
16 | | { |
17 | | static bool ParsePrechecks(const std::string& str) |
18 | 0 | { |
19 | 0 | if (str.empty()) // No empty string allowed |
20 | 0 | return false; |
21 | 0 | if (str.size() >= 1 && (json_isspace(str[0]) || json_isspace(str[str.size()-1]))) // No padding allowed |
22 | 0 | return false; |
23 | 0 | if (str.size() != strlen(str.c_str())) // No embedded NUL characters allowed |
24 | 0 | return false; |
25 | 0 | return true; |
26 | 0 | } |
27 | | |
28 | | bool ParseDouble(const std::string& str, double *out) |
29 | 0 | { |
30 | 0 | if (!ParsePrechecks(str)) |
31 | 0 | return false; |
32 | 0 | if (str.size() >= 2 && str[0] == '0' && str[1] == 'x') // No hexadecimal floats allowed |
33 | 0 | return false; |
34 | 0 | std::istringstream text(str); |
35 | 0 | text.imbue(std::locale::classic()); |
36 | 0 | double result; |
37 | 0 | text >> result; |
38 | 0 | if(out) *out = result; |
39 | 0 | return text.eof() && !text.fail(); |
40 | 0 | } |
41 | | } |
42 | | |
43 | | const std::vector<std::string>& UniValue::getKeys() const |
44 | 0 | { |
45 | 0 | checkType(VOBJ); |
46 | 0 | return keys; |
47 | 0 | } |
48 | | |
49 | | const std::vector<UniValue>& UniValue::getValues() const |
50 | 0 | { |
51 | 0 | if (typ != VOBJ && typ != VARR) |
52 | 0 | throw std::runtime_error("JSON value is not an object or array as expected"); |
53 | 0 | return values; |
54 | 0 | } |
55 | | |
56 | | bool UniValue::get_bool() const |
57 | 0 | { |
58 | 0 | checkType(VBOOL); |
59 | 0 | return isTrue(); |
60 | 0 | } |
61 | | |
62 | | const std::string& UniValue::get_str() const |
63 | 0 | { |
64 | 0 | checkType(VSTR); |
65 | 0 | return getValStr(); |
66 | 0 | } |
67 | | |
68 | | double UniValue::get_real() const |
69 | 0 | { |
70 | 0 | checkType(VNUM); |
71 | 0 | double retval; |
72 | 0 | if (!ParseDouble(getValStr(), &retval)) |
73 | 0 | throw std::runtime_error("JSON double out of range"); |
74 | 0 | return retval; |
75 | 0 | } |
76 | | |
77 | | const UniValue& UniValue::get_obj() const |
78 | 0 | { |
79 | 0 | checkType(VOBJ); |
80 | 0 | return *this; |
81 | 0 | } |
82 | | |
83 | | const UniValue& UniValue::get_array() const |
84 | 0 | { |
85 | 0 | checkType(VARR); |
86 | 0 | return *this; |
87 | 0 | } |