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
// Copyright 2021 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::writer::{Inner, InnerValueType, InspectType, Property};
use tracing::error;

/// Inspect API Bool Property data type.
///
/// NOTE: do not rely on PartialEq implementation for true comparison.
/// Instead leverage the reader.
///
/// NOTE: Operations on a Default value are no-ops.
#[derive(Debug, PartialEq, Eq, Default)]
pub struct BoolProperty {
    inner: Inner<InnerValueType>,
}

impl<'t> Property<'t> for BoolProperty {
    type Type = bool;

    fn set(&self, value: bool) {
        if let Some(ref inner_ref) = self.inner.inner_ref() {
            inner_ref
                .state
                .try_lock()
                .and_then(|mut state| state.set_bool(inner_ref.block_index, value))
                .unwrap_or_else(|e| {
                    error!("Failed to set property. Error: {:?}", e);
                });
        }
    }
}

impl InspectType for BoolProperty {}

crate::impl_inspect_type_internal!(BoolProperty);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::writer::{testing_utils::get_state, testing_utils::GetBlockExt, Node};
    use inspect_format::BlockType;

    #[fuchsia::test]
    fn bool_property() {
        // Create and use a default value.
        let default = BoolProperty::default();
        default.set(true);

        let state = get_state(4096);
        let root = Node::new_root(state);
        let node = root.create_child("node");
        {
            let property = node.create_bool("property", true);
            property.get_block(|block| {
                assert_eq!(block.block_type(), BlockType::BoolValue);
                assert_eq!(block.bool_value().unwrap(), true);
            });
            node.get_block(|block| {
                assert_eq!(block.child_count().unwrap(), 1);
            });

            property.set(false);
            property.get_block(|block| {
                assert_eq!(block.bool_value().unwrap(), false);
            });
        }
        node.get_block(|block| {
            assert_eq!(block.child_count().unwrap(), 0);
        });
    }
}