diagnostics_hierarchy/serialization/
deserialize.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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::{ArrayContent, DiagnosticsHierarchy, ExponentialHistogram, LinearHistogram, Property};
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use base64::engine::Engine as _;
use serde::de::{self, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer};
use std::collections::HashMap;
use std::fmt;
use std::hash::Hash;
use std::marker::PhantomData;
use std::str::FromStr;

struct RootVisitor<Key> {
    // Key is unused.
    marker: PhantomData<Key>,
}

impl<'de, Key> Visitor<'de> for RootVisitor<Key>
where
    Key: FromStr + Clone + Hash + Eq + AsRef<str>,
{
    type Value = DiagnosticsHierarchy<Key>;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("there should be a single root")
    }

    fn visit_map<V>(self, mut map: V) -> Result<DiagnosticsHierarchy<Key>, V::Error>
    where
        V: MapAccess<'de>,
    {
        let result = match map.next_entry::<String, FieldValue<Key>>()? {
            Some((map_key, value)) => {
                let key = Key::from_str(&map_key)
                    .map_err(|_| de::Error::custom("failed to parse key"))?;
                value.into_node(&key)
            }
            None => return Err(de::Error::invalid_length(0, &"expected a root node")),
        };

        let mut found = 1;
        while map.next_key::<String>()?.is_some() {
            found += 1;
        }

        if found > 1 {
            return Err(de::Error::invalid_length(found, &"expected a single root"));
        }

        result.ok_or_else(|| de::Error::custom("expected node for root"))
    }
}

impl<'de, Key> Deserialize<'de> for DiagnosticsHierarchy<Key>
where
    Key: FromStr + Clone + Hash + Eq + AsRef<str>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_map(RootVisitor { marker: PhantomData })
    }
}

trait IntoProperty<Key> {
    fn into_property(self, key: &Key) -> Option<Property<Key>>;
}

/// The value of an inspect tree field (node or property).
enum FieldValue<Key> {
    String(String),
    Bytes(Vec<u8>),
    Int(i64),
    Uint(u64),
    Double(f64),
    Bool(bool),
    Array(Vec<NumericValue>),
    LinearIntHistogram(LinearHistogram<i64>),
    LinearUintHistogram(LinearHistogram<u64>),
    LinearDoubleHistogram(LinearHistogram<f64>),
    ExponentialIntHistogram(ExponentialHistogram<i64>),
    ExponentialUintHistogram(ExponentialHistogram<u64>),
    ExponentialDoubleHistogram(ExponentialHistogram<f64>),
    Node(HashMap<Key, FieldValue<Key>>),
    StringList(Vec<String>),
}

impl<Key: Clone> IntoProperty<Key> for FieldValue<Key> {
    fn into_property(self, key: &Key) -> Option<Property<Key>> {
        match self {
            Self::String(value) => Some(Property::String(key.clone(), value)),
            Self::Bytes(value) => Some(Property::Bytes(key.clone(), value)),
            Self::Int(value) => Some(Property::Int(key.clone(), value)),
            Self::Uint(value) => Some(Property::Uint(key.clone(), value)),
            Self::Double(value) => Some(Property::Double(key.clone(), value)),
            Self::Bool(value) => Some(Property::Bool(key.clone(), value)),
            Self::Array(values) => values.into_property(key),
            Self::ExponentialIntHistogram(histogram) => {
                Some(Property::IntArray(key.clone(), ArrayContent::ExponentialHistogram(histogram)))
            }
            Self::ExponentialUintHistogram(histogram) => Some(Property::UintArray(
                key.clone(),
                ArrayContent::ExponentialHistogram(histogram),
            )),
            Self::ExponentialDoubleHistogram(histogram) => Some(Property::DoubleArray(
                key.clone(),
                ArrayContent::ExponentialHistogram(histogram),
            )),
            Self::LinearIntHistogram(histogram) => {
                Some(Property::IntArray(key.clone(), ArrayContent::LinearHistogram(histogram)))
            }
            Self::LinearUintHistogram(histogram) => {
                Some(Property::UintArray(key.clone(), ArrayContent::LinearHistogram(histogram)))
            }
            Self::LinearDoubleHistogram(histogram) => {
                Some(Property::DoubleArray(key.clone(), ArrayContent::LinearHistogram(histogram)))
            }
            Self::StringList(list) => Some(Property::StringList(key.clone(), list)),
            Self::Node(_) => None,
        }
    }
}

