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
// 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.

//! This crate provides types, traits and macros for ergonomic
//! interactions with `fuchsia_inspect`. Proc macros are originally defined
//! in a separate crate, but re-exported here. Users should depend directly
//! on this crate.

mod inspect;

use core::fmt;
use core::ops::{Deref, DerefMut};
use fuchsia_inspect::{
    BoolProperty, BytesProperty, DoubleProperty, IntProperty, Node, Property, StringProperty,
    UintProperty,
};
pub use inspect::{AttachError, Inspect, WithInspect};
use std::marker::PhantomData;

/// Re-export Node, used by the procedural macros in order to get a canonical,
/// stable import path. User code does not need `fuchsia_inspect` in their
/// namespace.
#[doc(hidden)]
pub use fuchsia_inspect::Node as InspectNode;

/// The `Unit` derive macro can be applied to named structs in order to generate an
/// implementation of the `Unit` trait. The name of the field corresponds to the
/// inspect node or property name, and the type of the field must also implement `Unit`.
/// Implementations of `Unit` are supplied for most primitives and `String`.
///
/// Example:
///
/// #[derive(Unit)]
/// struct Point {
///     x: f32,
///     y: f32,
/// }
pub use fuchsia_inspect_derive_macro::{Inspect, Unit};

/// Provides a custom inspect `fuchsia_inspect` subtree for a type which is
/// created, updated and removed in a single step. (It does NOT support per-field updates.)
pub trait Unit {
    /// This associated type owns a subtree (either a property or a node) of a parent inspect node.
    /// May be nested. When dropped, the subtree is detached from the parent.
    /// Default is required such that a detached state can be constructed. The base inspect node
    /// and property types implement default.
    type Data: Default;

    /// Insert an inspect subtree at `parent[name]` with values from `self` and return
    /// the inspect data.
    fn inspect_create(&self, parent: &Node, name: impl AsRef<str>) -> Self::Data;

    /// Update the inspect subtree owned by the inspect data with values from self.
    fn inspect_update(&self, data: &mut Self::Data);
}

impl Unit for String {
    type Data = StringProperty;

    fn inspect_create(&self, parent: &Node, name: impl AsRef<str>) -> Self::Data {
        parent.create_string(name.as_ref(), self)
    }

    fn inspect_update(&self, data: &mut Self::Data) {
        data.set(self);
    }
}

impl Unit for Vec<u8> {
    type Data = BytesProperty;

    fn inspect_create(&self, parent: &Node, name: impl AsRef<str>) -> Self::Data {
        parent.create_bytes(name.as_ref(), &self)
    }

    fn inspect_update(&self, data: &mut Self::Data) {
        data.set(&self);
    }
}

/// Implement `Unit` for a primitive type. Some implementations result in a
/// non-lossy upcast in order to conform to the supported types in the inspect API.
///   `impl_t`: The primitive types to be implemented, e.g. `{ u8, u16 }`
///   `inspect_t`: The type the inspect API expects, e.g. `u64`
///   `prop_name`: The name the inspect API uses for functions, e.g. `uint`
///   `prop_name_cap`: The name the inspect API uses for types, e.g. `Uint`
macro_rules! impl_unit_primitive {
    ({ $($impl_t:ty), *}, $inspect_t:ty, $prop_name:ident, $prop_name_cap:ident) => {
        $(
            paste::paste! {
                impl Unit for $impl_t {
                    type Data = [<$prop_name_cap Property>];

                    fn inspect_create(&self, parent: &Node, name: impl AsRef<str>) -> Self::Data {
                        parent.[<create_ $prop_name>](name.as_ref(), *self as $inspect_t)
                    }

                    fn inspect_update(&self, data: &mut Self::Data) {
                        data.set(*self as $inspect_t);
                    }
                }
            }
        )*
    };
}

// Implement `Unit` for the supported primitive types.
impl_unit_primitive!({ u8, u16, u32, u64, usize }, u64, uint, Uint);
impl_unit_primitive!({ i8, i16, i32, i64, isize }, i64, int, Int);
impl_unit_primitive!({ f32, f64 }, f64, double, Double);
impl_unit_primitive!({ bool }, bool, bool, Bool);

/// The inspect data of an Option<T> gets the same inspect representation as T,
/// but can also be absent.
pub struct OptionData<T: Unit> {
    // Keep a copy of the owned name, so that the inner node or property can be
    // reinitialized after initial attachment.
    name: String,

    // Keep a reference to the parent, so that the inner node or property can be
    // reinitialized after initial attachment.
    inspect_parent: Node,

    // Inner inspect data.
    inspect_data: Option<T::Data>,
}

impl<T: Unit> Default for OptionData<T> {
    fn default() -> Self {
        Self { name: String::default(), inspect_parent: Node::default(), inspect_data: None }
    }
}

impl<T: Unit> Unit for Option<T> {
    type Data = OptionData<T>;

    fn inspect_create(&self, parent: &Node, name: impl AsRef<str>) -> Self::Data {
        Self::Data {
            name: String::from(name.as_ref()),
            inspect_parent: parent.clone_weak(),
            inspect_data: self.as_ref().map(|inner| inner.inspect_create(&parent, name.as_ref())),
        }
    }

    fn inspect_update(&self, data: &mut Self::Data) {
        match (self.as_ref(), &mut data.inspect_data) {
            // None, always unset inspect data
            (None, ref mut inspect_data) => **inspect_data = None,

            // Missing inspect data, initialize it
            (Some(inner), None) => {
                data.inspect_data = Some(inner.inspect_create(&data.inspect_parent, &data.name));
            }

            // Update existing inspect data, for performance
            (Some(inner), Some(ref mut inner_inspect_data)) => {
                inner.inspect_update(inner_inspect_data);
            }
        }
    }
}

