summaryrefslogtreecommitdiff
path: root/core/java/com/android/internal/util/LineBreakBufferedWriter.java
blob: 552a93f6666a82540dc943344fe36dd3b03f0e17 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.internal.util;

import java.io.PrintWriter;
import java.io.Writer;
import java.util.Arrays;

/**
 * A writer that breaks up its output into chunks before writing to its out writer,
 * and which is linebreak aware, i.e., chunks will created along line breaks, if
 * possible.
 *
 * Note: this class is not thread-safe.
 */
public class LineBreakBufferedWriter extends PrintWriter {

    /**
     * A buffer to collect data until the buffer size is reached.
     *
     * Note: we manage a char[] ourselves to avoid an allocation when printing to the
     *       out writer. Otherwise a StringBuilder would have been simpler to use.
     */
    private char[] buffer;

    /**
     * The index of the first free element in the buffer.
     */
    private int bufferIndex;

    /**
     * The chunk size (=maximum buffer size) to use for this writer.
     */
    private final int bufferSize;


    /**
     * Index of the last newline character discovered in the buffer. The writer will try
     * to split there.
     */
    private int lastNewline = -1;

    /**
     * The line separator for println().
     */
    private final String lineSeparator;

    /**
     * Create a new linebreak-aware buffered writer with the given output and buffer
     * size. The initial capacity will be a default value.
     * @param out The writer to write to.
     * @param bufferSize The maximum buffer size.
     */
    public LineBreakBufferedWriter(Writer out, int bufferSize) {
        this(out, bufferSize, 16);  // 16 is the default size of a StringBuilder buffer.
    }

    /**
     * Create a new linebreak-aware buffered writer with the given output, buffer
     * size and initial capacity.
     * @param out The writer to write to.
     * @param bufferSize The maximum buffer size.
     * @param initialCapacity The initial capacity of the internal buffer.
     */
    public LineBreakBufferedWriter(Writer out, int bufferSize, int initialCapacity) {
        super(out);
        this.buffer = new char[Math.min(initialCapacity, bufferSize)];
        this.bufferIndex = 0;
        this.bufferSize = bufferSize;
        this.lineSeparator = System.getProperty("line.separator");
    }

    /**
     * Flush the current buffer. This will ignore line breaks.
     */
    @Override
    public void flush() {
        writeBuffer(bufferIndex);
        bufferIndex = 0;
        super.flush();
    }

    @Override
    public void write(int c) {
        if (bufferIndex < buffer.length) {
            buffer[bufferIndex] = (char)c;
            bufferIndex++;
            if ((char)c == '\n') {
                lastNewline = bufferIndex;
            }
        } else {
            // This should be an uncommon case, we mostly expect char[] and String. So
            // let the chunking be handled by the char[] case.
            write(new char[] { (char)c }, 0 ,1);
        }
    }

    @Override
    public void println() {
        write(lineSeparator);
    }

    @Override
    public void write(char[] buf, int off, int len) {
        while (bufferIndex + len > bufferSize) {
            // Find the next newline in the buffer, see if that's below the limit.
            // Repeat.
            int nextNewLine = -1;
            int maxLength = bufferSize - bufferIndex;
            for (int i = 0; i < maxLength; i++) {
                if (buf[off + i] == '\n') {
                    if (bufferIndex + i < bufferSize) {
                        nextNewLine = i;
                    } else {
                        break;
                    }
                }
            }

            if (nextNewLine != -1) {
                // We can add some more data.
                appendToBuffer(buf, off, nextNewLine);
                writeBuffer(bufferIndex);
                bufferIndex = 0;
                lastNewline = -1;
                off += nextNewLine + 1;
                len -= nextNewLine + 1;
            } else if (lastNewline != -1) {
                // Use the last newline.
                writeBuffer(lastNewline);
                removeFromBuffer(lastNewline + 1);
                lastNewline = -1;
            } else {
                // OK, there was no newline, break at a full buffer.
                int rest = bufferSize - bufferIndex;
                appendToBuffer(buf, off, rest);
                writeBuffer(bufferIndex);
                bufferIndex = 0;
                off += rest;
                len -= rest;
            }
        }

        // Add to the buffer, this will fit.
        if (len > 0) {
            // Add the chars, find the last newline.
            appendToBuffer(buf, off, len);
            for (int i = len - 1; i >= 0; i--) {
                if (buf[off + i] == '\n') {
                    lastNewline = bufferIndex - len + i;
                    break;
                }
            }
        }
    }