impl<Key: AsRef<str> + Clone> FieldValue<Key> {
    fn is_property(&self) -> bool {
        !matches!(self, Self::Node(_))
    }

    fn into_node(self, key: &Key) -> Option<DiagnosticsHierarchy<Key>> {
        match self {
            Self::Node(map) => {
                let mut properties = vec![];
                let mut children = vec![];
                for (map_key, value) in map {
                    if value.is_property() {
                        properties.push(value.into_property(&map_key).unwrap());
                    } else {
                        children.push(value.into_node(&map_key).unwrap());
                    }
                }
                Some(DiagnosticsHierarchy::new(key.as_ref(), properties, children))
            }
            _ => None,
        }
    }
}

impl<'de, Key> Deserialize<'de> for FieldValue<Key>
where
    Key: FromStr + Hash + Eq,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_any(FieldVisitor { marker: PhantomData })
    }
}

struct FieldVisitor<Key> {
    marker: PhantomData<Key>,
}

// Histogram type may be: linear or exponential; double, int, or uint.
// If it's linear, step will be Some and initial_step and step_multiplier will be None.
// if it's exponential, step will be None and initial_step and step_multiplier will be Some.
// In all cases, size must be usize (u64).
// indexes will be either None or Some(Vec<NumericValue>) which must be convertible to Vec<usize>.
// counts will be Vec<NumericValue>.
// If the histogram is double, every number must be f64 and counts must convert to Vec<f64>.
// If it's not double, the numbers will be some mix of i64 and u64. If even one can't fit in
// an i64, then the histogram must be represented as u64 and none of the numbers can be
// negative.
// The deserializer will have used i64 for any number that fits, and we can assume most
// histograms will fit in i64, so first we check if all numbers are i64 and counts can convert
// to Vec<i64>. If not, then we have to check if a mix of i64 and u64 can all be u64.

fn value_as_u64<Key>(value: &FieldValue<Key>) -> Option<u64> {
    match value {
        FieldValue::Uint(value) => Some(*value),
        FieldValue::Int(value) => u64::try_from(*value).ok(),
        _ => None,
    }
}

fn value_as_i64<Key>(value: &FieldValue<Key>) -> Option<i64> {
    match value {
        FieldValue::Int(value) => Some(*value),
        FieldValue::Uint(value) => i64::try_from(*value).ok(),
        _ => None,
    }
}

// Try to convert indexes to Option<Vec<usize>> and declared_len to usize, and check consistency of
// several sizes. Return Err(()) if anything goes wrong, and the converted (indexes, declared_len)
// if it's all good,
fn sanitize_histogram_parameters<Key>(
    indexes: Option<&FieldValue<Key>>,
    n_parameters: usize,
    dict_len: usize,
    counts: &FieldValue<Key>,
    size: &FieldValue<Key>,
) -> Result<(Option<Vec<usize>>, usize), ()> {
    let size = match size {
        FieldValue::Uint(size) => *size as usize,
        FieldValue::Int(size) if *size >= 0 => *size as usize,
        _ => return Err(()),
    };
    // An empty array will be cast as a StringList. A condensed histogram of all-zeroes will thus
    // have empty StringList counts and indexes. If we sanitize successfully, we'll return an
    // empty Vec<usize> for indexes, and we will have verified that counts is empty too.
    let counts_len = match counts {
        FieldValue::Array(counts) => counts.len(),
        FieldValue::StringList(counts) if counts.is_empty() => 0,
        _ => return Err(()),
    };
    if size < 3 {
        // We need at least 3 (overflow + 1) buckets to be a valid histogram
        return Err(());
    }
    // It's OK if indexes is None. If it's Some, it must be a Vec<NumericValue> that converts to a
    // Vec<usize>. Also, check that various lengths are consistent.
    match indexes {
        None => {
            if counts_len != size || dict_len != n_parameters - 1 {
                return Err(());
            }
            Ok((None, size))
        }
        Some(FieldValue::StringList(indexes)) if indexes.is_empty() => {
            if counts_len != 0 || dict_len != n_parameters {
                return Err(());
            }
            Ok((Some(vec![]), size))
        }
        Some(FieldValue::Array(indexes)) => {
            if indexes.len() != counts_len || counts_len > size || dict_len != n_parameters {
                return Err(());
            }
            let indexes = indexes
                .iter()
                .map(|value| match value.as_u64() {
                    None => None,
                    Some(i) if (i as usize) < size => Some(i as usize),
                    _ => None,
                })
                .collect::<Option<Vec<_>>>();
            match indexes {
                None => Err(()),
                Some(indexes) => Ok((Some(indexes), size)),
            }
        }
        _ => Err(()),
    }
}

