stepflow_data/value/
string_value.rs1use std::borrow::{Borrow, Cow};
2use super::{Value, BaseValue, InvalidValue};
3
4#[derive(Debug, PartialEq, Clone)]
5pub struct StringValue {
6 val: Cow<'static, str>,
7}
8
9impl StringValue {
10 pub fn try_new<STR>(val: STR) -> Result<Self, InvalidValue>
11 where STR: Into<Cow<'static, str>>
12 {
13 let val = val.into();
14 Self::validate(&val)?;
15 Ok(Self { val })
16 }
17
18 pub fn validate(val: &Cow<'static, str>) -> Result<(), InvalidValue> {
19 if val.is_empty() {
20 return Err(InvalidValue::Empty);
21 }
22 Ok(())
23 }
24
25 pub fn val(&self) -> &str {
26 self.val.borrow()
27 }
28 pub fn boxed(self) -> Box<dyn Value> {
29 Box::new(self)
30 }
31}
32
33define_value_impl!(StringValue);
34
35impl std::str::FromStr for StringValue {
36 type Err = InvalidValue;
37
38 fn from_str(s: &str) -> Result<Self, Self::Err> {
39 StringValue::try_new(s.to_owned())
40 }
41}
42
43
44#[cfg(test)]
45mod tests {
46 use super::{InvalidValue, StringValue};
47
48 #[test]
49 fn test_good_string() {
50 let string_value = StringValue::try_new("hi").unwrap();
51 assert_eq!(string_value.val(), "hi");
52 }
53
54 #[test]
55 fn test_bad_string() {
56 assert_eq!(StringValue::try_new(""), Err(InvalidValue::Empty));
57 }
58
59 #[test]
60 fn test_fromstr() {
61 assert!(matches!("".parse::<StringValue>(), Err(_)));
62 assert_eq!("valid".parse::<StringValue>().unwrap(), StringValue::try_new("valid").unwrap());
63 }
64}