From 90ecaf40b50a1960bc7c5760f7a402d521bf539b Mon Sep 17 00:00:00 2001 From: pedrocarlo Date: Tue, 4 Feb 2025 14:38:01 -0300 Subject: [PATCH] removed unnecessary string allocations for escaped json value --- core/json/mod.rs | 36 ++++++++++++++---------------------- 1 file changed, 14 insertions(+), 22 deletions(-) diff --git a/core/json/mod.rs b/core/json/mod.rs index d9ebb9405..4d972c150 100644 --- a/core/json/mod.rs +++ b/core/json/mod.rs @@ -685,34 +685,26 @@ pub fn json_quote(value: &OwnedValue) -> crate::Result { return Ok(value.to_owned()); } - let escaped_value: String = t - .value.to_string_lossy() - .chars() - .flat_map(|c| match c { - '"' => vec!['\\', c], - '\n' => vec!['\\', 'n'], - '\r' => vec!['\\', 'r'], - '\t' => vec!['\\', 't'], - '\\' => vec!['\\', '\\'], - '\u{0008}' => vec!['\\', 'b'], - '\u{000c}' => vec!['\\', 'f'], - c => vec![c], - }) - .collect(); + let mut escaped_value = String::with_capacity(t.value.len()); + escaped_value.push('"'); + for c in t.value.to_string_lossy().chars() { + match c { + '"' | '\\' | '\n' | '\r' | '\t' | '\u{0008}' | '\u{000c}' => { + escaped_value.push('\\'); + escaped_value.push(c); + } + c => escaped_value.push(c), + } + } + escaped_value.push('"'); - let quoted_value = format!("\"{}\"", escaped_value); - - Ok(OwnedValue::Text(Text::new(Rc::new(quoted_value)))) + Ok(OwnedValue::Text(Text::new(Rc::new(escaped_value)))) } // Numbers are unquoted in json OwnedValue::Integer(ref int) => Ok(OwnedValue::Integer(int.to_owned())), OwnedValue::Float(ref float) => Ok(OwnedValue::Float(float.to_owned())), OwnedValue::Blob(_) => crate::bail_constraint_error!("JSON cannot hold BLOB values"), - OwnedValue::Null => { - let null_value = "null".to_string(); - - Ok(OwnedValue::Text(Text::new(Rc::new(null_value)))) - } + OwnedValue::Null => Ok(OwnedValue::Text(Text::new(Rc::new("null".to_string())))), _ => { // TODO not too sure what message should be here crate::bail_parse_error!("Syntax error");