Debian Codegraph @

net/sf/saxon/serialize/charcode/JavaCharacterSet.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.serialize.charcode;
9
10 import net.sf.saxon.tree.tiny.CharSlice;
11
12 import java.nio.charset.Charset;
13 import java.nio.charset.CharsetEncoder;
14 import java.util.HashMap;
15
16 /**
17 * This class establishes properties of a character set that is
18 * known to the Java VM but not specifically known to Saxon. It determines whether particular
19 * characters are encodable by calling {@link CharsetEncoder#canEncode(char)}, and then caches
20 * this information locally.
21 */
22
23 public class JavaCharacterSet implements CharacterSet {
24
25 public static HashMap<Charset, JavaCharacterSet> map;
26
27 private CharsetEncoder encoder;
28
29 // This class is written on the assumption that the CharsetEncoder.canEncode()
30 // method may be expensive. For BMP characters, it therefore remembers the results
31 // so each character is only looked up the first time it is encountered.
32
33 private byte[] charinfo = new byte[65536];
34 // rely on initialization to zeroes
35
36 //private final static byte UNKNOWN = 0;
37 private static final byte GOOD = 1;
38 private static final byte BAD = 2;
39
40 private JavaCharacterSet(Charset charset) {
41 encoder = charset.newEncoder();
42 }
43
44 public static synchronized JavaCharacterSet makeCharSet(/*@NotNull*/ Charset charset) {
45 if (map == null) {
46 map = new HashMap<Charset, JavaCharacterSet>(10);
47 }
48 JavaCharacterSet c = map.get(charset);
49 if (c == null) {
50 c = new JavaCharacterSet(charset);
51 map.put(charset, c);
52 }
53 return c;
54 }
55
56 public final boolean inCharset(int c) {
57 // Assume ASCII chars are always OK
58 if (c <= 127) {
59 return true;
60 }
61 if (c <= 65535) {
62 if (charinfo[c] == GOOD) {
63 return true;
64 } else if (charinfo[c] == BAD) {
65 return false;
66 } else {
67 if (encoder.canEncode((char) c)) {
68 charinfo[c] = GOOD;
69 return true;
70 } else {
71 charinfo[c] = BAD;
72 return false;
73 }
74 }
75 } else {
76 char[] cc = new char[2];
77 cc[0] = UTF16CharacterSet.highSurrogate(c);
78 cc[1] = UTF16CharacterSet.lowSurrogate(c);
79 return encoder.canEncode(new CharSlice(cc));
80 }
81
82 }
83
84 public String getCanonicalName() {
85 return encoder.charset().name();
86 }
87 }
88