fuchsia_inspect_contrib/inspectable/
mod.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
// Copyright 2019 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.

//! Provides utilities on top of regular inspect properties to enable convenient features such as:
//!
//! - Directly mutating a value and dumping it to inspect
//!
//!   ```rust
//!   use fuchsia_inspect::component;
//!   use fuchsia_inspect::contrib::inspectable::InspectableU64;
//!
//!   let inspectable = InspectableU64::new(0, component::inspector::root(), "foo");
//!   *inspectable.get_mut() += 1;
//!   // The value of the u64 is 1 now and it was updated automatically in the inspect vmo.
//!   ```
//!
//! - Dump lengths automatically
//!
//!   ```rust
//!   use fuchsia_inspect::component;
//!   use fuchsia_inspect::contrib::inspectable::InspectableLen;
//!
//!   let inspectable = InspectableLen::new(vec![0], component::inspector::root(), "foo");
//!   // The value of the vector is [0] and the value in the inspect vmo under the foo property
//!   // is 1.
//!   *inspectable.get_mut().push(3);
//!   // The value of the vector is [0, 3] and the value in the inspect vmo under the foo property
//!   // is 2.
//!   ```
//!
//! - Dump debug representations automatically, etc.
//!
//!   ```rust
//!   use fuchsia_inspect::component;
//!   use fuchsia_inspect::contrib::inspectable::InspectableDebugString;
//!
//!   let inspectable = InspectableDebugString::new(vec![0], component::inspector::root(), "foo");
//!   // The value of the vector is vec![0] and the value in the inspect vmo under the foo property
//!   // is the debug string of the vector "[0]".
//!   *inspectable.get_mut().push(3);
//!   // The value of the vector is vec![0, 3] and the value in the inspect vmo under the foo
//!   // property is the debug string of the vector "[0, 3]".
//!   ```

use core::ops::{Deref, DerefMut};
use derivative::Derivative;
use fuchsia_inspect::{
    BoolProperty, Node, Property, StringProperty, StringReference, UintProperty,
};
use std::borrow::Borrow;
use std::collections::HashSet;

/// Generic wrapper for exporting variables via Inspect. Mutations to
/// the wrapped `value` occur through an `InspectableGuard`, which
/// notifies the `watcher` when `Drop`ped, transparently keeping the Inspect
/// state up-to-date.
///
/// How the `value` is exported is determined by the `Watch` implementation,
/// see e.g. `InspectableDebugString`.
///
/// Not correct for `V`s with interior mutability, because `Inspectable`
/// `Deref`s to `V`, mutations to which will bypass the `watcher`.
#[derive(Derivative)]
#[derivative(Debug, Eq, PartialEq)]
pub struct Inspectable<V, W>
where
    W: Watch<V>,
{
    value: V,
    #[derivative(Debug = "ignore", PartialEq = "ignore", Hash = "ignore")]
    watcher: W,
}

impl<V, W> Inspectable<V, W>
where
    W: Watch<V>,
{
    /// Creates an `Inspectable` wrapping `value`. Exports `value` via Inspect.
    pub fn new(value: V, node: &Node, name: impl Into<StringReference>) -> Self {
        let watcher = W::new(&value, node, name);
        Self { value, watcher }
    }

    /// Returns a guard that `DerefMut`s to the wrapped `value`. The `watcher`
    /// will receive the updated `value` when the guard is `Drop`ped.
    pub fn get_mut(&mut self) -> InspectableGuard<'_, V, W> {
        InspectableGuard { value: &mut self.value, watcher: &mut self.watcher }
    }
}

impl<V, W> Deref for Inspectable<V, W>
where
    W: Watch<V>,
{
    type Target = V;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl<V, W> Borrow<V> for Inspectable<V, W>
where
    W: Watch<V>,
{
    fn borrow(&self) -> &V {
        &self.value
    }
}

/// Used for exporting an `[Inspectable`][Inspectable]'s wrapped value .
pub trait Watch<V> {
    /// Used by [`Inspectable::new()`][Inspectable::new] to create a `Watch`er that exports via
    /// Inspect the [`Inspectable`][Inspectable]'s wrapped `value`.
    fn new(value: &V, node: &Node, name: impl Into<StringReference>) -> Self;

    /// Called by [`InspectableGuard`][InspectableGuard] when the guard is dropped, letting the
    /// `Watch`er update its state with the updated `value`.
    fn watch(&mut self, value: &V);
}

/// Calls self.watcher.watch(self.value) when dropped.
#[must_use]
pub struct InspectableGuard<'a, V, W>
where
    W: Watch<V>,
{
    value: &'a mut V,
    watcher: &'a mut W,
}

impl<'a, V, W> Deref for InspectableGuard<'a, V, W>
where
    W: Watch<V>,
{
    type Target = V;

    fn deref(&self) -> &Self::Target {
        self.value
    }
}

impl<'a, V, W> DerefMut for InspectableGuard<'a, V, W>
where
    W: Watch<V>,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.value
    }
}