fn match_linear_histogram<Key>(
    floor: &FieldValue<Key>,
    step: &FieldValue<Key>,
    counts: &FieldValue<Key>,
    indexes: Option<&FieldValue<Key>>,
    size: &FieldValue<Key>,
    dict_len: usize,
) -> Option<FieldValue<Key>> {
    let (indexes, size) = match sanitize_histogram_parameters(indexes, 5, dict_len, counts, size) {
        Ok((indexes, size)) => (indexes, size),
        Err(()) => return None,
    };
    // A double histogram will have all types double. An int or uint histogram may have a mix
    // of int and uint members.
    match (floor, step, counts) {
        (FieldValue::Double(floor), FieldValue::Double(step), counts) => {
            let counts = match parse_f64_list(counts) {
                None => return None,
                Some(counts) => counts,
            };
            Some(FieldValue::LinearDoubleHistogram(LinearHistogram {
                floor: *floor,
                step: *step,
                counts,
                indexes,
                size,
            }))
        }
        (floor, step, counts) => {
            let counts_i64 = parse_i64_list(counts);
            if let (Some(counts), Some(floor), Some(step)) =
                (counts_i64, value_as_i64(floor), value_as_i64(step))
            {
                return Some(FieldValue::LinearIntHistogram(LinearHistogram {
                    floor,
                    step,
                    counts,
                    indexes,
                    size,
                }));
            }
            // At this point, it's unsigned, or nothing.
            if let (Some(counts), Some(floor), Some(step)) =
                (parse_u64_list(counts), value_as_u64(floor), value_as_u64(step))
            {
                return Some(FieldValue::LinearUintHistogram(LinearHistogram {
                    floor,
                    step,
                    counts,
                    indexes,
                    size,
                }));
            }
            None
        }
    }
}

fn match_exponential_histogram<Key>(
    floor: &FieldValue<Key>,
    initial_step: &FieldValue<Key>,
    step_multiplier: &FieldValue<Key>,
    counts: &FieldValue<Key>,
    indexes: Option<&FieldValue<Key>>,
    size: &FieldValue<Key>,
    dict_len: usize,
) -> Option<FieldValue<Key>> {
    let (indexes, size) = match sanitize_histogram_parameters(indexes, 6, dict_len, counts, size) {
        Ok((indexes, size)) => (indexes, size),
        Err(()) => return None,
    };
    match (floor, initial_step, step_multiplier, counts) {
        (
            FieldValue::Double(floor),
            FieldValue::Double(initial_step),
            FieldValue::Double(step_multiplier),
            counts,
        ) => {
            let counts = match parse_f64_list(counts) {
                None => return None,
                Some(counts) => counts,
            };
            Some(FieldValue::ExponentialDoubleHistogram(ExponentialHistogram {
                floor: *floor,
                initial_step: *initial_step,
                step_multiplier: *step_multiplier,
                counts,
                indexes,
                size,
            }))
        }
        (floor, initial_step, step_multiplier, counts) => {
            let counts_i64 = parse_i64_list(counts);
            if let (Some(counts), Some(floor), Some(initial_step), Some(step_multiplier)) = (
                counts_i64,
                value_as_i64(floor),
                value_as_i64(initial_step),
                value_as_i64(step_multiplier),
            ) {
                return Some(FieldValue::ExponentialIntHistogram(ExponentialHistogram {
                    floor,
                    initial_step,
                    step_multiplier,
                    counts,
                    indexes,
                    size,
                }));
            }
            // At this point, it's unsigned, or nothing.
            if let (Some(counts), Some(floor), Some(initial_step), Some(step_multiplier)) = (
                parse_u64_list(counts),
                value_as_u64(floor),
                value_as_u64(initial_step),
                value_as_u64(step_multiplier),
            ) {
                return Some(FieldValue::ExponentialUintHistogram(ExponentialHistogram {
                    floor,
                    initial_step,
                    step_multiplier,
                    counts,
                    indexes,
                    size,
                }));
            }
            None
        }
    }
}

