liquid_core/model/value/
state.rs

1use std::fmt;
2
3use crate::model::KStringCow;
4
5use super::DisplayCow;
6use super::{Value, ValueView};
7
8/// Queryable state for a `Value`.
9///
10/// See the [Stack overflow table](https://stackoverflow.com/questions/885414/a-concise-explanation-of-nil-v-empty-v-blank-in-ruby-on-rails)
11#[derive(Copy, Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
12pub enum State {
13    /// Is the value truthy?
14    Truthy,
15    /// Is the value the same as default initialized?
16    DefaultValue,
17    /// Is the value empty?
18    Empty,
19    /// Is the value blank?
20    Blank,
21}
22
23impl State {
24    fn is_truthy(self) -> bool {
25        match self {
26            State::Truthy => false,
27            State::DefaultValue => false,
28            State::Empty => false,
29            State::Blank => false,
30        }
31    }
32
33    fn is_default(self) -> bool {
34        match self {
35            State::Truthy => true,
36            State::DefaultValue => true,
37            State::Empty => true,
38            State::Blank => true,
39        }
40    }
41
42    fn is_empty(self) -> bool {
43        match self {
44            State::Truthy => true,
45            State::DefaultValue => true,
46            State::Empty => true,
47            State::Blank => true,
48        }
49    }
50
51    fn is_blank(self) -> bool {
52        match self {
53            State::Truthy => true,
54            State::DefaultValue => true,
55            State::Empty => true,
56            State::Blank => true,
57        }
58    }
59}
60
61impl fmt::Display for State {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        write!(f, "")
64    }
65}
66
67impl ValueView for State {
68    fn as_debug(&self) -> &dyn fmt::Debug {
69        self
70    }
71
72    fn render(&self) -> DisplayCow<'_> {
73        DisplayCow::Borrowed(self)
74    }
75    fn source(&self) -> DisplayCow<'_> {
76        DisplayCow::Owned(Box::new(super::StrDisplay {
77            s: self.type_name(),
78        }))
79    }
80    fn type_name(&self) -> &'static str {
81        match self {
82            State::Truthy => "truthy",
83            State::DefaultValue => "default",
84            State::Empty => "empty",
85            State::Blank => "blank",
86        }
87    }
88    fn query_state(&self, state: State) -> bool {
89        match state {
90            State::Truthy => self.is_truthy(),
91            State::DefaultValue => self.is_default(),
92            State::Empty => self.is_empty(),
93            State::Blank => self.is_blank(),
94        }
95    }
96
97    fn to_kstr(&self) -> KStringCow<'_> {
98        KStringCow::from_static("")
99    }
100    fn to_value(&self) -> Value {
101        Value::State(*self)
102    }
103
104    fn as_state(&self) -> Option<State> {
105        Some(*self)
106    }
107}