impl<'a, V, W> Drop for InspectableGuard<'a, V, W>
where
    W: Watch<V>,
{
    fn drop(&mut self) {
        self.watcher.watch(self.value);
    }
}

/// Exports via an Inspect `UintProperty` the `len` of the wrapped container.
#[derive(Debug)]
pub struct InspectableLenWatcher {
    len: fuchsia_inspect::UintProperty,
}

/// Trait implemented by types that can provide a length. Values used for
/// [`InspectableLen`][InspectableLen] must implement this.
pub trait Len {
    fn len(&self) -> usize;
    fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl<V> Watch<V> for InspectableLenWatcher
where
    V: Len,
{
    fn new(value: &V, node: &Node, name: impl Into<StringReference>) -> Self {
        Self { len: node.create_uint(name, value.len() as u64) }
    }

    fn watch(&mut self, value: &V) {
        self.len.set(value.len() as u64);
    }
}

/// Exports via an Inspect `UintProperty` the `len` of the wrapped value `V`.
pub type InspectableLen<V> = Inspectable<V, InspectableLenWatcher>;

impl<V> Len for Vec<V> {
    fn len(&self) -> usize {
        self.len()
    }
}

impl<V> Len for HashSet<V> {
    fn len(&self) -> usize {
        self.len()
    }
}

/// Exports via an Inspect `StringProperty` the `Debug` representation of
/// the wrapped `value`.
#[derive(Debug)]
pub struct InspectableDebugStringWatcher {
    debug_string: StringProperty,
}

impl<V> Watch<V> for InspectableDebugStringWatcher
where
    V: std::fmt::Debug,
{
    fn new(value: &V, node: &Node, name: impl Into<StringReference>) -> Self {
        Self { debug_string: node.create_string(name, format!("{:?}", value)) }
    }

    fn watch(&mut self, value: &V) {
        self.debug_string.set(&format!("{:?}", value))
    }
}

/// Exports via an Inspect `StringProperty` the `Debug` representation of the wrapped value `V`.
pub type InspectableDebugString<V> = Inspectable<V, InspectableDebugStringWatcher>;

/// Exports via an Inspect `UintProperty` a `u64`. Useful because the wrapped `u64`
/// value can be read.
#[derive(Debug)]
pub struct InspectableU64Watcher {
    uint_property: UintProperty,
}

impl Watch<u64> for InspectableU64Watcher {
    fn new(value: &u64, node: &Node, name: impl Into<StringReference>) -> Self {
        Self { uint_property: node.create_uint(name, *value) }
    }

    fn watch(&mut self, value: &u64) {
        self.uint_property.set(*value);
    }
}

/// Exports via an Inspect `UintProperty` a `u64`. Useful because the wrapped `u64`
/// value can be read.
pub type InspectableU64 = Inspectable<u64, InspectableU64Watcher>;

pub struct InspectableBoolWatcher {
    bool_property: BoolProperty,
}

impl Watch<bool> for InspectableBoolWatcher {
    fn new(value: &bool, node: &Node, name: impl Into<StringReference>) -> Self {
        Self { bool_property: node.create_bool(name, *value) }
    }

    fn watch(&mut self, value: &bool) {
        self.bool_property.set(*value);
    }
}

pub type InspectableBool = Inspectable<bool, InspectableBoolWatcher>;

#[cfg(test)]
mod test {
    use super::*;
    use diagnostics_assertions::assert_data_tree;
    use fuchsia_inspect::{Inspector, IntProperty};

    struct InspectableIntWatcher {
        i: IntProperty,
    }
    impl Watch<i64> for InspectableIntWatcher {
        fn new(value: &i64, node: &Node, name: impl Into<StringReference>) -> Self {
            Self { i: node.create_int(name, *value) }
        }
        fn watch(&mut self, value: &i64) {
            self.i.set(*value)
        }
    }

    type InspectableInt = Inspectable<i64, InspectableIntWatcher>;
    fn make_inspectable(i: i64) -> (InspectableInt, Inspector) {
        let inspector = Inspector::default();
        let inspectable = InspectableInt::new(i, inspector.root(), "inspectable-int");
        (inspectable, inspector)
    }

    #[fuchsia::test]
    fn test_inspectable_deref() {
        let inspectable = make_inspectable(1).0;

        assert_eq!(*inspectable, 1);
    }

