Skip to content

Commit c182e41

Browse files
committed
perf: Optimize Buffer::push()
fix #8
1 parent aa0afb1 commit c182e41

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

sailfish/src/runtime/buffer.rs

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -149,8 +149,13 @@ impl Buffer {
149149

150150
#[inline]
151151
pub fn push(&mut self, data: char) {
152-
let mut buf = [0u8; 4];
153-
self.push_str(data.encode_utf8(&mut buf));
152+
// Question: Is it safe to pass uninitialized memory to `encode_utf8` function?
153+
unsafe {
154+
self.reserve_small(4);
155+
let bp = self.data.add(self.len) as *mut [u8; 4];
156+
let result = data.encode_utf8(&mut *bp);
157+
self.len += result.len();
158+
}
154159
}
155160

156161
#[cfg_attr(feature = "perf-inline", inline)]
@@ -400,4 +405,18 @@ mod tests {
400405
s2.clear();
401406
let _ = s2.clone();
402407
}
408+
409+
#[test]
410+
fn push() {
411+
for initial_capacity in &[0, 4, 16] {
412+
let mut s = Buffer::with_capacity(*initial_capacity);
413+
414+
s.push('a');
415+
s.push('é');
416+
s.push('A');
417+
s.push('🄫');
418+
419+
assert_eq!(s.as_str(), "aéA🄫");
420+
}
421+
}
403422
}

0 commit comments

Comments
 (0)