    @Override
    public void write(String s, int off, int len) {
        while (bufferIndex + len > bufferSize) {
            // Find the next newline in the buffer, see if that's below the limit.
            // Repeat.
            int nextNewLine = -1;
            int maxLength = bufferSize - bufferIndex;
            for (int i = 0; i < maxLength; i++) {
                if (s.charAt(off + i) == '\n') {
                    if (bufferIndex + i < bufferSize) {
                        nextNewLine = i;
                    } else {
                        break;
                    }
                }
            }

            if (nextNewLine != -1) {
                // We can add some more data.
                appendToBuffer(s, off, nextNewLine);
                writeBuffer(bufferIndex);
                bufferIndex = 0;
                lastNewline = -1;
                off += nextNewLine + 1;
                len -= nextNewLine + 1;
            } else if (lastNewline != -1) {
                // Use the last newline.
                writeBuffer(lastNewline);
                removeFromBuffer(lastNewline + 1);
                lastNewline = -1;
            } else {
                // OK, there was no newline, break at a full buffer.
                int rest = bufferSize - bufferIndex;
                appendToBuffer(s, off, rest);
                writeBuffer(bufferIndex);
                bufferIndex = 0;
                off += rest;
                len -= rest;
            }
        }

        // Add to the buffer, this will fit.
        if (len > 0) {
            // Add the chars, find the last newline.
            appendToBuffer(s, off, len);
            for (int i = len - 1; i >= 0; i--) {
                if (s.charAt(off + i) == '\n') {
                    lastNewline = bufferIndex - len + i;
                    break;
                }
            }
        }
    }

    /**
     * Append the characters to the buffer. This will potentially resize the buffer,
     * and move the index along.
     * @param buf The char[] containing the data.
     * @param off The start index to copy from.
     * @param len The number of characters to copy.
     */
    private void appendToBuffer(char[] buf, int off, int len) {
        if (bufferIndex + len > buffer.length) {
            ensureCapacity(bufferIndex + len);
        }
        System.arraycopy(buf, off, buffer, bufferIndex, len);
        bufferIndex += len;
    }

    /**
     * Append the characters from the given string to the buffer. This will potentially
     * resize the buffer, and move the index along.
     * @param s The string supplying the characters.
     * @param off The start index to copy from.
     * @param len The number of characters to copy.
     */
    private void appendToBuffer(String s, int off, int len) {
        if (bufferIndex + len > buffer.length) {
            ensureCapacity(bufferIndex + len);
        }
        s.getChars(off, off + len, buffer, bufferIndex);
        bufferIndex += len;
    }

    /**
     * Resize the buffer. We use the usual double-the-size plus constant scheme for
     * amortized O(1) insert. Note: we expect small buffers, so this won't check for
     * overflow.
     * @param capacity The size to be ensured.
     */
    private void ensureCapacity(int capacity) {
        int newSize = buffer.length * 2 + 2;
        if (newSize < capacity) {
            newSize = capacity;
        }
        buffer = Arrays.copyOf(buffer, newSize);
    }

    /**
     * Remove the characters up to (and excluding) index i from the buffer. This will
     * not resize the buffer, but will update bufferIndex.
     * @param i The number of characters to remove from the front.
     */
    private void removeFromBuffer(int i) {
        int rest = bufferIndex - i;
        if (rest > 0) {
            System.arraycopy(buffer, bufferIndex - rest, buffer, 0, rest);
            bufferIndex = rest;
        } else {
            bufferIndex = 0;
        }
    }

    /**
     * Helper method, write the given part of the buffer, [start,length), to the output.
     * @param length The number of characters to flush.
     */
    private void writeBuffer(int length) {
        if (length > 0) {
            super.write(buffer, 0, length);
        }
    }
}