Debian Codegraph @

core/java/com/android/internal/util/FastDataOutput.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 android.annotation.NonNull;
20 import android.util.CharsetUtils;
21
22 import dalvik.system.VMRuntime;
23
24 import java.io.BufferedOutputStream;
25 import java.io.Closeable;
26 import java.io.DataOutput;
27 import java.io.DataOutputStream;
28 import java.io.Flushable;
29 import java.io.IOException;
30 import java.io.OutputStream;
31 import java.util.HashMap;
32 import java.util.Objects;
33 import java.util.concurrent.atomic.AtomicReference;
34
35 /**
36 * Optimized implementation of {@link DataOutput} which buffers data in memory
37 * before flushing to the underlying {@link OutputStream}.
38 * <p>
39 * Benchmarks have demonstrated this class is 2x more efficient than using a
40 * {@link DataOutputStream} with a {@link BufferedOutputStream}.
41 */
42 public class FastDataOutput implements DataOutput, Flushable, Closeable {
43 private static final int MAX_UNSIGNED_SHORT = 65_535;
44
45 private static final int DEFAULT_BUFFER_SIZE = 32_768;
46
47 private static AtomicReference<FastDataOutput> sOutCache = new AtomicReference<>();
48
49 private final VMRuntime mRuntime;
50
51 private final byte[] mBuffer;
52 private final long mBufferPtr;
53 private final int mBufferCap;
54 private final boolean mUse4ByteSequence;
55
56 private OutputStream mOut;
57 private int mBufferPos;
58
59 /**
60 * Values that have been "interned" by {@link #writeInternedUTF(String)}.
61 */
62 private final HashMap<String, Short> mStringRefs = new HashMap<>();
63
64 /**
65 * @deprecated callers must specify {@code use4ByteSequence} so they make a
66 * clear choice about working around a long-standing ART bug, as
67 * described by the {@code kUtfUse4ByteSequence} comments in
68 * {@code art/runtime/jni/jni_internal.cc}.
69 */
70 @Deprecated
71 public FastDataOutput(@NonNull OutputStream out, int bufferSize) {
72 this(out, bufferSize, true /* use4ByteSequence */);
73 }
74
75 public FastDataOutput(@NonNull OutputStream out, int bufferSize, boolean use4ByteSequence) {
76 mRuntime = VMRuntime.getRuntime();
77 if (bufferSize < 8) {
78 throw new IllegalArgumentException();
79 }
80
81 mBuffer = (byte[]) mRuntime.newNonMovableArray(byte.class, bufferSize);
82 mBufferPtr = mRuntime.addressOf(mBuffer);
83 mBufferCap = mBuffer.length;
84 mUse4ByteSequence = use4ByteSequence;
85
86 setOutput(out);
87 }
88
89 /**
90 * Obtain a {@link FastDataOutput} configured with the given
91 * {@link OutputStream} and which encodes large code-points using 3-byte
92 * sequences.
93 * <p>
94 * This <em>is</em> compatible with the {@link DataOutput} API contract,
95 * which specifies that large code-points must be encoded with 3-byte
96 * sequences.
97 */
98 public static FastDataOutput obtainUsing3ByteSequences(@NonNull OutputStream out) {
99 return new FastDataOutput(out, DEFAULT_BUFFER_SIZE, false /* use4ByteSequence */);
100 }
101
102 /**
103 * Obtain a {@link FastDataOutput} configured with the given
104 * {@link OutputStream} and which encodes large code-points using 4-byte
105 * sequences.
106 * <p>
107 * This <em>is not</em> compatible with the {@link DataOutput} API contract,
108 * which specifies that large code-points must be encoded with 3-byte
109 * sequences.
110 */
111 public static FastDataOutput obtainUsing4ByteSequences(@NonNull OutputStream out) {
112 FastDataOutput instance = sOutCache.getAndSet(null);
113 if (instance != null) {
114 instance.setOutput(out);
115 return instance;
116 }
117 return new FastDataOutput(out, DEFAULT_BUFFER_SIZE, true /* use4ByteSequence */);
118 }
119
120 /**
121 * Release a {@link FastDataOutput} to potentially be recycled. You must not
122 * interact with the object after releasing it.
123 */
124 public void release() {
125 if (mBufferPos > 0) {
126 throw new IllegalStateException("Lingering data, call flush() before releasing.");
127 }
128
129 mOut = null;
130 mBufferPos = 0;
131 mStringRefs.clear();
132
133 if (mBufferCap == DEFAULT_BUFFER_SIZE && mUse4ByteSequence) {
134 // Try to return to the cache.
135 sOutCache.compareAndSet(null, this);
136 }
137 }
138
139 /**
140 * Re-initializes the object for the new output.
141 */
142 private void setOutput(@NonNull OutputStream out) {
143 mOut = Objects.requireNonNull(out);
144 mBufferPos = 0;
145 mStringRefs.clear();
146 }
147
148 private void drain() throws IOException {
149 if (mBufferPos > 0) {
150 mOut.write(mBuffer, 0, mBufferPos);
151 mBufferPos = 0;
152 }
153 }
154
155 @Override
156 public void flush() throws IOException {
157 drain();
158 mOut.flush();
159 }
160
161 @Override
162 public void close() throws IOException {
163 mOut.close();
164 release();
165 }
166
167 @Override
168 public void write(int b) throws IOException {
169 writeByte(b);
170 }
171
172 @Override
173 public void write(byte[] b) throws IOException {
174 write(b, 0, b.length);
175 }
176
177 @Override
178 public void write(byte[] b, int off, int len) throws IOException {
179 if (mBufferCap < len) {
180 drain();
181 mOut.write(b, off, len);
182 } else {
183 if (mBufferCap - mBufferPos < len) drain();
184 System.arraycopy(b, off, mBuffer, mBufferPos, len);
185 mBufferPos += len;
186 }
187 }
188
189 @Override
190 public void writeUTF(String s) throws IOException {
191 if (mUse4ByteSequence) {
192 writeUTFUsing4ByteSequences(s);
193 } else {
194 writeUTFUsing3ByteSequences(s);
195 }
196 }
197
198 private void writeUTFUsing4ByteSequences(String s) throws IOException {
199 // Attempt to write directly to buffer space if there's enough room,
200 // otherwise fall back to chunking into place
201 if (mBufferCap - mBufferPos < 2 + s.length()) drain();
202
203 // Magnitude of this returned value indicates the number of bytes
204 // required to encode the string; sign indicates success/failure
205 int len = CharsetUtils.toModifiedUtf8Bytes(s, mBufferPtr, mBufferPos + 2, mBufferCap);
206 if (Math.abs(len) > MAX_UNSIGNED_SHORT) {
207 throw new IOException("Modified UTF-8 length too large: " + len);
208 }
209
210 if (len >= 0) {
211 // Positive value indicates the string was encoded into the buffer
212 // successfully, so we only need to prefix with length
213 writeShort(len);
214 mBufferPos += len;
215 } else {
216 // Negative value indicates buffer was too small and we need to
217 // allocate a temporary buffer for encoding
218 len = -len;
219 final byte[] tmp = (byte[]) mRuntime.newNonMovableArray(byte.class, len + 1);
220 CharsetUtils.toModifiedUtf8Bytes(s, mRuntime.addressOf(tmp), 0, tmp.length);
221 writeShort(len);
222 write(tmp, 0, len);
223 }
224 }
225
226 private void writeUTFUsing3ByteSequences(String s) throws IOException {
227 final int len = (int) ModifiedUtf8.countBytes(s, false);
228 if (len > MAX_UNSIGNED_SHORT) {
229 throw new IOException("Modified UTF-8 length too large: " + len);
230 }
231
232 // Attempt to write directly to buffer space if there's enough room,
233 // otherwise fall back to chunking into place
234 if (mBufferCap >= 2 + len) {
235 if (mBufferCap - mBufferPos < 2 + len) drain();
236 writeShort(len);
237 ModifiedUtf8.encode(mBuffer, mBufferPos, s);
238 mBufferPos += len;
239 } else {
240 final byte[] tmp = (byte[]) mRuntime.newNonMovableArray(byte.class, len + 1);
241 ModifiedUtf8.encode(tmp, 0, s);
242 writeShort(len);
243 write(tmp, 0, len);
244 }
245 }
246
247 /**
248 * Write a {@link String} value with the additional signal that the given
249 * value is a candidate for being canonicalized, similar to
250 * {@link String#intern()}.
251 * <p>
252 * Canonicalization is implemented by writing each unique string value once
253 * the first time it appears, and then writing a lightweight {@code short}
254 * reference when that string is written again in the future.
255 *
256 * @see FastDataInput#readInternedUTF()
257 */
258 public void writeInternedUTF(@NonNull String s) throws IOException {
259 Short ref = mStringRefs.get(s);
260 if (ref != null) {
261 writeShort(ref);
262 } else {
263 writeShort(MAX_UNSIGNED_SHORT);
264 writeUTF(s);
265
266 // We can only safely intern when we have remaining values; if we're
267 // full we at least sent the string value above
268 ref = (short) mStringRefs.size();
269 if (ref < MAX_UNSIGNED_SHORT) {
270 mStringRefs.put(s, ref);
271 }
272 }
273 }
274
275 @Override
276 public void writeBoolean(boolean v) throws IOException {
277 writeByte(v ? 1 : 0);
278 }
279
280 @Override
281 public void writeByte(int v) throws IOException {
282 if (mBufferCap - mBufferPos < 1) drain();
283 mBuffer[mBufferPos++] = (byte) ((v >> 0) & 0xff);
284 }
285
286 @Override
287 public void writeShort(int v) throws IOException {
288 if (mBufferCap - mBufferPos < 2) drain();
289 mBuffer[mBufferPos++] = (byte) ((v >> 8) & 0xff);
290 mBuffer[mBufferPos++] = (byte) ((v >> 0) & 0xff);
291 }
292
293 @Override
294 public void writeChar(int v) throws IOException {
295 writeShort((short) v);
296 }
297
298 @Override
299 public void writeInt(int v) throws IOException {
300 if (mBufferCap - mBufferPos < 4) drain();
301 mBuffer[mBufferPos++] = (byte) ((v >> 24) & 0xff);
302 mBuffer[mBufferPos++] = (byte) ((v >> 16) & 0xff);
303 mBuffer[mBufferPos++] = (byte) ((v >> 8) & 0xff);
304 mBuffer[mBufferPos++] = (byte) ((v >> 0) & 0xff);
305 }
306
307 @Override
308 public void writeLong(long v) throws IOException {
309 if (mBufferCap - mBufferPos < 8) drain();
310 int i = (int) (v >> 32);
311 mBuffer[mBufferPos++] = (byte) ((i >> 24) & 0xff);
312 mBuffer[mBufferPos++] = (byte) ((i >> 16) & 0xff);
313 mBuffer[mBufferPos++] = (byte) ((i >> 8) & 0xff);
314 mBuffer[mBufferPos++] = (byte) ((i >> 0) & 0xff);
315 i = (int) v;
316 mBuffer[mBufferPos++] = (byte) ((i >> 24) & 0xff);
317 mBuffer[mBufferPos++] = (byte) ((i >> 16) & 0xff);
318 mBuffer[mBufferPos++] = (byte) ((i >> 8) & 0xff);
319 mBuffer[mBufferPos++] = (byte) ((i >> 0) & 0xff);
320 }
321
322 @Override
323 public void writeFloat(float v) throws IOException {
324 writeInt(Float.floatToIntBits(v));
325 }
326
327 @Override
328 public void writeDouble(double v) throws IOException {
329 writeLong(Double.doubleToLongBits(v));
330 }
331
332 @Override
333 public void writeBytes(String s) throws IOException {
334 // Callers should use writeUTF()
335 throw new UnsupportedOperationException();
336 }
337
338 @Override
339 public void writeChars(String s) throws IOException {
340 // Callers should use writeUTF()
341 throw new UnsupportedOperationException();
342 }
343 }