1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 package com.sun.star.comp.sdbc;
22 
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.Reader;
26 
27 public class ReaderInputStream extends InputStream {
28     private final Reader reader;
29     private int nextByte = -1;
30 
ReaderInputStream(Reader reader)31     public ReaderInputStream(Reader reader) {
32         this.reader = reader;
33     }
34 
35     @Override
close()36     public void close() throws IOException {
37         reader.close();
38     }
39 
40     @Override
read()41     public int read() throws IOException {
42         if (nextByte >= 0) {
43             int currentByte = nextByte;
44             nextByte = -1;
45             return currentByte;
46         } else {
47             int c = reader.read();
48             if (c < 0) {
49                 return c;
50             }
51             nextByte = (byte) ((c >>> 8) & 0xff);
52             return c & 0xff;
53         }
54     }
55 
56 
57     @Override
read(byte[] b, int off, int len)58     public int read(byte[] b, int off, int len) throws IOException {
59         if ((off < 0) || (len < 0) || (off + len > b.length)) {
60             throw new IndexOutOfBoundsException();
61         } else if (len == 0) {
62             return 0;
63         } else if (len == 1) {
64             int next = read();
65             if (next < 0) {
66                 return next;
67             }
68             b[off] = (byte) next;
69             return 1;
70         } else {
71             int charCount = len / 2;
72             char[] chars = new char[charCount];
73             int charsRead = reader.read(chars);
74             if (charsRead < 0) {
75                 return charsRead;
76             }
77             int byteLength = len & ~1;
78             for (int i = 0; i < byteLength; i++) {
79                 b[off + i] = (byte)(chars[i/2] >>> (8*(i&1)));
80             }
81             return byteLength;
82         }
83     }
84 }
85