settings_inspect_utils/
joinable_inspect_vecdeque.rs

1// Copyright 2022 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use fuchsia_inspect::{Node, Property, StringProperty};
6use fuchsia_inspect_derive::Unit;
7// use itertools::Itertools;
8use std::collections::VecDeque;
9
10/// Wrapper around [std::collections::VecDeque] that only holds [String].
11///
12/// Implements [fuchsia_inspect_derive::Unit], which allows it to be written
13/// to inspect as a single property with its value being a comma-separated list
14/// that's concatenation of all of the items in the VecDeque.
15///
16/// To use this in a a structure that implements [fuchsia_inspect_derive::Inspect], wrap this in the
17/// [fuchsia_inspect_derive::IValue] smart pointer and it will automatically update the value of the
18/// inspect property when updated.
19#[derive(Default)]
20pub struct JoinableInspectVecDeque(pub VecDeque<String>);
21
22impl JoinableInspectVecDeque {
23    fn join(&self) -> String {
24        self.0.iter().map(String::as_str).collect::<Vec<_>>().join(",")
25    }
26}
27
28impl Unit for JoinableInspectVecDeque {
29    type Data = StringProperty;
30
31    fn inspect_create(&self, parent: &Node, name: impl AsRef<str>) -> Self::Data {
32        parent.create_string(name.as_ref(), self.join())
33    }
34
35    fn inspect_update(&self, data: &mut Self::Data) {
36        data.set(&self.join());
37    }
38}
39
40#[cfg(test)]
41mod tests {
42    use crate::joinable_inspect_vecdeque::JoinableInspectVecDeque;
43    use diagnostics_assertions::assert_data_tree;
44    use fuchsia_inspect::{Inspector, Node};
45    use fuchsia_inspect_derive::{IValue, Inspect, WithInspect};
46
47    #[derive(Default, Inspect)]
48    struct TestInspectWrapper {
49        inspect_node: Node,
50        pub test_vec_deque: IValue<JoinableInspectVecDeque>,
51    }
52
53    // Tests that adding and removing from JoinableInspectVecDeque updates the inspect tree.
54    #[fuchsia::test]
55    fn test_vec_deque() {
56        let inspector = Inspector::default();
57
58        let mut wrapper = TestInspectWrapper::default()
59            .with_inspect(inspector.root(), "wrapper_node")
60            .expect("Failed to attach wrapper_node");
61
62        wrapper.test_vec_deque.as_mut().0.push_back("test1".to_string());
63        wrapper.test_vec_deque.as_mut().0.push_back("test2".to_string());
64        wrapper.test_vec_deque.as_mut().0.push_back("test3".to_string());
65
66        let _ = wrapper.test_vec_deque.as_mut().0.pop_front();
67
68        assert_data_tree!(inspector, root: {
69            wrapper_node: {
70                "test_vec_deque": "test2,test3",
71            }
72        });
73    }
74}