From df19e6b005c6a08e2b068ec0468c50db31387002 Mon Sep 17 00:00:00 2001 From: Richard Walters Date: Thu, 15 Oct 2020 12:53:28 -0700 Subject: Refactoring for encode_element; thanks to @Serayen for suggesting them * We can write! directly into a String (as lone as we use std::fmt::Write). * We can pre-allocate the encoded String with an estimate of the number of bytes we need. If we need more, String will allocate more, and only in doubles (not every `push` or `write!`). --- src/codec.rs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/codec.rs b/src/codec.rs index 05fcee8..1002b8e 100644 --- a/src/codec.rs +++ b/src/codec.rs @@ -1,5 +1,6 @@ use std::collections::HashSet; use std::convert::TryFrom; +use std::fmt::Write; use super::context::Context; use super::error::Error; @@ -43,12 +44,12 @@ pub fn encode_element( element: &[u8], allowed_characters: &HashSet ) -> String { - element.iter() - .map(|ci| { - match char::try_from(*ci) { - Ok(c) if allowed_characters.contains(&c) => c.to_string(), - _ => format!("%{:02X}", ci), - } - }) - .collect() + let mut encoding = String::with_capacity(element.len()); + for ci in element { + match char::try_from(*ci) { + Ok(c) if allowed_characters.contains(&c) => encoding.push(c), + _ => write!(encoding, "%{:02X}", ci).unwrap(), + } + } + encoding } -- cgit v1.2.3