-
Notifications
You must be signed in to change notification settings - Fork 11
/
value.rs
577 lines (512 loc) · 16.5 KB
/
value.rs
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
use core::fmt;
use core::hash::{Hash, Hasher};
use std::borrow::Cow;
use std::fmt::{Debug, Display};
use crate::index::Index;
pub use crate::object_vec::ObjectAsVec;
/// Represents any valid JSON value.
///
/// # Example
/// ```
/// use std::io;
/// use serde_json_borrow::Value;
/// fn main() -> io::Result<()> {
/// let data = r#"{"bool": true, "key": "123"}"#;
/// let value: Value = serde_json::from_str(&data)?;
/// assert_eq!(value.get("bool"), &Value::Bool(true));
/// assert_eq!(value.get("key"), &Value::Str("123".into()));
/// Ok(())
/// }
/// ```
#[derive(Clone, Eq, PartialEq, Hash, Default)]
pub enum Value<'ctx> {
/// Represents a JSON null value.
///
/// ```
/// # use serde_json_borrow::Value;
/// #
/// let v = Value::Null;
/// ```
#[default]
Null,
/// Represents a JSON boolean.
///
/// ```
/// # use serde_json_borrow::Value;
/// #
/// let v = Value::Bool(true);
/// ```
Bool(bool),
/// Represents a JSON number, whether integer or floating point.
///
/// ```
/// # use serde_json_borrow::Value;
/// #
/// let v = Value::Number(12.5.into());
/// ```
Number(Number),
/// Represents a JSON string.
///
/// ```
/// # use serde_json_borrow::Value;
/// #
/// let v = Value::Str("ref".into());
/// ```
Str(Cow<'ctx, str>),
/// Represents a JSON array.
Array(Vec<Value<'ctx>>),
/// Represents a JSON object.
///
/// By default the map is backed by a Vec. Allows very fast deserialization.
/// Ideal when wanting to iterate over the values, in contrast to look up by key.
///
/// ```
/// # use serde_json_borrow::Value;
/// # use serde_json_borrow::ObjectAsVec;
/// #
/// let v = Value::Object([("key".into(), Value::Str("value".into()))].into_iter().collect::<Vec<_>>().into());
/// ```
Object(ObjectAsVec<'ctx>),
}
impl<'ctx> Value<'ctx> {
/// Index into a `serde_json_borrow::Value` using the syntax `value.get(0)` or
/// `value.get("k")`.
///
/// Returns `Value::Null` if the type of `self` does not match the type of
/// the index, for example if the index is a string and `self` is an array
/// or a number. Also returns `Value::Null` if the given key does not exist
/// in the map or the given index is not within the bounds of the array.
///
/// # Examples
///
/// ```
/// # use serde_json_borrow::Value;
/// #
/// let json_obj = r#"
/// {
/// "x": {
/// "y": ["z", "zz"]
/// }
/// }
/// "#;
///
/// let data: Value = serde_json::from_str(json_obj).unwrap();
///
/// assert_eq!(data.get("x").get("y").get(0), &Value::Str("z".into()));
/// assert_eq!(data.get("x").get("y").get(1), &Value::Str("zz".into()));
/// assert_eq!(data.get("x").get("y").get(2), &Value::Null);
///
/// assert_eq!(data.get("a"), &Value::Null);
/// assert_eq!(data.get("a").get("b"), &Value::Null);
/// ```
#[inline]
pub fn get<I: Index<'ctx>>(&'ctx self, index: I) -> &'ctx Value<'ctx> {
static NULL: Value = Value::Null;
index.index_into(self).unwrap_or(&NULL)
}
/// Returns true if `Value` is Value::Null.
pub fn is_null(&self) -> bool {
matches!(self, Value::Null)
}
/// Returns true if `Value` is Value::Array.
pub fn is_array(&self) -> bool {
matches!(self, Value::Array(_))
}
/// Returns true if `Value` is Value::Object.
pub fn is_object(&self) -> bool {
matches!(self, Value::Object(_))
}
/// Returns true if `Value` is Value::Bool.
pub fn is_bool(&self) -> bool {
matches!(self, Value::Bool(_))
}
/// Returns true if `Value` is Value::Number.
pub fn is_number(&self) -> bool {
matches!(self, Value::Number(_))
}
/// Returns true if `Value` is Value::Str.
pub fn is_string(&self) -> bool {
matches!(self, Value::Str(_))
}
/// Returns true if the Value is an integer between i64::MIN and i64::MAX.
/// For any Value on which is_i64 returns true, as_i64 is guaranteed to return the integer
/// value.
pub fn is_i64(&self) -> bool {
match self {
Value::Number(n) => n.is_i64(),
_ => false,
}
}
/// Returns true if the Value is an integer between zero and u64::MAX.
/// For any Value on which is_u64 returns true, as_u64 is guaranteed to return the integer
/// value.
pub fn is_u64(&self) -> bool {
match self {
Value::Number(n) => n.is_u64(),
_ => false,
}
}
/// Returns true if the Value is a f64 number.
pub fn is_f64(&self) -> bool {
match self {
Value::Number(n) => n.is_f64(),
_ => false,
}
}
/// If the Value is an Array, returns an iterator over the elements in the array.
pub fn iter_array(&self) -> Option<impl Iterator<Item = &Value<'_>>> {
match self {
Value::Array(arr) => Some(arr.iter()),
_ => None,
}
}
/// If the Value is an Object, returns an iterator over the elements in the object.
pub fn iter_object(&self) -> Option<impl Iterator<Item = (&str, &Value<'_>)>> {
match self {
Value::Object(arr) => Some(arr.iter()),
_ => None,
}
}
/// If the Value is an Array, returns the associated Array. Returns None otherwise.
pub fn as_array(&self) -> Option<&[Value<'ctx>]> {
match self {
Value::Array(arr) => Some(arr),
_ => None,
}
}
/// If the Value is an Object, returns the associated Object. Returns None otherwise.
pub fn as_object(&self) -> Option<&ObjectAsVec<'ctx>> {
match self {
Value::Object(obj) => Some(obj),
_ => None,
}
}
/// If the Value is a Boolean, returns the associated bool. Returns None otherwise.
pub fn as_bool(&self) -> Option<bool> {
match self {
Value::Bool(b) => Some(*b),
_ => None,
}
}
/// If the Value is a String, returns the associated str. Returns None otherwise.
pub fn as_str(&self) -> Option<&str> {
match self {
Value::Str(text) => Some(text),
_ => None,
}
}
/// If the Value is an integer, represent it as i64 if possible. Returns None otherwise.
pub fn as_i64(&self) -> Option<i64> {
match self {
Value::Number(n) => n.as_i64(),
_ => None,
}
}
/// If the Value is an integer, represent it as u64 if possible. Returns None otherwise.
pub fn as_u64(&self) -> Option<u64> {
match self {
Value::Number(n) => n.as_u64(),
_ => None,
}
}
/// If the Value is a number, represent it as f64 if possible. Returns None otherwise.
pub fn as_f64(&self) -> Option<f64> {
match self {
Value::Number(n) => n.as_f64(),
_ => None,
}
}
}
impl From<bool> for Value<'_> {
fn from(val: bool) -> Self {
Value::Bool(val)
}
}
impl<'a> From<&'a str> for Value<'a> {
fn from(val: &'a str) -> Self {
Value::Str(Cow::Borrowed(val))
}
}
impl From<String> for Value<'_> {
fn from(val: String) -> Self {
Value::Str(Cow::Owned(val))
}
}
impl<'a, T: Into<Value<'a>>> From<Vec<T>> for Value<'a> {
fn from(val: Vec<T>) -> Self {
Value::Array(val.into_iter().map(Into::into).collect())
}
}
impl<'a, T: Clone + Into<Value<'a>>> From<&[T]> for Value<'a> {
fn from(val: &[T]) -> Self {
Value::Array(val.iter().map(Clone::clone).map(Into::into).collect())
}
}
impl Debug for Value<'_> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
match self {
Value::Null => formatter.write_str("Null"),
Value::Bool(boolean) => write!(formatter, "Bool({})", boolean),
Value::Number(number) => match number.n {
N::PosInt(n) => write!(formatter, "Number({:?})", n),
N::NegInt(n) => write!(formatter, "Number({:?})", n),
N::Float(n) => write!(formatter, "Number({:?})", n),
},
Value::Str(string) => write!(formatter, "Str({:?})", string),
Value::Array(vec) => {
formatter.write_str("Array ")?;
Debug::fmt(vec, formatter)
}
Value::Object(map) => {
formatter.write_str("Object ")?;
Debug::fmt(map, formatter)
}
}
}
}
// We just convert to serde_json::Value to Display
impl Display for Value<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", serde_json::Value::from(self.clone()))
}
}
/// Represents a JSON number, whether integer or floating point.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Number {
pub(crate) n: N,
}
impl From<N> for Number {
fn from(n: N) -> Self {
Self { n }
}
}
#[derive(Copy, Clone)]
pub(crate) enum N {
PosInt(u64),
/// Always less than zero.
NegInt(i64),
/// Always finite.
Float(f64),
}
impl Number {
/// If the `Number` is an integer, represent it as i64 if possible. Returns
/// None otherwise.
pub fn as_u64(&self) -> Option<u64> {
match self.n {
N::PosInt(v) => Some(v),
_ => None,
}
}
/// If the `Number` is an integer, represent it as u64 if possible. Returns
/// None otherwise.
pub fn as_i64(&self) -> Option<i64> {
match self.n {
N::PosInt(n) => {
if n <= i64::MAX as u64 {
Some(n as i64)
} else {
None
}
}
N::NegInt(v) => Some(v),
_ => None,
}
}
/// Represents the number as f64 if possible. Returns None otherwise.
pub fn as_f64(&self) -> Option<f64> {
match self.n {
N::PosInt(n) => Some(n as f64),
N::NegInt(n) => Some(n as f64),
N::Float(n) => Some(n),
}
}
/// Returns true if the `Number` is a f64.
pub fn is_f64(&self) -> bool {
matches!(self.n, N::Float(_))
}
/// Returns true if the `Number` is a u64.
pub fn is_u64(&self) -> bool {
matches!(self.n, N::PosInt(_))
}
/// Returns true if the `Number` is an integer between `i64::MIN` and
/// `i64::MAX`.
pub fn is_i64(&self) -> bool {
match self.n {
N::PosInt(v) => v <= i64::MAX as u64,
N::NegInt(_) => true,
N::Float(_) => false,
}
}
}
impl PartialEq for N {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(N::PosInt(a), N::PosInt(b)) => a == b,
(N::NegInt(a), N::NegInt(b)) => a == b,
(N::Float(a), N::Float(b)) => a == b,
_ => false,
}
}
}
// Implementing Eq is fine since any float values are always finite.
impl Eq for N {}
impl Hash for N {
fn hash<H: Hasher>(&self, h: &mut H) {
match *self {
N::PosInt(i) => i.hash(h),
N::NegInt(i) => i.hash(h),
N::Float(f) => {
if f == 0.0f64 {
// There are 2 zero representations, +0 and -0, which
// compare equal but have different bits. We use the +0 hash
// for both so that hash(+0) == hash(-0).
0.0f64.to_bits().hash(h);
} else {
f.to_bits().hash(h);
}
}
}
}
}
impl From<u64> for Value<'_> {
fn from(val: u64) -> Self {
Value::Number(val.into())
}
}
impl From<i64> for Value<'_> {
fn from(val: i64) -> Self {
Value::Number(val.into())
}
}
impl From<f64> for Value<'_> {
fn from(val: f64) -> Self {
Value::Number(val.into())
}
}
impl From<u64> for Number {
fn from(val: u64) -> Self {
Self { n: N::PosInt(val) }
}
}
impl From<i64> for Number {
fn from(val: i64) -> Self {
Self { n: N::NegInt(val) }
}
}
impl From<f64> for Number {
fn from(val: f64) -> Self {
Self { n: N::Float(val) }
}
}
impl From<Number> for serde_json::value::Number {
fn from(num: Number) -> Self {
match num.n {
N::PosInt(n) => n.into(),
N::NegInt(n) => n.into(),
N::Float(n) => serde_json::value::Number::from_f64(n).unwrap(),
}
}
}
impl From<Value<'_>> for serde_json::Value {
fn from(val: Value) -> Self {
match val {
Value::Null => serde_json::Value::Null,
Value::Bool(val) => serde_json::Value::Bool(val),
Value::Number(val) => serde_json::Value::Number(val.into()),
Value::Str(val) => serde_json::Value::String(val.to_string()),
Value::Array(vals) => {
serde_json::Value::Array(vals.into_iter().map(|val| val.into()).collect())
}
Value::Object(vals) => serde_json::Value::Object(vals.into()),
}
}
}
impl From<&Value<'_>> for serde_json::Value {
fn from(val: &Value) -> Self {
match val {
Value::Null => serde_json::Value::Null,
Value::Bool(val) => serde_json::Value::Bool(*val),
Value::Number(val) => serde_json::Value::Number((*val).into()),
Value::Str(val) => serde_json::Value::String(val.to_string()),
Value::Array(vals) => {
serde_json::Value::Array(vals.iter().map(|val| val.into()).collect())
}
Value::Object(vals) => serde_json::Value::Object(vals.into()),
}
}
}
impl<'ctx> From<&'ctx serde_json::Value> for Value<'ctx> {
fn from(value: &'ctx serde_json::Value) -> Self {
match value {
serde_json::Value::Null => Value::Null,
serde_json::Value::Bool(b) => Value::Bool(*b),
serde_json::Value::Number(n) => {
if let Some(n) = n.as_i64() {
Value::Number(n.into())
} else if let Some(n) = n.as_u64() {
Value::Number(n.into())
} else if let Some(n) = n.as_f64() {
Value::Number(n.into())
} else {
unreachable!()
}
}
serde_json::Value::String(val) => Value::Str(Cow::Borrowed(val)),
serde_json::Value::Array(arr) => {
let out: Vec<Value<'ctx>> = arr.iter().map(|v| v.into()).collect();
Value::Array(out)
}
serde_json::Value::Object(obj) => {
let mut ans = ObjectAsVec::default();
for (k, v) in obj {
ans.insert(k.as_str(), v.into());
}
Value::Object(ans)
}
}
}
}
#[cfg(test)]
mod tests {
use std::io;
use super::*;
#[test]
fn from_serde() {
let value = &serde_json::json!({
"a": 1,
"b": "2",
"c": [3, 4],
"d": {"e": "alo"}
});
let value: Value = value.into();
assert_eq!(value.get("a"), &Value::Number(1i64.into()));
assert_eq!(value.get("b"), &Value::Str("2".into()));
assert_eq!(value.get("c").get(0), &Value::Number(3i64.into()));
assert_eq!(value.get("c").get(1), &Value::Number(4i64.into()));
assert_eq!(value.get("d").get("e"), &Value::Str("alo".into()));
}
#[test]
fn number_test() -> io::Result<()> {
let data = r#"{"val1": 123.5, "val2": 123, "val3": -123}"#;
let value: Value = serde_json::from_str(data)?;
assert!(value.get("val1").is_f64());
assert!(!value.get("val1").is_u64());
assert!(!value.get("val1").is_i64());
assert!(!value.get("val2").is_f64());
assert!(value.get("val2").is_u64());
assert!(value.get("val2").is_i64());
assert!(!value.get("val3").is_f64());
assert!(!value.get("val3").is_u64());
assert!(value.get("val3").is_i64());
assert!(value.get("val1").as_f64().is_some());
assert!(value.get("val2").as_f64().is_some());
assert!(value.get("val3").as_f64().is_some());
assert!(value.get("val1").as_u64().is_none());
assert!(value.get("val2").as_u64().is_some());
assert!(value.get("val3").as_u64().is_none());
assert!(value.get("val1").as_i64().is_none());
assert!(value.get("val2").as_i64().is_some());
assert!(value.get("val3").as_i64().is_some());
Ok(())
}
}