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
107
108
//! Build &str using existing [u8] array
/*
use std;
pub struct StrBuilder<'a> {
buf: &'a mut [u8],
written: usize,
}
impl<'a> StrBuilder<'a> {
pub fn new(buf: &'a mut [u8]) -> Self {
StrBuilder {
buf,
written: 0
}
}
pub fn add(mut self, chunk: &str) -> Self {
let src = chunk.as_bytes();
let dst = &mut self.buf[self.written..self.written + src.len()];
dst.copy_from_slice(src);
self.written += src.len();
self
}
pub fn get_str(self) -> Result<&'a str, std::str::Utf8Error> {
std::str::from_utf8(self.buf)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_build() {
let expected = "Hello, World!";
let mut buf = [0; 13];
let s = StrBuilder::new(&mut buf)
.add("Hello")
.add(", ")
.add("World")
.add("!")
.add("")
.get_str();
assert_eq!(s.unwrap(), expected);
}
#[test]
#[should_panic]
fn test_overflow() {
let expected = "Hello, World!";
let mut buf = [0; 13];
let s = StrBuilder::new(&mut buf)
.add("Hello")
.add(", ")
.add("World")
.add("!")
.add("a")
.get_str();
assert_eq!(s.unwrap(), expected);
}
#[test]
fn test_empty() {
let expected = "";
let mut buf = [0; 0];
let s = StrBuilder::new(&mut buf)
.add("")
.add("")
.add("")
.get_str();
assert_eq!(s.unwrap(), expected);
let s = StrBuilder::new(&mut buf)
.get_str();
assert_eq!(s.unwrap(), expected);
}
#[test]
fn test_incomplete() {
let expected = "Hello";
let mut buf = [0; 13];
let s = StrBuilder::new(&mut buf)
.add("Hello")
.get_str();
assert_eq!(&s.unwrap()[..5], expected);
}
}
*/