diff options
author | Richard Walters <rwalters@digitalstirling.com> | 2020-10-15 12:53:28 -0700 |
---|---|---|
committer | Richard Walters <rwalters@digitalstirling.com> | 2020-10-15 12:53:28 -0700 |
commit | df19e6b005c6a08e2b068ec0468c50db31387002 (patch) | |
tree | c0dac4b84fd04b0b48e793ee211c674fc85fcef5 | |
parent | 170b711d710a0572fbd396c29be6647a5dcf3836 (diff) |
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!`).
-rw-r--r-- | src/codec.rs | 17 |
1 files 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<char> ) -> 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 } |