Skip to main content

ferroui_dynamic_data/binding/
property_value.rs

1//! `PropertyValue<TObject, TValue>` (`Binding/PropertyValue.cs`).
2
3use std::fmt;
4
5/// A value of a property and the object it was read from (`PropertyValue<TObject, TValue>`).
6///
7/// Upstream's value of a path that a null step interrupts is the default value of `TValue`, with a
8/// flag (`UnobtainableValue`); here it is `None` ([`value`](Self::value)).
9#[derive(Clone)]
10pub struct PropertyValue<T, V> {
11    sender: T,
12    value: Option<V>,
13}
14
15impl<T, V> PropertyValue<T, V> {
16    /// The value of a property of `sender` (`PropertyValue(TObject sender, TValue value)`).
17    pub fn new(sender: T, value: V) -> Self {
18        Self { sender, value: Some(value) }
19    }
20
21    /// A value that could not be read, as a step of the path was null
22    /// (`PropertyValue(TObject sender)`).
23    pub fn unobtainable(sender: T) -> Self {
24        Self { sender, value: None }
25    }
26
27    /// The object the value was read from (`Sender`).
28    pub fn sender(&self) -> &T {
29        &self.sender
30    }
31
32    /// The value (`Value`); `None` when it could not be read.
33    pub fn value(&self) -> Option<&V> {
34        self.value.as_ref()
35    }
36
37    /// The value, giving up the rest.
38    pub fn into_value(self) -> Option<V> {
39        self.value
40    }
41
42    /// Whether the value could not be read, as a step of the path was null (`UnobtainableValue`).
43    pub fn is_unobtainable(&self) -> bool {
44        self.value.is_none()
45    }
46}
47
48impl<T: PartialEq, V: PartialEq> PartialEq for PropertyValue<T, V> {
49    /// `Equals`: two values that could not be read are equal whatever their senders, as are two
50    /// null values upstream; otherwise the senders and the values are compared.
51    fn eq(&self, other: &Self) -> bool {
52        match (&self.value, &other.value) {
53            (None, None) => true,
54            (Some(value), Some(other_value)) => self.sender == other.sender && value == other_value,
55            _ => false,
56        }
57    }
58}
59
60impl<T: fmt::Display, V: fmt::Debug> fmt::Display for PropertyValue<T, V> {
61    /// `ToString`: the sender and the value in parentheses.
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        match &self.value {
64            Some(value) => write!(f, "{} ({:?})", self.sender, value),
65            None => write!(f, "{} ()", self.sender),
66        }
67    }
68}
69
70impl<T: fmt::Debug, V: fmt::Debug> fmt::Debug for PropertyValue<T, V> {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        f.debug_struct("PropertyValue").field("sender", &self.sender).field("value", &self.value).finish()
73    }
74}