perf: Zero-copy conversion from String into Buffer

This commit is contained in:
Kogia-sima 2020-08-04 03:14:21 +09:00
parent 941cd965ab
commit d79a5d3b4b
1 changed files with 9 additions and 4 deletions

View File

@ -222,13 +222,18 @@ impl fmt::Write for Buffer {
} }
impl From<String> for Buffer { impl From<String> for Buffer {
/// Always copy the inner data from `String` because it is dangerous to /// Shrink the data and pass raw pointer directory to buffer
/// handle the raw components of `String`.
/// ///
/// This operation is `O(n)` /// This operation is `O(1)`
#[inline] #[inline]
fn from(other: String) -> Buffer { fn from(other: String) -> Buffer {
Buffer::from(other.as_str()) let bs = other.into_boxed_str();
let data = unsafe { &mut *Box::into_raw(bs) };
Buffer {
data: data.as_mut_ptr(),
len: data.len(),
capacity: data.len(),
}
} }
} }