simple_string_builder/
lib.rs

1use std::str;
2
3/// ## Simple String Builder
4/// Super basic string builder based on my memory of Javas
5/// Accepts Strings and &str
6/// Some one probobly did this better
7
8/// # Example
9/// 
10/// ```
11/// let name = "quinn".to_string();
12/// let mut b = Builder::new();
13/// b.append("Hello");
14/// b.append(" My Name Is".to_string());
15/// b.append(format!(" {} and I Like you 😍", name));
16/// let: Result<String, Utf8Error> = b.try_to_string(); 
17/// ```
18#[derive(Debug)]
19pub struct Builder { 
20    builder: Vec<u8> 
21}
22
23
24/// Trait to convert to byte vec implement this to allow you struct to be used by builder
25pub trait ToBytes {
26    ///convert your type to bytes repersenting string of your type
27    fn to_bytes(self) -> Vec<u8>;
28}
29
30impl ToBytes for String {
31    fn to_bytes(self) -> Vec<u8> {
32        self.into_bytes()
33    }
34}
35
36impl ToBytes for &str {
37    fn to_bytes(self) -> Vec<u8> {
38        self.as_bytes().to_vec()
39    }
40}
41
42
43impl Builder {
44    pub fn new() -> Self {
45        Builder {
46            builder: Vec::default()
47        }
48    }
49
50    pub fn append<B: ToBytes>(&mut self, buf: B) {
51        self.builder.append(&mut buf.to_bytes())
52    }
53
54    ///Try to convert to string fails if bytes don't repersent utf-8
55    pub fn try_to_string(&self) -> Result<String, str::Utf8Error> {
56        let string_maybe = str::from_utf8(&self.builder);
57        match string_maybe {
58            Ok(s) => Ok(s.to_owned()),
59            Err(e) => Err(e)
60        }
61    }
62
63}
64
65#[cfg(test)]
66mod tests {
67    use super::Builder;
68
69    #[test]
70    fn test_string() {
71        let name = "quinn".to_string();
72        let mut b = Builder::new();
73        b.append("Hello");
74        b.append(" My Name Is".to_string());
75        b.append(format!(" {} and I Like you 😍", name));
76
77        assert_eq!(b.try_to_string().unwrap(), "Hello My Name Is quinn and I Like you 😍".to_owned())
78    }
79}
80
81
82