fuchsia_inspect/writer/types/
bytes_property.rs

1// Copyright 2021 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 crate::writer::{Inner, InnerPropertyType, InspectType, Property};
6use log::error;
7
8/// Inspect Bytes Property data type.
9///
10/// NOTE: do not rely on PartialEq implementation for true comparison.
11/// Instead leverage the reader.
12///
13/// NOTE: Operations on a Default value are no-ops.
14#[derive(Debug, PartialEq, Eq, Default)]
15pub struct BytesProperty {
16    inner: Inner<InnerPropertyType>,
17}
18
19impl<'t> Property<'t> for BytesProperty {
20    type Type = &'t [u8];
21
22    fn set(&self, value: &'t [u8]) {
23        if let Some(ref inner_ref) = self.inner.inner_ref() {
24            inner_ref
25                .state
26                .try_lock()
27                .and_then(|mut state| state.set_buffer_property(inner_ref.block_index, value))
28                .unwrap_or_else(|e| error!("Failed to set property. Error: {:?}", e));
29        }
30    }
31}
32
33impl InspectType for BytesProperty {}
34
35crate::impl_inspect_type_internal!(BytesProperty);
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40    use crate::writer::testing_utils::{get_state, GetBlockExt};
41    use crate::writer::Node;
42    use inspect_format::{BlockType, Buffer, PropertyFormat};
43
44    #[fuchsia::test]
45    fn bytes_property() {
46        // Create and use a default value.
47        let default = BytesProperty::default();
48        default.set(&[0u8, 3u8]);
49
50        let state = get_state(4096);
51        let root = Node::new_root(state);
52        let node = root.create_child("node");
53        {
54            let property = node.create_bytes("property", b"test");
55            property.get_block::<_, Buffer>(|block| {
56                assert_eq!(block.block_type(), Some(BlockType::BufferValue));
57                assert_eq!(block.total_length(), 4);
58                assert_eq!(block.format(), Some(PropertyFormat::Bytes));
59            });
60            node.get_block::<_, inspect_format::Node>(|block| {
61                assert_eq!(block.child_count(), 1);
62            });
63
64            property.set(b"test-set");
65            property.get_block::<_, Buffer>(|block| {
66                assert_eq!(block.total_length(), 8);
67            });
68        }
69        node.get_block::<_, inspect_format::Node>(|block| {
70            assert_eq!(block.child_count(), 0);
71        });
72    }
73}