/ src / univalue / lib / univalue_get.cpp
univalue_get.cpp
 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  {
19      if (str.empty()) // No empty string allowed
20          return false;
21      if (str.size() >= 1 && (json_isspace(str[0]) || json_isspace(str[str.size()-1]))) // No padding allowed
22          return false;
23      if (str.size() != strlen(str.c_str())) // No embedded NUL characters allowed
24          return false;
25      return true;
26  }
27  
28  bool ParseDouble(const std::string& str, double *out)
29  {
30      if (!ParsePrechecks(str))
31          return false;
32      if (str.size() >= 2 && str[0] == '0' && str[1] == 'x') // No hexadecimal floats allowed
33          return false;
34      std::istringstream text(str);
35      text.imbue(std::locale::classic());
36      double result;
37      text >> result;
38      if(out) *out = result;
39      return text.eof() && !text.fail();
40  }
41  }
42  
43  const std::vector<std::string>& UniValue::getKeys() const
44  {
45      checkType(VOBJ);
46      return keys;
47  }
48  
49  const std::vector<UniValue>& UniValue::getValues() const
50  {
51      if (typ != VOBJ && typ != VARR)
52          throw std::runtime_error("JSON value is not an object or array as expected");
53      return values;
54  }
55  
56  bool UniValue::get_bool() const
57  {
58      checkType(VBOOL);
59      return isTrue();
60  }
61  
62  const std::string& UniValue::get_str() const
63  {
64      checkType(VSTR);
65      return getValStr();
66  }
67  
68  double UniValue::get_real() const
69  {
70      checkType(VNUM);
71      double retval;
72      if (!ParseDouble(getValStr(), &retval))
73          throw std::runtime_error("JSON double out of range");
74      return retval;
75  }
76  
77  const UniValue& UniValue::get_obj() const
78  {
79      checkType(VOBJ);
80      return *this;
81  }
82  
83  const UniValue& UniValue::get_array() const
84  {
85      checkType(VARR);
86      return *this;
87  }