/// Renders inspect state. This trait should be implemented with
/// a relevant constraint on the base type.
pub trait Render {
    /// The base type, provided by the user.
    type Base;

    /// Inspect data, provided by implementors of this trait.
    type Data: Default;

    /// Initializes the inspect data from the current state of base.
    fn create(base: &Self::Base, parent: &Node, name: impl AsRef<str>) -> Self::Data;

    /// Updates the inspect data from the current state of base.
    fn update(base: &Self::Base, data: &mut Self::Data);
}

/// Generic smart pointer which owns an inspect subtree (either a Node or a
/// Property) for the duration of its lifetime. It dereferences to the
/// user-provided base type (similar to Arc and other smart pointers).
/// This type should rarely be used declared explictly. Rather, a specific smart
/// pointer (such as IValue) should be used.
pub struct IOwned<R: Render> {
    _base: R::Base,
    _inspect_data: R::Data,
}

impl<R: Render> IOwned<R> {
    /// Construct the smart pointer but don't populate any inspect state.
    pub fn new(value: R::Base) -> Self {
        let _inspect_data = R::Data::default();
        Self { _base: value, _inspect_data }
    }

    /// Construct the smart pointer and populate the inspect state under parent[name].
    pub fn attached(value: R::Base, parent: &Node, name: impl AsRef<str>) -> Self {
        let _inspect_data = R::create(&value, &parent, name.as_ref());
        Self { _base: value, _inspect_data }
    }

    /// Returns a RAII guard which can be used for mutations. When the guard
    /// goes out of scope, the new inspect state is published.
    pub fn as_mut(&mut self) -> IOwnedMutGuard<'_, R> {
        IOwnedMutGuard(self)
    }

    /// Set the value, then update inspect state.
    pub fn iset(&mut self, value: R::Base) {
        self._base = value;
        R::update(&self._base, &mut self._inspect_data);
    }

    pub fn into_inner(self) -> R::Base {
        self._base
    }
}

impl<R: Render> Inspect for &mut IOwned<R> {
    fn iattach(self, parent: &Node, name: impl AsRef<str>) -> Result<(), AttachError> {
        self._inspect_data = R::create(&self._base, &parent, name.as_ref());
        Ok(())
    }
}

impl<R, B> fmt::Debug for IOwned<R>
where
    R: Render<Base = B>,
    B: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self._base, f)
    }
}

impl<R, B> fmt::Display for IOwned<R>
where
    R: Render<Base = B>,
    B: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self._base, f)
    }
}

impl<R, B> Default for IOwned<R>
where
    R: Render<Base = B>,
    B: Default,
{
    fn default() -> Self {
        let _inspect_data = R::Data::default();
        let _base = B::default();
        Self { _base, _inspect_data }
    }
}

impl<R: Render> Deref for IOwned<R> {
    type Target = R::Base;
    fn deref(&self) -> &Self::Target {
        &self._base
    }
}

/// A RAII implementation of a scoped guard of an IOwned smart pointer. When
/// this structure is dropped (falls out of scope), the new inspect state will
/// be published.
pub struct IOwnedMutGuard<'a, R: Render>(&'a mut IOwned<R>);

impl<'a, R: Render> Deref for IOwnedMutGuard<'a, R> {
    type Target = R::Base;
    fn deref(&self) -> &R::Base {
        &self.0._base
    }
}

impl<'a, R: Render> DerefMut for IOwnedMutGuard<'a, R> {
    fn deref_mut(&mut self) -> &mut R::Base {
        &mut self.0._base
    }
}

impl<'a, R: Render> Drop for IOwnedMutGuard<'a, R> {
    fn drop(&mut self) {
        R::update(&self.0._base, &mut self.0._inspect_data);
    }
}

#[doc(hidden)]
pub struct ValueMarker<B: Unit>(PhantomData<B>);

impl<B: Unit> Render for ValueMarker<B> {
    type Base = B;
    type Data = B::Data;

    fn create(base: &Self::Base, parent: &Node, name: impl AsRef<str>) -> Self::Data {
        base.inspect_create(parent, name.as_ref())
    }

    fn update(base: &Self::Base, data: &mut Self::Data) {
        base.inspect_update(data);
    }
}

/// An `Inspect` smart pointer for a type `B`, which renders an
/// inspect subtree as defined by `B: Unit`.
pub type IValue<B> = IOwned<ValueMarker<B>>;

impl<B: Unit> From<B> for IValue<B> {
    fn from(value: B) -> Self {
        Self::new(value)
    }
}

#[doc(hidden)]
pub struct DebugMarker<B: fmt::Debug>(PhantomData<B>);

impl<B: fmt::Debug> Render for DebugMarker<B> {
    type Base = B;
    type Data = StringProperty;

    fn create(base: &Self::Base, parent: &Node, name: impl AsRef<str>) -> Self::Data {
        parent.create_string(name.as_ref(), &format!("{:?}", base))
    }

    fn update(base: &Self::Base, data: &mut Self::Data) {
        data.set(&format!("{:?}", base));
    }
}

/// An `Inspect` smart pointer for a type `B`, which renders the debug
/// output of `B` as a string property.
pub type IDebug<B> = IOwned<DebugMarker<B>>;

impl<B: fmt::Debug> From<B> for IDebug<B> {
    fn from(value: B) -> Self {
        Self::new(value)
    }
}