Debian Codegraph @

core/java/com/android/internal/util/BinaryXmlSerializer.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.android.internal.util;
18
19 import static org.xmlpull.v1.XmlPullParser.CDSECT;
20 import static org.xmlpull.v1.XmlPullParser.COMMENT;
21 import static org.xmlpull.v1.XmlPullParser.DOCDECL;
22 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
23 import static org.xmlpull.v1.XmlPullParser.END_TAG;
24 import static org.xmlpull.v1.XmlPullParser.ENTITY_REF;
25 import static org.xmlpull.v1.XmlPullParser.IGNORABLE_WHITESPACE;
26 import static org.xmlpull.v1.XmlPullParser.PROCESSING_INSTRUCTION;
27 import static org.xmlpull.v1.XmlPullParser.START_DOCUMENT;
28 import static org.xmlpull.v1.XmlPullParser.START_TAG;
29 import static org.xmlpull.v1.XmlPullParser.TEXT;
30
31 import android.annotation.NonNull;
32 import android.annotation.Nullable;
33 import android.util.TypedXmlSerializer;
34
35 import org.xmlpull.v1.XmlPullParser;
36 import org.xmlpull.v1.XmlSerializer;
37
38 import java.io.IOException;
39 import java.io.OutputStream;
40 import java.io.Writer;
41 import java.nio.charset.StandardCharsets;
42 import java.util.Arrays;
43
44 /**
45 * Serializer that writes XML documents using a custom binary wire protocol
46 * which benchmarking has shown to be 4.3x faster and use 2.4x less disk space
47 * than {@code Xml.newFastSerializer()} for a typical {@code packages.xml}.
48 * <p>
49 * The high-level design of the wire protocol is to directly serialize the event
50 * stream, while efficiently and compactly writing strongly-typed primitives
51 * delivered through the {@link TypedXmlSerializer} interface.
52 * <p>
53 * Each serialized event is a single byte where the lower half is a normal
54 * {@link XmlPullParser} token and the upper half is an optional data type
55 * signal, such as {@link #TYPE_INT}.
56 * <p>
57 * This serializer has some specific limitations:
58 * <ul>
59 * <li>Only the UTF-8 encoding is supported.
60 * <li>Variable length values, such as {@code byte[]} or {@link String}, are
61 * limited to 65,535 bytes in length. Note that {@link String} values are stored
62 * as UTF-8 on the wire.
63 * <li>Namespaces, prefixes, properties, and options are unsupported.
64 * </ul>
65 */
66 public final class BinaryXmlSerializer implements TypedXmlSerializer {
67 /**
68 * The wire protocol always begins with a well-known magic value of
69 * {@code ABX_}, representing "Android Binary XML." The final byte is a
70 * version number which may be incremented as the protocol changes.
71 */
72 public static final byte[] PROTOCOL_MAGIC_VERSION_0 = new byte[] { 0x41, 0x42, 0x58, 0x00 };
73
74 /**
75 * Internal token which represents an attribute associated with the most
76 * recent {@link #START_TAG} token.
77 */
78 static final int ATTRIBUTE = 15;
79
80 static final int TYPE_NULL = 1 << 4;
81 static final int TYPE_STRING = 2 << 4;
82 static final int TYPE_STRING_INTERNED = 3 << 4;
83 static final int TYPE_BYTES_HEX = 4 << 4;
84 static final int TYPE_BYTES_BASE64 = 5 << 4;
85 static final int TYPE_INT = 6 << 4;
86 static final int TYPE_INT_HEX = 7 << 4;
87 static final int TYPE_LONG = 8 << 4;
88 static final int TYPE_LONG_HEX = 9 << 4;
89 static final int TYPE_FLOAT = 10 << 4;
90 static final int TYPE_DOUBLE = 11 << 4;
91 static final int TYPE_BOOLEAN_TRUE = 12 << 4;
92 static final int TYPE_BOOLEAN_FALSE = 13 << 4;
93
94 private FastDataOutput mOut;
95
96 /**
97 * Stack of tags which are currently active via {@link #startTag} and which
98 * haven't been terminated via {@link #endTag}.
99 */
100 private int mTagCount = 0;
101 private String[] mTagNames;
102
103 /**
104 * Write the given token and optional {@link String} into our buffer.
105 */
106 private void writeToken(int token, @Nullable String text) throws IOException {
107 if (text != null) {
108 mOut.writeByte(token | TYPE_STRING);
109 mOut.writeUTF(text);
110 } else {
111 mOut.writeByte(token | TYPE_NULL);
112 }
113 }
114
115 @Override
116 public void setOutput(@NonNull OutputStream os, @Nullable String encoding) throws IOException {
117 if (encoding != null && !StandardCharsets.UTF_8.name().equalsIgnoreCase(encoding)) {
118 throw new UnsupportedOperationException();
119 }
120
121 mOut = FastDataOutput.obtainUsing4ByteSequences(os);
122 mOut.write(PROTOCOL_MAGIC_VERSION_0);
123
124 mTagCount = 0;
125 mTagNames = new String[8];
126 }
127
128 @Override
129 public void setOutput(Writer writer) {
130 throw new UnsupportedOperationException();
131 }
132
133 @Override
134 public void flush() throws IOException {
135 if (mOut != null) {
136 mOut.flush();
137 }
138 }
139
140 @Override
141 public void startDocument(@Nullable String encoding, @Nullable Boolean standalone)
142 throws IOException {
143 if (encoding != null && !StandardCharsets.UTF_8.name().equalsIgnoreCase(encoding)) {
144 throw new UnsupportedOperationException();
145 }
146 if (standalone != null && !standalone) {
147 throw new UnsupportedOperationException();
148 }
149 mOut.writeByte(START_DOCUMENT | TYPE_NULL);
150 }
151
152 @Override
153 public void endDocument() throws IOException {
154 mOut.writeByte(END_DOCUMENT | TYPE_NULL);
155 flush();
156
157 mOut.release();
158 mOut = null;
159 }
160
161 @Override
162 public int getDepth() {
163 return mTagCount;
164 }
165
166 @Override
167 public String getNamespace() {
168 // Namespaces are unsupported
169 return XmlPullParser.NO_NAMESPACE;
170 }
171
172 @Override
173 public String getName() {
174 return mTagNames[mTagCount - 1];
175 }
176
177 @Override
178 public XmlSerializer startTag(String namespace, String name) throws IOException {
179 if (namespace != null && !namespace.isEmpty()) throw illegalNamespace();
180 if (mTagCount == mTagNames.length) {
181 mTagNames = Arrays.copyOf(mTagNames, mTagCount + (mTagCount >> 1));
182 }
183 mTagNames[mTagCount++] = name;
184 mOut.writeByte(START_TAG | TYPE_STRING_INTERNED);
185 mOut.writeInternedUTF(name);
186 return this;
187 }
188
189 @Override
190 public XmlSerializer endTag(String namespace, String name) throws IOException {
191 if (namespace != null && !namespace.isEmpty()) throw illegalNamespace();
192 mTagCount--;
193 mOut.writeByte(END_TAG | TYPE_STRING_INTERNED);
194 mOut.writeInternedUTF(name);
195 return this;
196 }
197
198 @Override
199 public XmlSerializer attribute(String namespace, String name, String value) throws IOException {
200 if (namespace != null && !namespace.isEmpty()) throw illegalNamespace();
201 mOut.writeByte(ATTRIBUTE | TYPE_STRING);
202 mOut.writeInternedUTF(name);
203 mOut.writeUTF(value);
204 return this;
205 }
206
207 @Override
208 public XmlSerializer attributeInterned(String namespace, String name, String value)
209 throws IOException {
210 if (namespace != null && !namespace.isEmpty()) throw illegalNamespace();
211 mOut.writeByte(ATTRIBUTE | TYPE_STRING_INTERNED);
212 mOut.writeInternedUTF(name);
213 mOut.writeInternedUTF(value);
214 return this;
215 }
216
217 @Override
218 public XmlSerializer attributeBytesHex(String namespace, String name, byte[] value)
219 throws IOException {
220 if (namespace != null && !namespace.isEmpty()) throw illegalNamespace();
221 mOut.writeByte(ATTRIBUTE | TYPE_BYTES_HEX);
222 mOut.writeInternedUTF(name);
223 mOut.writeShort(value.length);
224 mOut.write(value);
225 return this;
226 }
227
228 @Override
229 public XmlSerializer attributeBytesBase64(String namespace, String name, byte[] value)
230 throws IOException {
231 if (namespace != null && !namespace.isEmpty()) throw illegalNamespace();
232 mOut.writeByte(ATTRIBUTE | TYPE_BYTES_BASE64);
233 mOut.writeInternedUTF(name);
234 mOut.writeShort(value.length);
235 mOut.write(value);
236 return this;
237 }
238
239 @Override
240 public XmlSerializer attributeInt(String namespace, String name, int value)
241 throws IOException {
242 if (namespace != null && !namespace.isEmpty()) throw illegalNamespace();
243 mOut.writeByte(ATTRIBUTE | TYPE_INT);
244 mOut.writeInternedUTF(name);
245 mOut.writeInt(value);
246 return this;
247 }
248
249 @Override
250 public XmlSerializer attributeIntHex(String namespace, String name, int value)
251 throws IOException {
252 if (namespace != null && !namespace.isEmpty()) throw illegalNamespace();
253 mOut.writeByte(ATTRIBUTE | TYPE_INT_HEX);
254 mOut.writeInternedUTF(name);
255 mOut.writeInt(value);
256 return this;
257 }
258
259 @Override
260 public XmlSerializer attributeLong(String namespace, String name, long value)
261 throws IOException {
262 if (namespace != null && !namespace.isEmpty()) throw illegalNamespace();
263 mOut.writeByte(ATTRIBUTE | TYPE_LONG);
264 mOut.writeInternedUTF(name);
265 mOut.writeLong(value);
266 return this;
267 }
268
269 @Override
270 public XmlSerializer attributeLongHex(String namespace, String name, long value)
271 throws IOException {
272 if (namespace != null && !namespace.isEmpty()) throw illegalNamespace();
273 mOut.writeByte(ATTRIBUTE | TYPE_LONG_HEX);
274 mOut.writeInternedUTF(name);
275 mOut.writeLong(value);
276 return this;
277 }
278
279 @Override
280 public XmlSerializer attributeFloat(String namespace, String name, float value)
281 throws IOException {
282 if (namespace != null && !namespace.isEmpty()) throw illegalNamespace();
283 mOut.writeByte(ATTRIBUTE | TYPE_FLOAT);
284 mOut.writeInternedUTF(name);
285 mOut.writeFloat(value);
286 return this;
287 }
288
289 @Override
290 public XmlSerializer attributeDouble(String namespace, String name, double value)
291 throws IOException {
292 if (namespace != null && !namespace.isEmpty()) throw illegalNamespace();
293 mOut.writeByte(ATTRIBUTE | TYPE_DOUBLE);
294 mOut.writeInternedUTF(name);
295 mOut.writeDouble(value);
296 return this;
297 }
298
299 @Override
300 public XmlSerializer attributeBoolean(String namespace, String name, boolean value)
301 throws IOException {
302 if (namespace != null && !namespace.isEmpty()) throw illegalNamespace();
303 if (value) {
304 mOut.writeByte(ATTRIBUTE | TYPE_BOOLEAN_TRUE);
305 mOut.writeInternedUTF(name);
306 } else {
307 mOut.writeByte(ATTRIBUTE | TYPE_BOOLEAN_FALSE);
308 mOut.writeInternedUTF(name);
309 }
310 return this;
311 }
312
313 @Override
314 public XmlSerializer text(char[] buf, int start, int len) throws IOException {
315 writeToken(TEXT, new String(buf, start, len));
316 return this;
317 }
318
319 @Override
320 public XmlSerializer text(String text) throws IOException {
321 writeToken(TEXT, text);
322 return this;
323 }
324
325 @Override
326 public void cdsect(String text) throws IOException {
327 writeToken(CDSECT, text);
328 }
329
330 @Override
331 public void entityRef(String text) throws IOException {
332 writeToken(ENTITY_REF, text);
333 }
334
335 @Override
336 public void processingInstruction(String text) throws IOException {
337 writeToken(PROCESSING_INSTRUCTION, text);
338 }
339
340 @Override
341 public void comment(String text) throws IOException {
342 writeToken(COMMENT, text);
343 }
344
345 @Override
346 public void docdecl(String text) throws IOException {
347 writeToken(DOCDECL, text);
348 }
349
350 @Override
351 public void ignorableWhitespace(String text) throws IOException {
352 writeToken(IGNORABLE_WHITESPACE, text);
353 }
354
355 @Override
356 public void setFeature(String name, boolean state) {
357 // Quietly handle no-op features
358 if ("http://xmlpull.org/v1/doc/features.html#indent-output".equals(name)) {
359 return;
360 }
361 // Features are not supported
362 throw new UnsupportedOperationException();
363 }
364
365 @Override
366 public boolean getFeature(String name) {
367 // Features are not supported
368 throw new UnsupportedOperationException();
369 }
370
371 @Override
372 public void setProperty(String name, Object value) {
373 // Properties are not supported
374 throw new UnsupportedOperationException();
375 }
376
377 @Override
378 public Object getProperty(String name) {
379 // Properties are not supported
380 throw new UnsupportedOperationException();
381 }
382
383 @Override
384 public void setPrefix(String prefix, String namespace) {
385 // Prefixes are not supported
386 throw new UnsupportedOperationException();
387 }
388
389 @Override
390 public String getPrefix(String namespace, boolean generatePrefix) {
391 // Prefixes are not supported
392 throw new UnsupportedOperationException();
393 }
394
395 private static IllegalArgumentException illegalNamespace() {
396 throw new IllegalArgumentException("Namespaces are not supported");
397 }
398 }