simple_string_builder/
lib.rs1use std::str;
2
3#[derive(Debug)]
19pub struct Builder {
20 builder: Vec<u8>
21}
22
23
24pub trait ToBytes {
26 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 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