Skip to main content

tilo_resource/
non_blank.rs

1//! Text that says something: a title, a name, a message.
2//!
3//! An action that refuses blank text takes a [`NonBlank`] instead of a
4//! `String`. The only ways to make one are [`NonBlank::parse`] and reading it
5//! from JSON, and both refuse text that is empty or only whitespace. So a
6//! view cannot hand such an action whatever its field holds: it parses the
7//! field, and a control bound through [`ActionRef::try_map`] stays disabled
8//! while the field does not parse. An agent, a remote peer and the shell's
9//! argument step are checked by the same type at the boundary, and the
10//! schema they read says it (`minLength` 1, a non-space character).
11//!
12//! The text is kept trimmed: what is stored is what the person meant, never
13//! the spaces around it.
14//!
15//! [`ActionRef::try_map`]: crate::ActionRef::try_map
16//!
17//! A `String` is not a `NonBlank`; it has to be parsed:
18//!
19//! ```compile_fail
20//! fn rename(name: tilo_resource::NonBlank) -> String {
21//!     name.into()
22//! }
23//! rename(String::from("Groceries"));
24//! ```
25//!
26//! ```compile_fail
27//! let name: tilo_resource::NonBlank = String::from("Groceries").into();
28//! ```
29//!
30//! ```
31//! use tilo_resource::NonBlank;
32//! assert_eq!(NonBlank::parse("  Groceries ").unwrap().as_str(), "Groceries");
33//! assert!(NonBlank::parse(" \t").is_none());
34//! ```
35
36use std::fmt;
37
38use serde_json::{Value, json};
39
40/// Text with at least one character that is not whitespace, trimmed. See
41/// the [module](self).
42///
43/// It is written, read and printed through the code for `String` (reading
44/// then checks the text, in code compiled once), so an app that takes one
45/// reuses what it already has for strings rather than a copy for this type.
46#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
47#[repr(transparent)]
48pub struct NonBlank(String);
49
50impl NonBlank {
51    /// `text` trimmed, or `None` when nothing is left.
52    #[must_use]
53    pub fn parse(text: &str) -> Option<Self> {
54        let trimmed = text.trim();
55        (!trimmed.is_empty()).then(|| Self(trimmed.to_owned()))
56    }
57
58    /// `text` trimmed, or [`Blank`] when nothing is left: [`Self::parse`]
59    /// for text already owned, as JSON reads it.
60    #[inline(never)]
61    fn from_owned(text: String) -> Result<Self, Blank> {
62        if text.len() == text.trim().len() {
63            return if text.is_empty() {
64                Err(Blank)
65            } else {
66                Ok(Self(text))
67            };
68        }
69        Self::parse(&text).ok_or(Blank)
70    }
71
72    /// The text.
73    #[must_use]
74    pub fn as_str(&self) -> &str {
75        &self.0
76    }
77
78    /// The text, owned.
79    #[must_use]
80    pub fn into_string(self) -> String {
81        self.0
82    }
83}
84
85/// Why text is not a [`NonBlank`]: there is nothing in it but whitespace.
86#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub struct Blank;
88
89/// What [`Blank`] says.
90const BLANK: &str = "blank text where something must be said";
91
92impl fmt::Display for Blank {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        f.write_str(BLANK)
95    }
96}
97
98impl std::error::Error for Blank {}
99
100impl std::str::FromStr for NonBlank {
101    type Err = Blank;
102
103    fn from_str(text: &str) -> Result<Self, Blank> {
104        Self::parse(text).ok_or(Blank)
105    }
106}
107
108impl std::ops::Deref for NonBlank {
109    type Target = str;
110
111    fn deref(&self) -> &str {
112        &self.0
113    }
114}
115
116impl AsRef<str> for NonBlank {
117    fn as_ref(&self) -> &str {
118        &self.0
119    }
120}
121
122impl From<NonBlank> for String {
123    fn from(text: NonBlank) -> Self {
124        text.0
125    }
126}
127
128impl fmt::Debug for NonBlank {
129    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130        fmt::Debug::fmt(&self.0, f)
131    }
132}
133
134impl fmt::Display for NonBlank {
135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136        f.write_str(&self.0)
137    }
138}
139
140impl PartialEq<str> for NonBlank {
141    fn eq(&self, other: &str) -> bool {
142        self.0 == other
143    }
144}
145
146impl PartialEq<&str> for NonBlank {
147    fn eq(&self, other: &&str) -> bool {
148        self.0 == *other
149    }
150}
151
152impl serde::Serialize for NonBlank {
153    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
154        self.0.serialize(serializer)
155    }
156}
157
158impl<'de> serde::Deserialize<'de> for NonBlank {
159    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
160        // Read as a `String` is (the reader every app already has), then
161        // checked by code compiled once; the error is made from the plain
162        // message, which needs no formatting machinery per reader.
163        let text = String::deserialize(deserializer)?;
164        Self::from_owned(text).map_err(|Blank| <D::Error as serde::de::Error>::custom(BLANK))
165    }
166}
167
168impl crate::JsonSchema for NonBlank {
169    fn json_schema() -> Value {
170        json!({"type": "string", "minLength": 1, "pattern": "\\S"})
171    }
172    fn field_type(_: &mut crate::TypeSet) -> crate::FieldType {
173        crate::FieldType::Text
174    }
175}
176
177#[cfg(test)]
178mod tests {
179    use super::NonBlank;
180    use crate::JsonSchema as _;
181
182    tilo_test_env::scenario! {
183        fn non_blank_text_refuses_blank_however_it_is_read;
184
185        phase parsing_trims_and_refuses_blank_text;
186        {
187            assert_eq!(NonBlank::parse(" a b ").unwrap(), "a b");
188            assert_eq!(NonBlank::parse(""), None);
189            assert_eq!(NonBlank::parse(" \n\t "), None);
190        }
191
192        phase json_is_read_through_the_same_parse;
193        {
194            let read = |value| serde_json::from_value::<NonBlank>(value);
195            assert_eq!(read(serde_json::json!(" Ship it ")).unwrap(), "Ship it");
196            assert!(read(serde_json::json!("   ")).is_err());
197            assert!(read(serde_json::json!("")).is_err());
198            assert!(read(serde_json::json!(null)).is_err());
199            let written = serde_json::to_value(NonBlank::parse("x").unwrap()).unwrap();
200            assert_eq!(written, serde_json::json!("x"));
201        }
202
203        phase the_schema_refuses_what_parsing_refuses;
204        {
205            let schema = NonBlank::json_schema();
206            assert_eq!(schema["minLength"], 1);
207            let pattern = schema["pattern"].as_str().unwrap();
208            assert_eq!(pattern, "\\S");
209        }
210    }
211}