fn match_histogram<Key>(dict: &HashMap<Key, FieldValue<Key>>) -> Option<FieldValue<Key>>
where
    Key: FromStr + Hash + Eq,
{
    // Quick checks for efficiency - most maps won't be histograms.
    let dict_len = dict.len();
    if !(4..=6).contains(&dict_len) {
        return None;
    }
    let floor = dict.get(&Key::from_str("floor").ok().unwrap())?;
    let step = dict.get(&Key::from_str("step").ok().unwrap());
    let initial_step = dict.get(&Key::from_str("initial_step").ok().unwrap());
    let step_multiplier = dict.get(&Key::from_str("step_multiplier").ok().unwrap());
    let counts = dict.get(&Key::from_str("counts").ok().unwrap());
    let indexes = dict.get(&Key::from_str("indexes").ok().unwrap());
    let size = dict.get(&Key::from_str("size").ok().unwrap());
    // Indexes may be None if the histogram isn't condensed.
    match (step, initial_step, step_multiplier, counts, indexes, size) {
        (Some(step), None, None, Some(counts), indexes, Some(size)) => {
            match_linear_histogram(floor, step, counts, indexes, size, dict_len)
        }
        (None, Some(initial_step), Some(step_multiplier), Some(counts), indexes, Some(size)) => {
            match_exponential_histogram(
                floor,
                initial_step,
                step_multiplier,
                counts,
                indexes,
                size,
                dict_len,
            )
        }
        _ => None,
    }
}

impl<'de, Key> Visitor<'de> for FieldVisitor<Key>
where
    Key: FromStr + Hash + Eq,
{
    type Value = FieldValue<Key>;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("failed to field")
    }

    fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
    where
        V: MapAccess<'de>,
    {
        let mut entries = vec![];
        while let Some(entry) = map.next_entry::<String, FieldValue<Key>>()? {
            entries.push(entry);
        }

        let node = entries
            .into_iter()
            .map(|(key, value)| Key::from_str(&key).map(|key| (key, value)))
            .collect::<Result<HashMap<Key, FieldValue<Key>>, _>>()
            .map_err(|_| de::Error::custom("failed to parse key"))?;
        if let Some(histogram) = match_histogram(&node) {
            Ok(histogram)
        } else {
            Ok(FieldValue::Node(node))
        }
    }

    fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E> {
        Ok(FieldValue::Int(value))
    }

    fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> {
        Ok(FieldValue::Uint(value))
    }

    fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E> {
        Ok(FieldValue::Double(value))
    }

    fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E> {
        Ok(FieldValue::Bool(value))
    }

    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
    where
        E: de::Error,
    {
        if value.starts_with("b64:") {
            let bytes64 = value.replace("b64:", "");
            let bytes = BASE64_STANDARD
                .decode(&bytes64)
                .map_err(|_| de::Error::custom("failed to decode bytes"))?;
            return Ok(FieldValue::Bytes(bytes));
        }
        Ok(FieldValue::String(value.to_string()))
    }

    fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
    where
        S: SeqAccess<'de>,
    {
        let mut result = vec![];
        while let Some(elem) = seq.next_element::<SeqItem>()? {
            result.push(elem);
        }
        // There can be two types of sequences: regular arrays (containing numeric values),
        // and string lists (containing only strings). There cannot be a
        // sequence containing a mix of them.
        let mut array = vec![];
        let mut strings = vec![];
        for item in result {
            match item {
                SeqItem::Value(x) => array.push(x),
                SeqItem::StringValue(x) => strings.push(x),
            }
        }

        match (!array.is_empty(), !strings.is_empty()) {
            (true, false) => Ok(FieldValue::Array(array)),
            (false, _) => {
                // Numeric arrays cannot be empty, but string lists can.
                // Histograms can contain empty arrays of numbers, but we'll check for empty
                // StringList in the histogram-matching code, and know what it means.
                Ok(FieldValue::StringList(strings))
            }
            _ => Err(de::Error::custom("unexpected sequence containing mixed values")),
        }
    }
}

