aboutsummaryrefslogtreecommitdiff
path: root/util/json/json_helpers.h
blob: 1943973dc2a06b17edfc3f4e0129c73963d68e3f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef UTIL_JSON_JSON_HELPERS_H_
#define UTIL_JSON_JSON_HELPERS_H_

#include <chrono>
#include <cmath>
#include <functional>
#include <string>
#include <utility>
#include <vector>

#include "absl/strings/string_view.h"
#include "json/value.h"
#include "platform/base/error.h"
#include "util/chrono_helpers.h"
#include "util/simple_fraction.h"

// This file contains helper methods for parsing JSON, in an attempt to
// reduce boilerplate code when working with JsonCpp.
namespace openscreen {
namespace json {

// TODO(jophba): remove these methods after refactoring offer messaging.
inline Error CreateParseError(const std::string& type) {
  return Error(Error::Code::kJsonParseError, "Failed to parse " + type);
}

inline Error CreateParameterError(const std::string& type) {
  return Error(Error::Code::kParameterInvalid, "Invalid parameter: " + type);
}

inline ErrorOr<bool> ParseBool(const Json::Value& parent,
                               const std::string& field) {
  const Json::Value& value = parent[field];
  if (!value.isBool()) {
    return CreateParseError("bool field " + field);
  }
  return value.asBool();
}

inline ErrorOr<int> ParseInt(const Json::Value& parent,
                             const std::string& field) {
  const Json::Value& value = parent[field];
  if (!value.isInt()) {
    return CreateParseError("integer field: " + field);
  }
  return value.asInt();
}

inline ErrorOr<uint32_t> ParseUint(const Json::Value& parent,
                                   const std::string& field) {
  const Json::Value& value = parent[field];
  if (!value.isUInt()) {
    return CreateParseError("unsigned integer field: " + field);
  }
  return value.asUInt();
}

inline ErrorOr<std::string> ParseString(const Json::Value& parent,
                                        const std::string& field) {
  const Json::Value& value = parent[field];
  if (!value.isString()) {
    return CreateParseError("string field: " + field);
  }
  return value.asString();
}

// TODO(jophba): offer messaging should use these methods instead.
inline bool ParseBool(const Json::Value& value, bool* out) {
  if (!value.isBool()) {
    return false;
  }
  *out = value.asBool();
  return true;
}

// A general note about parsing primitives. "Validation" in this context
// generally means ensuring that the values are non-negative, excepting doubles
// which may be negative in some cases.
inline bool ParseAndValidateDouble(const Json::Value& value,
                                   double* out,
                                   bool allow_negative = false) {
  if (!value.isDouble()) {
    return false;
  }
  const double d = value.asDouble();
  if (std::isnan(d)) {
    return false;
  }
  if (!allow_negative && d < 0) {
    return false;
  }
  *out = d;
  return true;
}

inline bool ParseAndValidateInt(const Json::Value& value, int* out) {
  if (!value.isInt()) {
    return false;
  }
  int i = value.asInt();
  if (i < 0) {
    return false;
  }
  *out = i;
  return true;
}

inline bool ParseAndValidateUint(const Json::Value& value, uint32_t* out) {
  if (!value.isUInt()) {
    return false;
  }
  *out = value.asUInt();
  return true;
}

inline bool ParseAndValidateString(const Json::Value& value, std::string* out) {
  if (!value.isString()) {
    return false;
  }
  *out = value.asString();
  return true;
}

// We want to be more robust when we parse fractions then just
// allowing strings, this will parse numeral values such as
// value: 50 as well as value: "50" and value: "100/2".
inline bool ParseAndValidateSimpleFraction(const Json::Value& value,
                                           SimpleFraction* out) {
  if (value.isInt()) {
    int parsed = value.asInt();
    if (parsed < 0) {
      return false;
    }
    *out = SimpleFraction{parsed, 1};
    return true;
  }

  if (value.isString()) {
    auto fraction_or_error = SimpleFraction::FromString(value.asString());
    if (!fraction_or_error) {
      return false;
    }

    if (!fraction_or_error.value().is_positive() ||
        !fraction_or_error.value().is_defined()) {
      return false;
    }
    *out = std::move(fraction_or_error.value());
    return true;
  }
  return false;
}

inline bool ParseAndValidateMilliseconds(const Json::Value& value,
                                         milliseconds* out) {
  int out_ms;
  if (!ParseAndValidateInt(value, &out_ms) || out_ms < 0) {
    return false;
  }
  *out = milliseconds(out_ms);
  return true;
}

template <typename T>
using Parser = std::function<bool(const Json::Value&, T*)>;

// NOTE: array parsing methods reset the output vector to an empty vector in
// any error case. This is especially useful for optional arrays.
template <typename T>
bool ParseAndValidateArray(const Json::Value& value,
                           Parser<T> parser,
                           std::vector<T>* out) {
  out->clear();
  if (!value.isArray() || value.empty()) {
    return false;
  }

  out->reserve(value.size());
  for (Json::ArrayIndex i = 0; i < value.size(); ++i) {
    T v;
    if (!parser(value[i], &v)) {
      out->clear();
      return false;
    }
    out->push_back(v);
  }

  return true;
}

inline bool ParseAndValidateIntArray(const Json::Value& value,
                                     std::vector<int>* out) {
  return ParseAndValidateArray<int>(value, ParseAndValidateInt, out);
}

inline bool ParseAndValidateUintArray(const Json::Value& value,
                                      std::vector<uint32_t>* out) {
  return ParseAndValidateArray<uint32_t>(value, ParseAndValidateUint, out);
}

inline bool ParseAndValidateStringArray(const Json::Value& value,
                                        std::vector<std::string>* out) {
  return ParseAndValidateArray<std::string>(value, ParseAndValidateString, out);
}

}  // namespace json
}  // namespace openscreen

#endif  // UTIL_JSON_JSON_HELPERS_H_