Skip to content

Commit 81d7e2a

Browse files
dppadriaanm
authored andcommitted
Fixed XML Utility.escape method to conform to X...
Fixed XML Utility.escape method to conform to XML spec. Closes #3014
1 parent 3adacdf commit 81d7e2a

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

src/library/scala/xml/Utility.scala

+23-5
Original file line numberDiff line numberDiff line change
@@ -106,11 +106,29 @@ object Utility extends AnyRef with parsing.TokenTests
106106
* @param s ...
107107
* @return ...
108108
*/
109-
final def escape(text: String, s: StringBuilder): StringBuilder =
110-
text.foldLeft(s)((s, c) => escMap.get(c) match {
111-
case Some(str) => s append str
112-
case None => s append c
113-
})
109+
final def escape(text: String, s: StringBuilder): StringBuilder = {
110+
// Implemented per XML spec:
111+
// http://www.w3.org/International/questions/qa-controls
112+
// imperative code 3x-4x faster than current implementation
113+
// dpp (David Pollak) 2010/02/03
114+
val len = text.length
115+
var pos = 0
116+
while (pos < len) {
117+
text.charAt(pos) match {
118+
case '<' => s.append("&lt;")
119+
case '>' => s.append("&gt;")
120+
case '&' => s.append("&amp;")
121+
case '"' => s.append("&quot;")
122+
case '\n' => s.append('\n')
123+
case '\r' => s.append('\r')
124+
case '\t' => s.append('\t')
125+
case c => if (c >= ' ') s.append(c)
126+
}
127+
128+
pos += 1
129+
}
130+
s
131+
}
114132

115133
/**
116134
* Appends unescaped string to <code>s</code>, amp becomes &amp;

0 commit comments

Comments
 (0)