Skip to content

Commit 2358f0f

Browse files
authored
refactor!: do not reserve memory in escape_into (#36)
1 parent f408c90 commit 2358f0f

File tree

1 file changed

+5
-8
lines changed

1 file changed

+5
-8
lines changed

src/lib.rs

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -326,13 +326,11 @@ pub fn escape(value: &str) -> String {
326326
unsafe { String::from_utf8_unchecked(buf) }
327327
}
328328

329-
pub fn escape_into<S: AsRef<str>>(value: S, dst: &mut Vec<u8>) -> usize {
329+
/// # Panics
330+
///
331+
/// Panics if the buffer is not large enough. Allocate enough capacity for dst.
332+
pub fn escape_into<S: AsRef<str>>(value: S, dst: &mut Vec<u8>) {
330333
let value = value.as_ref();
331-
let needed_capacity = value.len() * 6 + 32 + 3;
332-
333-
// Ensure we have enough capacity
334-
dst.reserve(needed_capacity);
335-
336334
let old_len = dst.len();
337335

338336
// SAFETY: We've reserved enough capacity above, and format_string will
@@ -343,7 +341,6 @@ pub fn escape_into<S: AsRef<str>>(value: S, dst: &mut Vec<u8>) -> usize {
343341
std::slice::from_raw_parts_mut(dst.as_mut_ptr().add(old_len), dst.capacity() - old_len);
344342
let cnt = format_string(value, spare);
345343
dst.set_len(old_len + cnt);
346-
cnt
347344
}
348345
}
349346

@@ -572,7 +569,7 @@ mod tests {
572569
.take(if cfg!(miri) { 10 } else { sources.len() })
573570
{
574571
assert_eq!(escape(source), serde_json::to_string(&source).unwrap());
575-
let mut output = String::new();
572+
let mut output = String::with_capacity(source.len() * 6 + 32 + 3);
576573
escape_into(source, unsafe { output.as_mut_vec() });
577574
assert_eq!(output, serde_json::to_string(&source).unwrap());
578575
}

0 commit comments

Comments
 (0)