use crate::writer::{Inner, InnerValueType, InspectType, NumericProperty, Property};
use tracing::error;
#[derive(Debug, PartialEq, Eq, Default)]
pub struct DoubleProperty {
inner: Inner<InnerValueType>,
}
impl InspectType for DoubleProperty {}
crate::impl_inspect_type_internal!(DoubleProperty);
impl<'t> Property<'t> for DoubleProperty {
type Type = f64;
fn set(&self, value: f64) {
if let Some(ref inner_ref) = self.inner.inner_ref() {
inner_ref
.state
.try_lock()
.and_then(|mut state| state.set_double_metric(inner_ref.block_index, value))
.unwrap_or_else(|err| {
error!(?err, "Failed to set property");
});
}
}
}
impl NumericProperty<'_> for DoubleProperty {
fn add(&self, value: f64) -> Option<f64> {
if let Some(ref inner_ref) = self.inner.inner_ref() {
inner_ref
.state
.try_lock()
.and_then(|mut state| state.add_double_metric(inner_ref.block_index, value))
.map(Option::from)
.unwrap_or_else(|err| {
error!(?err, "Failed to set property");
None
})
} else {
None
}
}
fn subtract(&self, value: f64) -> Option<f64> {
if let Some(ref inner_ref) = self.inner.inner_ref() {
inner_ref
.state
.try_lock()
.and_then(|mut state| state.subtract_double_metric(inner_ref.block_index, value))
.map(Option::from)
.unwrap_or_else(|err| {
error!(?err, "Failed to set property");
None
})
} else {
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::writer::testing_utils::{get_state, GetBlockExt};
use crate::writer::Node;
use inspect_format::BlockType;
#[fuchsia::test]
fn double_property() {
let default = DoubleProperty::default();
default.add(1.0);
let state = get_state(4096);
let root = Node::new_root(state);
let node = root.create_child("node");
{
let property = node.create_double("property", 1.0);
property.get_block(|property_block| {
assert_eq!(property_block.block_type(), BlockType::DoubleValue);
assert_eq!(property_block.double_value().unwrap(), 1.0);
});
node.get_block(|node_block| {
assert_eq!(node_block.child_count().unwrap(), 1);
});
property.set(2.0);
property.get_block(|property_block| {
assert_eq!(property_block.double_value().unwrap(), 2.0);
});
assert_eq!(property.subtract(5.5).unwrap(), -3.5);
property.get_block(|property_block| {
assert_eq!(property_block.double_value().unwrap(), -3.5);
});
assert_eq!(property.add(8.1).unwrap(), 4.6);
property.get_block(|property_block| {
assert_eq!(property_block.double_value().unwrap(), 4.6);
});
}
node.get_block(|node_block| {
assert_eq!(node_block.child_count().unwrap(), 0);
});
}
}