1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
use std::fmt;
use std::ops;

#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct StringBuf(String);

impl StringBuf {
    pub fn new() -> Self { StringBuf(String::new()) }

    pub fn append<'s, S: Into<&'s str>>(self, string: S) -> Self {
        self + string.into()
    }
}


impl ops::Deref for StringBuf {
    type Target = String;

    fn deref(&self) -> &String {  &self.0  }
}


impl fmt::Display for StringBuf {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}


impl<'s> From<&'s str> for StringBuf {
    fn from(string: &'s str) -> StringBuf {  StringBuf(string.to_string())  }
}

impl From<String> for StringBuf {
    fn from(string: String) -> StringBuf {  StringBuf(string)  }
}

impl From<StringBuf> for String {
    fn from(str_buf: StringBuf) -> String {  str_buf.0  }
}



impl<'s, S> ops::Add<S> for StringBuf where S: Into<&'s str> {
    type Output = StringBuf;

    fn add(mut self, string: S) -> StringBuf {
        self.0.push_str(string.into());
        self
    }
}

impl<'s, S> ops::AddAssign<S> for StringBuf where S: Into<&'s str> {
    fn add_assign(&mut self, string: S) {
        self.0.push_str(string.into());
    }
}

#[cfg(test)]
mod tests {
    use *;

    #[test]
    fn instantiation() {
        let sb = StringBuf::new();
        assert_eq!("", String::from(sb))
    }

    #[test]
    fn append() {
        let sb = StringBuf::new().append("foo").append("bar!");
        assert_eq!("foobar!", String::from(sb));
    }


    #[test]
    fn add() {
        let sb = StringBuf::new();
        let s = String::from("baz!");
        let sb = sb + "foo" + "bar!" + &*s;
        assert_eq!("foobar!baz!", String::from(sb));
    }

    #[test]
    fn add_assign() {
        let mut sb = StringBuf::new();
        sb += "foo";
        sb += "bar!";
        assert_eq!("foobar!", String::from(sb));
    }

    #[test]
    fn deref() {
        let sb = StringBuf::from("foobar!");
        assert_eq!("foobar!", *sb);
    }

    #[test]
    fn monster() {
        // This just combines lots of StringBuf operations.
        let mut sb = StringBuf::from("foo!bar!");
        sb = sb + "baz!" + "qux!";
        sb += "quux!";
        assert_eq!("foo!bar!baz!qux!quux!corge!", *sb.append("corge!"));
    }
}