1 /*
2 * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
3 *
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Distribution License v. 1.0, which is available at
6 * http://www.eclipse.org/org/documents/edl-v10.php.
7 *
8 * SPDX-License-Identifier: BSD-3-Clause
9 */
10
11 package com.sun.xml.bind.marshaller;
12
13 import java.io.IOException;
14 import java.io.Writer;
15
16 /**
17 * Performs no character escaping. Usable only when the output encoding
18 * is UTF, but this handler gives the maximum performance.
19 *
20 * @author
21 * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
22 */
23 public class MinimumEscapeHandler implements CharacterEscapeHandler {
24
25 private MinimumEscapeHandler() {} // no instanciation please
26
27 public static final CharacterEscapeHandler theInstance = new MinimumEscapeHandler();
28
29 public void escape(char[] ch, int start, int length, boolean isAttVal, Writer out) throws IOException {
30 // avoid calling the Writerwrite method too much by assuming
31 // that the escaping occurs rarely.
32 // profiling revealed that this is faster than the naive code.
33 int limit = start+length;
34 for (int i = start; i < limit; i++) {
35 char c = ch[i];
36 if (c == '&' || c == '<' || c == '>' || c == '\r' || (c == '\n' && isAttVal) || (c == '\"' && isAttVal)) {
37 if (i != start)
38 out.write(ch, start, i - start);
39 start = i + 1;
40 switch (ch[i]) {
41 case '&':
42 out.write("&");
43 break;
44 case '<':
45 out.write("<");
46 break;
47 case '>':
48 out.write(">");
49 break;
50 case '\"':
51 out.write(""");
52 break;
53 case '\n':
54 case '\r':
55 out.write("&#");
56 out.write(Integer.toString(c));
57 out.write(';');
58 break;
59 default:
60 throw new IllegalArgumentException("Cannot escape: '" + c + "'");
61 }
62 }
63 }
64
65 if( start!=limit )
66 out.write(ch,start,limit-start);
67 }
68
69 }
70