[librsvg: 7/10] Reduce allocations in whitespace normalize_default.



commit 7edfd2c0e78ff2241097280dbbdea226bb8e9579
Author: Jordan Petridis <jordanpetridis protonmail com>
Date:   Fri Dec 8 18:23:14 2017 +0200

    Reduce allocations in whitespace normalize_default.
    
    Instead of spliting->trimming->join use itertools::coalesce.

 rust/src/space.rs | 23 +++++++++++++++++------
 1 file changed, 17 insertions(+), 6 deletions(-)
---
diff --git a/rust/src/space.rs b/rust/src/space.rs
index 36ddf55..ee4ae76 100644
--- a/rust/src/space.rs
+++ b/rust/src/space.rs
@@ -32,12 +32,23 @@ pub fn xml_space_normalize(mode: XmlSpace, s: &str) -> String {
 // characters will be consolidated.
 fn normalize_default<'a, S: Into<Cow<'a, str>>>(s: S) -> String {
     let s = s.into();
-    s.chars()
+    s.trim()
+        .chars()
         .filter(|ch| *ch != '\n')
+        .map(|ch| {
+            match ch {
+                '\t' => ' ',
+                c => c
+            }
+        })
+        .coalesce(|current, next| {
+            if current == ' ' && next == ' ' {
+                Ok(' ')
+            } else {
+                Err((current, next))
+            }
+        })
         .collect::<String>()
-        // split at whitespace, also trims whitespace.
-        .split_whitespace()
-        .join(" ")
 }
 
 // From https://www.w3.org/TR/SVG/text.html#WhiteSpace
@@ -77,8 +88,8 @@ mod tests {
     fn xml_space_default() {
         assert_eq!(xml_space_normalize(XmlSpace::Default, "\n    WS example\n    indented lines\n  "),
                    "WS example indented lines");
-        assert_eq!(xml_space_normalize(XmlSpace::Default, "\n  \t  \tWS \t\t\texample\n  \t  indented 
lines\t\t  \n  "),
-                   "WS example indented lines");
+        assert_eq!(xml_space_normalize(XmlSpace::Default, "\n  \t  \tWS \t\t\texample\n  \t  indented 
liines\t\t  \n  "),
+                   "WS example indented liines");
 
         assert_eq!(xml_space_normalize(XmlSpace::Default, "\nWS example\nnon-indented lines\n  "),
                    "WS examplenon-indented lines");


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]