Debian Codegraph @

net/sf/saxon/value/Base64BinaryValue.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.value;
9
10 import net.sf.saxon.expr.sort.AtomicMatchKey;
11 import net.sf.saxon.lib.StringCollator;
12 import net.sf.saxon.om.SequenceTool;
13 import net.sf.saxon.serialize.charcode.UTF16CharacterSet;
14 import net.sf.saxon.trans.XPathException;
15 import net.sf.saxon.tree.util.FastStringBuffer;
16 import net.sf.saxon.type.AtomicType;
17 import net.sf.saxon.type.BuiltInAtomicType;
18
19 import java.util.Arrays;
20
21 /**
22 * A value of type xs:base64Binary
23 * <p><i>Rewritten for Saxon 9.5 to avoid dependency on the open-source Netscape code, whose
24 * license many users were unhappy with.</i></p>
25 */
26
27 public class Base64BinaryValue extends AtomicValue implements AtomicMatchKey, Comparable {
28
29 private byte[] binaryValue;
30
31
32 /**
33 * Constructor: create a base64Binary value from a supplied string in base64 encoding
34 *
35 * @param s the lexical representation of the base64 binary value. There is no requirement
36 * that whitespace should already be collapsed.
37 * @throws net.sf.saxon.trans.XPathException
38 * if the supplied value is not in the lexical
39 * space of the xs:base64Binary data type
40 */
41
42 public Base64BinaryValue(/*@NotNull*/ CharSequence s) throws XPathException {
43 binaryValue = decode(s);
44 typeLabel = BuiltInAtomicType.BASE64_BINARY;
45 }
46
47 /**
48 * Constructor: create a base64Binary value from a given array of bytes
49 *
50 * @param value array of bytes holding the octet sequence
51 */
52
53 public Base64BinaryValue(byte[] value) {
54 binaryValue = value;
55 typeLabel = BuiltInAtomicType.BASE64_BINARY;
56 }
57
58 /**
59 * Create a copy of this atomic value (usually so that the type label can be changed).
60 * The type label of the copy will be reset to the primitive type.
61 *
62 * @param typeLabel the type label to be attached to the value, a subtype of xs:base64Binary
63 * @return the copied value
64 */
65
66 /*@NotNull*/
67 public AtomicValue copyAsSubType(AtomicType typeLabel) {
68 Base64BinaryValue v = new Base64BinaryValue(binaryValue);
69 v.typeLabel = typeLabel;
70 return v;
71 }
72
73 /**
74 * Get the binary value
75 *
76 * @return the octet sequence that is the typed value
77 */
78
79 public byte[] getBinaryValue() {
80 return binaryValue;
81 }
82
83 /*@NotNull*/
84 public BuiltInAtomicType getPrimitiveType() {
85 return BuiltInAtomicType.BASE64_BINARY;
86 }
87
88 /**
89 * Convert to string
90 *
91 * @return the canonical representation.
92 */
93
94 /*@NotNull*/
95 public String getPrimitiveStringValue() {
96 return encode(binaryValue).toString();
97 }
98
99 /**
100 * Get the number of octets in the value
101 *
102 * @return the number of octets
103 */
104
105 public int getLengthInOctets() {
106 return binaryValue.length;
107 }
108
109 /**
110 * Support XML Schema comparison semantics
111 */
112
113 /*@NotNull*/
114 public Comparable getSchemaComparable() {
115 return new Base64BinaryComparable();
116 }
117
118 /**
119 * Private inner class to support XML Schema comparison semantics
120 */
121
122 private class Base64BinaryComparable implements Comparable {
123
124 /*@NotNull*/
125 public Base64BinaryValue getBase64BinaryValue() {
126 return Base64BinaryValue.this;
127 }
128
129 public int compareTo(/*@NotNull*/ Object o) {
130 if (o instanceof Base64BinaryComparable &&
131 Arrays.equals(getBase64BinaryValue().binaryValue,
132 ((Base64BinaryComparable) o).getBase64BinaryValue().binaryValue)) {
133 return 0;
134 } else {
135 return SequenceTool.INDETERMINATE_ORDERING;
136 }
137 }
138
139 @SuppressWarnings({"EqualsWhichDoesntCheckParameterClass"})
140 public boolean equals(/*@NotNull*/ Object o) {
141 return compareTo(o) == 0;
142 }
143
144 public int hashCode() {
145 return Base64BinaryValue.this.hashCode();
146 }
147 }
148
149
150 /**
151 * Get an object value that implements the XPath equality and ordering comparison semantics for this value.
152 * If the ordered parameter is set to true, the result will be a Comparable and will support a compareTo()
153 * method with the semantics of the XPath lt/gt operator, provided that the other operand is also obtained
154 * using the getXPathComparable() method. In all cases the result will support equals() and hashCode() methods
155 * that support the semantics of the XPath eq operator, again provided that the other operand is also obtained
156 * using the getXPathComparable() method. A context argument is supplied for use in cases where the comparison
157 * semantics are context-sensitive, for example where they depend on the implicit timezone or the default
158 * collation.
159 *
160 * @param ordered true if an ordered comparison is required. In this case the result is null if the
161 * type is unordered; in other cases the returned value will be a Comparable.
162 * @param collator the collation (not used in this version of the method)
163 * @param implicitTimezone the XPath dynamic evaluation context, used in cases where the comparison is context
164 */
165
166 /*@Nullable*/
167 public AtomicMatchKey getXPathComparable(boolean ordered, StringCollator collator, int implicitTimezone) {
168 return this;
169 }
170
171 /**
172 * Test if the two base64Binary values are equal.
173 */
174
175 public boolean equals(/*@NotNull*/ Object other) {
176 return other instanceof Base64BinaryValue
177 && Arrays.equals(binaryValue, ((Base64BinaryValue) other).binaryValue);
178 }
179
180 public int hashCode() {
181 return byteArrayHashCode(binaryValue);
182 }
183
184 protected static int byteArrayHashCode(/*@NotNull*/ byte[] value) {
185 long h = 0;
186 for (int i = 0; i < Math.min(value.length, 64); i++) {
187 h = (h << 1) ^ value[i];
188 }
189 return (int) ((h >> 32) ^ h);
190 }
191
192 ////////////////////////////////////////////////////////////////////////////////////////////////////////////
193 // Code for converting to/from base64 representation
194 ////////////////////////////////////////////////////////////////////////////////////////////////////////////
195
196 private final static String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
197
198 private static int[] encoding = new int[64];
199 private static int[] decoding = new int[128];
200
201 static {
202 Arrays.fill(decoding, -1);
203 for (int i = 0; i < alphabet.length(); i++) {
204 char c = alphabet.charAt(i);
205 encoding[i] = c;
206 decoding[c] = i;
207 }
208 }
209
210 /**
211 * Encode a byte sequence into base64 representation
212 *
213 * @param value the byte sequence
214 * @return the base64 representation
215 */
216
217 public static CharSequence encode(byte[] value) {
218 FastStringBuffer buff = new FastStringBuffer(value.length);
219 int whole = value.length - value.length % 3;
220 // process bytes 3 at a time: 3 bytes => 4 characters
221 for (int i = 0; i < whole; i += 3) {
222 // 3 bytes = 24 bits = 4 characters
223 int val = ((((int) value[i]) & 0xff) << 16) + ((((int) value[i + 1]) & 0xff) << 8) + ((((int) value[i + 2]) & 0xff));
224 buff.append((char) encoding[(val >> 18) & 0x3f]);
225 buff.append((char) encoding[(val >> 12) & 0x3f]);
226 buff.append((char) encoding[(val >> 6) & 0x3f]);
227 buff.append((char) encoding[val & 0x3f]);
228 }
229 int remainder = (value.length % 3);
230 switch (remainder) {
231 case 0:
232 default:
233 // no action
234 break;
235 case 1: {
236 // pad the final 8 bits to 12 (2 groups of 6)
237 int val = ((((int) value[whole]) & 0xff) << 4);
238 buff.append((char) encoding[(val >> 6) & 0x3f]);
239 buff.append((char) encoding[val & 0x3f]);
240 buff.append("==");
241 break;
242 }
243 case 2: {
244 // pad the final 16 bits to 18 (3 groups of 6)
245 int val = ((((int) value[whole]) & 0xff) << 10) + ((((int) value[whole + 1]) & 0xff) << 2);
246 buff.append((char) encoding[(val >> 12) & 0x3f]);
247 buff.append((char) encoding[(val >> 6) & 0x3f]);
248 buff.append((char) encoding[val & 0x3f]);
249 buff.append("=");
250 break;
251 }
252 }
253 return buff.condense();
254 }
255
256 /**
257 * Decode a character string in base64 notation to yield the encoded octets
258 *
259 * @param in the lexical representation
260 * @return the array of octets represented
261 * @throws XPathException if the format is invalid (as required by XSD, this method
262 * does draconian error handling, unlike many other base64 decoders which are liberal
263 * in what they accept)
264 */
265
266 public static byte[] decode(CharSequence in) throws XPathException {
267 char[] unit = new char[4];
268 byte[] result = new byte[in.length()];
269 int bytesUsed = 0;
270 int i = 0;
271 int u = 0;
272 int pad = 0;
273 int chars = 0;
274 char last = 0;
275
276 // process characters 4 at a time: 4 characters => 3 bytes
277 while (i < in.length()) {
278 char c = in.charAt(i++);
279 if (!Whitespace.isWhite(c)) {
280 chars++;
281 if (c == '=') {
282 // all following chars must be '=' or whitespace
283 pad = 1;
284 for (int k = i; k < in.length(); k++) {
285 char ch = in.charAt(k);
286 if (ch == '=') {
287 pad++;
288 chars++;
289 } else if (Whitespace.isWhite(ch)) {
290 // no action
291 } else {
292 throw new XPathException("Base64 padding character '=' is followed by non-padding characters", "FORG0001");
293 }
294 }
295 if (pad == 1 && "AEIMQUYcgkosw048".indexOf(last) < 0) {
296 throw new XPathException("In base64, if the value ends with a single '=' character, then the preceding character must be" +
297 " one of [AEIMQUYcgkosw048]", "FORG0001");
298 } else if (pad == 2 && "AQgw".indexOf(last) < 0) {
299 throw new XPathException("In base64, if the value ends with '==', then the preceding character must be" +
300 " one of [AQgw]", "FORG0001");
301 }
302 // number of padding characters must be the number required
303 if (pad > 2) {
304 throw new XPathException("Found " + pad + " '=' characters at end of base64 value; max is 2", "FORG0001");
305 }
306 if (pad != ((4 - u) % 4)) {
307 throw new XPathException("Required " + ((4 - u) % 4) + " '=' characters at end of base64 value; found " + pad, "FORG0001");
308 }
309 // append 0 sextets corresponding to number of padding characters
310 for (int p = 0; p < pad; p++) {
311 unit[u++] = 'A';
312 }
313 i = in.length();
314 } else {
315 last = c;
316 unit[u++] = c;
317 }
318 if (u == 4) {
319 int t = (decodeChar(unit[0]) << 18) +
320 (decodeChar(unit[1]) << 12) +
321 (decodeChar(unit[2]) << 6) +
322 (decodeChar(unit[3]));
323 if (bytesUsed + 3 > result.length) {
324 byte[] r2 = new byte[bytesUsed * 2];
325 System.arraycopy(result, 0, r2, 0, bytesUsed);
326 result = r2;
327 }
328 result[bytesUsed++] = (byte) ((t >> 16) & 0xff);
329 result[bytesUsed++] = (byte) ((t >> 8) & 0xff);
330 result[bytesUsed++] = (byte) (t & 0xff);
331 u = 0;
332 }
333 }
334 if (i >= in.length()) {
335 bytesUsed -= pad;
336 break;
337 }
338 }
339 if (chars % 4 != 0) {
340 throw new XPathException("Length of base64 value must be a multiple of four", "FORG0001");
341 }
342 byte[] r3 = new byte[bytesUsed];
343 System.arraycopy(result, 0, r3, 0, bytesUsed);
344 return r3;
345
346 }
347
348 private static int decodeChar(char c) throws XPathException {
349 int d = c < 128 ? decoding[c] : -1;
350 if (d == -1) {
351 if (UTF16CharacterSet.isSurrogate(c)) {
352 throw new XPathException("Invalid character (surrogate pair) in base64 value", "FORG0001");
353 } else {
354 throw new XPathException("Invalid character '" + c + "' in base64 value", "FORG0001");
355 }
356 }
357 return d;
358 }
359
360 public int compareTo(Object o) {
361 byte[] other = ((Base64BinaryValue)o).binaryValue;
362 int len0 = binaryValue.length;
363 int len1 = other.length;
364 int shorter = java.lang.Math.min(len0, len1);
365 for (int i=0; i<shorter; i++) {
366 int a = (int)binaryValue[i] & 0xff;
367 int b = (int)other[i] & 0xff;
368 if (a != b) {
369 return a < b ? -1 : +1;
370 }
371 }
372 return Integer.signum(len0 - len1);
373 }
374 }
375