stylish_stringlike/text/
pushable.rs

1/// Trait for text objects that can have content pushed into them without changing type.
2pub trait Pushable<T: ?Sized> {
3    /// Pushes another text object onto this one. [`String`] implements this
4    /// trivially.
5    ///
6    /// # Example
7    /// ```rust
8    /// use stylish_stringlike::text::Pushable;
9    /// let mut foobar = String::from("foo");
10    /// let bar = "bar";
11    /// Pushable::<str>::push(&mut foobar, &bar);
12    /// assert_eq!(foobar, String::from("foobar"));
13    /// ```
14    fn push(&mut self, other: &T);
15}
16
17impl Pushable<str> for String {
18    fn push(&mut self, other: &str) {
19        self.push_str(other);
20    }
21}
22
23impl Pushable<String> for String {
24    fn push(&mut self, other: &String) {
25        self.push_str(other.as_str());
26    }
27}
28
29impl<S, O: Sized> Pushable<Option<O>> for S
30where
31    S: Pushable<O>,
32{
33    fn push(&mut self, other: &Option<O>) {
34        match other {
35            Some(ref o) => self.push(o),
36            None => {}
37        }
38    }
39}
40
41#[cfg(test)]
42mod test {
43    use super::*;
44    #[test]
45    fn push_string() {
46        let mut foobar = String::from("foo");
47        let bar = String::from("bar");
48        Pushable::<String>::push(&mut foobar, &bar);
49        assert_eq!(foobar, String::from("foobar"));
50    }
51    #[test]
52    fn push_string_option() {
53        let mut foobar = String::from("foo");
54        let bar = Some(String::from("bar"));
55        let baz: Option<String> = None;
56        Pushable::push(&mut foobar, &bar);
57        Pushable::push(&mut foobar, &baz);
58        assert_eq!(foobar, String::from("foobar"));
59    }
60}