001: /*
002: * @(#)CharBufferReader.java 1.2 04/12/06
003: *
004: * Copyright (c) 2001-2004 Sun Microsystems, Inc. All Rights Reserved.
005: *
006: * See the file "LICENSE.txt" for information on usage and redistribution
007: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
008: */
009: package pnuts.nio;
010:
011: import java.io.*;
012: import java.nio.*;
013:
014: public class CharBufferReader extends Reader {
015:
016: private CharBuffer cbuf;
017: private int length;
018: private int next = 0;
019: private int mark = 0;
020:
021: public CharBufferReader(CharBuffer cbuf) {
022: this .cbuf = cbuf;
023: this .length = cbuf.length();
024: }
025:
026: private void ensureOpen() throws IOException {
027: if (cbuf == null) {
028: throw new IOException("Stream closed");
029: }
030: }
031:
032: public int read() throws IOException {
033: synchronized (lock) {
034: ensureOpen();
035: if (next >= length) {
036: return -1;
037: }
038: return cbuf.get(next++);
039: }
040: }
041:
042: public int read(char ca[], int off, int len) throws IOException {
043: synchronized (lock) {
044: ensureOpen();
045: if ((off < 0) || (off > ca.length) || (len < 0)
046: || ((off + len) > ca.length) || ((off + len) < 0)) {
047: throw new IndexOutOfBoundsException();
048: } else if (len == 0) {
049: return 0;
050: }
051: if (next >= length)
052: return -1;
053: int n = Math.min(length - next, len);
054: cbuf.get(ca, off, n);
055: next += n;
056: return n;
057: }
058: }
059:
060: public long skip(long ns) throws IOException {
061: synchronized (lock) {
062: ensureOpen();
063: if (next >= length) {
064: return 0;
065: }
066: long n = Math.min(length - next, ns);
067: next += n;
068: return n;
069: }
070: }
071:
072: public boolean ready() throws IOException {
073: synchronized (lock) {
074: ensureOpen();
075: return true;
076: }
077: }
078:
079: public boolean markSupported() {
080: return true;
081: }
082:
083: public void mark(int readAheadLimit) throws IOException {
084: if (readAheadLimit < 0) {
085: throw new IllegalArgumentException("Read-ahead limit < 0");
086: }
087: synchronized (lock) {
088: ensureOpen();
089: mark = next;
090: }
091: }
092:
093: public void reset() throws IOException {
094: synchronized (lock) {
095: ensureOpen();
096: next = mark;
097: }
098: }
099:
100: public void close() {
101: this.cbuf = null;
102: }
103: }
|