    #[fuchsia::test]
    fn test_guard_deref() {
        let mut inspectable = make_inspectable(1).0;

        assert_eq!(*inspectable.get_mut(), 1);
    }

    #[fuchsia::test]
    fn test_guard_deref_mut() {
        let mut inspectable = make_inspectable(1).0;

        *inspectable.get_mut() = 2;

        assert_eq!(*inspectable, 2);
    }

    #[fuchsia::test]
    fn test_guard_drop_calls_callback() {
        let (mut inspectable, inspector) = make_inspectable(1);

        let mut guard = inspectable.get_mut();
        *guard = 2;
        drop(guard);

        assert_data_tree!(
            inspector,
            root: {
                "inspectable-int": 2i64
            }
        );
    }

    #[fuchsia::test]
    fn test_partial_eq() {
        let inspectable0 = make_inspectable(1).0;
        let inspectable1 = make_inspectable(1).0;

        assert_eq!(inspectable0, inspectable1);
    }

    #[fuchsia::test]
    fn test_partial_eq_not() {
        let inspectable0 = make_inspectable(1).0;
        let inspectable1 = make_inspectable(2).0;

        assert_ne!(inspectable0, inspectable1);
    }

    #[fuchsia::test]
    fn test_borrow() {
        let inspectable = make_inspectable(1).0;

        assert_eq!(Borrow::<i64>::borrow(&inspectable), &1);
    }
}

#[cfg(test)]
mod test_inspectable_len {
    use super::*;
    use diagnostics_assertions::assert_data_tree;

    #[fuchsia::test]
    fn test_initialization() {
        let inspector = fuchsia_inspect::Inspector::default();
        let _inspectable = InspectableLen::new(vec![0], inspector.root(), "test-property");

        assert_data_tree!(
            inspector,
            root: {
                "test-property": 1u64
            }
        );
    }

    #[fuchsia::test]
    fn test_watcher() {
        let inspector = fuchsia_inspect::Inspector::default();
        let mut inspectable = InspectableLen::new(vec![0], inspector.root(), "test-property");

        inspectable.get_mut().push(1);

        assert_data_tree!(
            inspector,
            root: {
                "test-property": 2u64
            }
        );
    }
}

#[cfg(test)]
mod test_inspectable_debug_string {
    use super::*;
    use diagnostics_assertions::assert_data_tree;

    #[fuchsia::test]
    fn test_initialization() {
        let inspector = fuchsia_inspect::Inspector::default();
        let _inspectable = InspectableDebugString::new(vec![0], inspector.root(), "test-property");

        assert_data_tree!(
            inspector,
            root: {
                "test-property": "[0]"
            }
        );
    }

    #[fuchsia::test]
    fn test_watcher() {
        let inspector = fuchsia_inspect::Inspector::default();
        let mut inspectable =
            InspectableDebugString::new(vec![0], inspector.root(), "test-property");

        inspectable.get_mut().push(1);

        assert_data_tree!(
            inspector,
            root: {
                "test-property": "[0, 1]"
            }
        );
    }
}

#[cfg(test)]
mod test_inspectable_u64 {
    use super::*;
    use diagnostics_assertions::assert_data_tree;

    #[fuchsia::test]
    fn test_initialization() {
        let inspector = fuchsia_inspect::Inspector::default();
        let _inspectable = InspectableU64::new(0, inspector.root(), "test-property");

        assert_data_tree!(
            inspector,
            root: {
                "test-property": 0u64,
            }
        );
    }

    #[fuchsia::test]
    fn test_watcher() {
        let inspector = fuchsia_inspect::Inspector::default();
        let mut inspectable = InspectableU64::new(0, inspector.root(), "test-property");

        *inspectable.get_mut() += 1;

        assert_data_tree!(
            inspector,
            root: {
                "test-property": 1u64,
            }
        );
    }
}

#[cfg(test)]
mod test_inspectable_bool {
    use super::*;
    use diagnostics_assertions::assert_data_tree;

    #[fuchsia::test]
    fn test_initialization() {
        let inspector = fuchsia_inspect::Inspector::default();
        let _inspectable = InspectableBool::new(false, inspector.root(), "test-property");

        assert_data_tree!(
            inspector,
            root: {
                "test-property": false,
            }
        );
    }

    #[fuchsia::test]
    fn test_watcher() {
        let inspector = fuchsia_inspect::Inspector::default();
        let mut inspectable = InspectableBool::new(false, inspector.root(), "test-property");

        *inspectable.get_mut() = true;

        assert_data_tree!(
            inspector,
            root: {
                "test-property": true,
            }
        );
    }
}