@@ -93,24 +93,35 @@ object Utility extends AnyRef with parsing.TokenTests
93
93
*/
94
94
final def escape (text : String ): String = sbToString(escape(text, _))
95
95
96
+ object Escapes {
97
+ /** For reasons unclear escape and unescape are a long ways from
98
+ * being logical inverses. */
99
+ private val pairs = List (
100
+ " lt" -> '<' ,
101
+ " gt" -> '>' ,
102
+ " amp" -> '&' ,
103
+ " quot" -> '"'
104
+ // comment explaining why this isn't escaped --
105
+ // is valid xhtml but not html, and IE doesn't know it, says jweb
106
+ // "apos" -> '\''
107
+ )
108
+ val escMap = Map ((for ((s, c) <- pairs) yield (c, " &%s;" format s)) : _* )
109
+ val unescMap = Map ((" apos" -> '\' ' ) :: pairs : _* )
110
+ }
111
+ import Escapes ._
112
+
96
113
/**
97
114
* Appends escaped string to <code>s</code>.
98
115
*
99
116
* @param text ...
100
117
* @param s ...
101
118
* @return ...
102
119
*/
103
- final def escape (text : String , s : StringBuilder ): StringBuilder = {
104
- for (c <- text.iterator) c match {
105
- case '<' => s.append(" <" )
106
- case '>' => s.append(" >" )
107
- case '&' => s.append(" &" )
108
- case '"' => s.append(" "" )
109
- // case '\'' => s.append("'") // is valid xhtml but not html, and IE doesn't know it, says jweb
110
- case _ => s.append(c)
111
- }
112
- s
113
- }
120
+ final def escape (text : String , s : StringBuilder ): StringBuilder =
121
+ text.foldLeft(s)((s, c) => escMap.get(c) match {
122
+ case Some (str) => s append str
123
+ case None => s append c
124
+ })
114
125
115
126
/**
116
127
* Appends unescaped string to <code>s</code>, amp becomes &
@@ -122,14 +133,7 @@ object Utility extends AnyRef with parsing.TokenTests
122
133
* entity.
123
134
*/
124
135
final def unescape (ref : String , s : StringBuilder ): StringBuilder =
125
- ref match {
126
- case " lt" => s.append('<' )
127
- case " gt" => s.append('>' )
128
- case " amp" => s.append('&' )
129
- case " quot" => s.append('"' )
130
- case " apos" => s.append('\' ' )
131
- case _ => null
132
- }
136
+ (unescMap get ref) map (s append _) getOrElse null
133
137
134
138
/**
135
139
* Returns a set of all namespaces used in a sequence of nodes
@@ -138,13 +142,8 @@ object Utility extends AnyRef with parsing.TokenTests
138
142
* @param nodes ...
139
143
* @return ...
140
144
*/
141
- def collectNamespaces (nodes : Seq [Node ]): Set [String ] = {
142
- var m = new HashSet [String ]()
143
- val it = nodes.iterator
144
- while (it.hasNext)
145
- collectNamespaces(it.next, m);
146
- m
147
- }
145
+ def collectNamespaces (nodes : Seq [Node ]): Set [String ] =
146
+ nodes.foldLeft(new HashSet [String ]) { (set, x) => collectNamespaces(x, set) ; set }
148
147
149
148
/**
150
149
* Adds all namespaces in node to set.
0 commit comments