#[derive(Deserialize)]
#[serde(untagged)]
enum SeqItem {
    Value(NumericValue),
    StringValue(String),
}

enum NumericValue {
    Positive(u64),
    Negative(i64),
    Double(f64),
}

impl NumericValue {
    #[inline]
    fn as_i64(&self) -> Option<i64> {
        match self {
            Self::Positive(x) if *x <= i64::MAX as u64 => Some(*x as i64),
            Self::Negative(x) => Some(*x),
            _ => None,
        }
    }

    #[inline]
    fn as_u64(&self) -> Option<u64> {
        match self {
            Self::Positive(x) => Some(*x),
            _ => None,
        }
    }

    #[inline]
    fn as_f64(&self) -> Option<f64> {
        match self {
            Self::Double(x) => Some(*x),
            _ => None,
        }
    }
}

impl<'de> Deserialize<'de> for NumericValue {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_any(NumericValueVisitor)
    }
}

impl<Key: Clone> IntoProperty<Key> for Vec<NumericValue> {
    fn into_property(self, key: &Key) -> Option<Property<Key>> {
        if let Some(values) = parse_f64_vec(&self) {
            return Some(Property::DoubleArray(key.clone(), ArrayContent::Values(values)));
        }
        if let Some(values) = parse_i64_vec(&self) {
            return Some(Property::IntArray(key.clone(), ArrayContent::Values(values)));
        }
        if let Some(values) = parse_u64_vec(&self) {
            return Some(Property::UintArray(key.clone(), ArrayContent::Values(values)));
        }
        None
    }
}

macro_rules! parse_numeric_vec_impls {
    ($($type:ty),*) => {
        $(
            paste::paste! {
                fn [<parse_ $type _vec>](vec: &[NumericValue]) -> Option<Vec<$type>> {
                    vec.iter().map(|value| value.[<as_ $type>]()).collect::<Option<Vec<_>>>()
                }

                // Histograms can contain empty lists for counts and indexes. These will be
                // deserialized as empty StringLists and should parse to empty vecs
                // of any numeric type.
                fn [<parse_ $type _list>]<Key>(list: &FieldValue<Key>) -> Option<Vec<$type>> {
                    match list {
                        FieldValue::StringList(list) if list.len() == 0 => Some(vec![]),
                        FieldValue::Array(vec) => [<parse_ $type _vec>](vec),
                        _ => None,
                    }
                }
            }
        )*
    };
}

// Generates the following functions:
// fn parse_f64_vec()
// fn parse_u64_vec()
// fn parse_i64_vec()
// fn parse_f64_list()
// fn parse_u64_list()
// fn parse_i64_list()
parse_numeric_vec_impls!(f64, u64, i64);

struct NumericValueVisitor;

