File: ReaderInputStream.java

package info (click to toggle)
lib-xp-java 0.5-1
  • links: PTS
  • area: main
  • in suites: potato
  • size: 1,652 kB
  • ctags: 2,424
  • sloc: java: 8,085; makefile: 53; sh: 17; xml: 7
file content (91 lines) | stat: -rw-r--r-- 2,093 bytes parent folder | download | duplicates (3)
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
package com.jclark.xml.sax;

import java.io.Reader;
import java.io.InputStream;
import java.io.IOException;

/**
 * An InputStream of the UTF-16 encoding of a Reader.
 *
 * @version $Revision: 1.3 $ $Date: 1998/05/04 07:46:28 $
 */
public class ReaderInputStream extends InputStream {
  private Reader reader;
  private static final int BUF_SIZE = 4096;
  private char[] buf = new char[BUF_SIZE];
  private int bufIndex = 0;
  private int bufEnd = 1;
  /* true if we have read the first nibble of the character at bufIndex
     but not yet read the second */
  private boolean nibbled = false;

  public ReaderInputStream(Reader reader) {
    this.reader = reader;
    buf[0] = '\ufeff';
  }

  public synchronized int read() throws IOException {
    if (nibbled) {
      nibbled = false;
      return buf[bufIndex++] & 0xff;
    }
    while (bufIndex == bufEnd) {
      bufIndex = 0;
      bufEnd = reader.read(buf, 0, buf.length);
      if (bufEnd < 0) {
	bufEnd = 0;
	return -1;
      }
    }
    nibbled = true;
    return buf[bufIndex] >> 8;
  }

  public synchronized int read(byte b[], int off, int len) throws IOException {
    if (len <= 0)
      return 0;
    int startOff = off;
    if (nibbled) {
      nibbled = false;
      if (b != null)
	b[off] = (byte)(buf[bufIndex] & 0xff);
      bufIndex++;
      off++;
      len--;
    }
    while (len > 0) {
      if (bufIndex == bufEnd) {
	bufIndex = 0;
	bufEnd = reader.read(buf, 0, buf.length);
	if (bufEnd < 0) {
	  bufEnd = 0;
	  if (off != startOff)
	    break;
	  return -1;
	}
	if (bufEnd == 0)
	  return off - startOff;
      }
      if (len == 1) {
	if (b != null)
	  b[off] = (byte)(buf[bufIndex] >> 8);
	off++;
	nibbled = true;
	break;
      }
      if (b != null) {
	b[off++] = (byte)(buf[bufIndex] >> 8);
	b[off++] = (byte)(buf[bufIndex] & 0xff);
      }
      else
	off += 2;
      len -= 2;
      bufIndex++;
    }
    return off - startOff;
  }

  public synchronized void close() throws IOException {
    reader.close();
  }
}