Debian Codegraph @

src/tools/org/h2/dev/util/ReaderInputStream.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.dev.util;
7
8 import java.io.BufferedWriter;
9 import java.io.ByteArrayOutputStream;
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.io.OutputStreamWriter;
13 import java.io.Reader;
14 import java.io.Writer;
15 import java.nio.charset.StandardCharsets;
16
17 import org.h2.engine.Constants;
18
19 /**
20 * The reader input stream wraps a reader and convert the character to the UTF-8
21 * format.
22 */
23 public class ReaderInputStream extends InputStream {
24
25 private final Reader reader;
26 private final char[] chars;
27 private final ByteArrayOutputStream out;
28 private final Writer writer;
29 private int pos;
30 private int remaining;
31 private byte[] buffer;
32
33 public ReaderInputStream(Reader reader) {
34 chars = new char[Constants.IO_BUFFER_SIZE];
35 this.reader = reader;
36 out = new ByteArrayOutputStream(Constants.IO_BUFFER_SIZE);
37 writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
38 }
39
40 private void fillBuffer() throws IOException {
41 if (remaining == 0) {
42 pos = 0;
43 remaining = reader.read(chars, 0, Constants.IO_BUFFER_SIZE);
44 if (remaining < 0) {
45 return;
46 }
47 writer.write(chars, 0, remaining);
48 writer.flush();
49 buffer = out.toByteArray();
50 remaining = buffer.length;
51 out.reset();
52 }
53 }
54
55 @Override
56 public int read() throws IOException {
57 if (remaining == 0) {
58 fillBuffer();
59 }
60 if (remaining < 0) {
61 return -1;
62 }
63 remaining--;
64 return buffer[pos++] & 0xff;
65 }
66
67 }