impl Visitor<'_> for NumericValueVisitor {
    type Value = NumericValue;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("failed to deserialize bucket array")
    }

    fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E> {
        if value < 0 {
            return Ok(NumericValue::Negative(value));
        }
        Ok(NumericValue::Positive(value as u64))
    }

    fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> {
        Ok(NumericValue::Positive(value))
    }

    fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E> {
        Ok(NumericValue::Double(value))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ArrayFormat;

    #[fuchsia::test]
    fn deserialize_json() {
        let json_string = get_single_json_hierarchy();
        let mut parsed_hierarchy: DiagnosticsHierarchy =
            serde_json::from_str(&json_string).expect("deserialized");
        let mut expected_hierarchy = get_unambigious_deserializable_hierarchy();
        parsed_hierarchy.sort();
        expected_hierarchy.sort();
        assert_eq!(expected_hierarchy, parsed_hierarchy);
    }

    #[fuchsia::test]
    fn reversible_deserialize() {
        let mut original_hierarchy = get_unambigious_deserializable_hierarchy();
        let result =
            serde_json::to_string(&original_hierarchy).expect("failed to format hierarchy");
        let mut parsed_hierarchy: DiagnosticsHierarchy =
            serde_json::from_str(&result).expect("deserialized");
        parsed_hierarchy.sort();
        original_hierarchy.sort();
        assert_eq!(original_hierarchy, parsed_hierarchy);
    }

    #[fuchsia::test]
    fn test_exp_histogram() {
        let mut hierarchy = DiagnosticsHierarchy::new(
            "root".to_string(),
            vec![Property::IntArray(
                "histogram".to_string(),
                ArrayContent::new(
                    vec![1000, 1000, 2, 1, 2, 3, 4, 5, 6],
                    ArrayFormat::ExponentialHistogram,
                )
                .unwrap(),
            )],
            vec![],
        );
        let expected_json = serde_json::json!({
            "root": {
                "histogram": {
                    "floor": 1000,
                    "initial_step": 1000,
                    "step_multiplier": 2,
                    "counts": [1, 2, 3, 4, 5, 6],
                    "size": 6
                }
            }
        });
        let result_json = serde_json::json!(hierarchy);
        assert_eq!(result_json, expected_json);
        let mut parsed_hierarchy: DiagnosticsHierarchy =
            serde_json::from_value(result_json).expect("deserialized");
        parsed_hierarchy.sort();
        hierarchy.sort();
        assert_eq!(hierarchy, parsed_hierarchy);
    }

    // Creates a hierarchy that isn't lossy due to its unambigious values.
    fn get_unambigious_deserializable_hierarchy() -> DiagnosticsHierarchy {
        DiagnosticsHierarchy::new(
            "root",
            vec![
                Property::UintArray(
                    "array".to_string(),
                    ArrayContent::Values(vec![0, 2, u64::MAX]),
                ),
                Property::Bool("bool_true".to_string(), true),
                Property::Bool("bool_false".to_string(), false),
                Property::StringList(
                    "string_list".to_string(),
                    vec!["foo".to_string(), "bar".to_string()],
                ),
                Property::StringList("empty_string_list".to_string(), vec![]),
            ],
            vec![
                DiagnosticsHierarchy::new(
                    "a",
                    vec![
                        Property::Double("double".to_string(), 2.5),
                        Property::DoubleArray(
                            "histogram".to_string(),
                            ArrayContent::new(
                                vec![0.0, 2.0, 4.0, 1.0, 3.0, 4.0, 7.0],
                                ArrayFormat::ExponentialHistogram,
                            )
                            .unwrap(),
                        ),
                    ],
                    vec![],
                ),
                DiagnosticsHierarchy::new(
                    "b",
                    vec![
                        Property::Int("int".to_string(), -2),
                        Property::String("string".to_string(), "some value".to_string()),
                        Property::IntArray(
                            "histogram".to_string(),
                            ArrayContent::new(vec![0, 2, 4, 1, 3], ArrayFormat::LinearHistogram)
                                .unwrap(),
                        ),
                    ],
                    vec![],
                ),
            ],
        )
    }
    pub fn get_single_json_hierarchy() -> String {
        "{ \"root\": {
                \"a\": {
                    \"double\": 2.5,
                    \"histogram\": {
                        \"floor\": 0.0,
                        \"initial_step\": 2.0,
                        \"step_multiplier\": 4.0,
                        \"counts\": [1.0, 3.0, 4.0, 7.0],
                        \"size\": 4
                    }
                },
                \"array\": [
                    0,
                    2,
                    18446744073709551615
                ],
                \"string_list\": [\"foo\", \"bar\"],
                \"empty_string_list\": [],
                \"b\": {
                    \"histogram\": {
                        \"floor\": 0,
                        \"step\": 2,
                        \"counts\": [4, 1, 3],
                        \"size\": 3
                    },
                    \"int\": -2,
                    \"string\": \"some value\"
                },
                \"bool_false\": false,
                \"bool_true\": true
            }}"
        .to_string()
    }
}