1 package org.apache.lucene.store; 2 3 18 19 import java.io.IOException ; 20 21 22 public abstract class BufferedIndexInput extends IndexInput { 23 static final int BUFFER_SIZE = BufferedIndexOutput.BUFFER_SIZE; 24 25 private byte[] buffer; 26 27 private long bufferStart = 0; private int bufferLength = 0; private int bufferPosition = 0; 31 public byte readByte() throws IOException { 32 if (bufferPosition >= bufferLength) 33 refill(); 34 return buffer[bufferPosition++]; 35 } 36 37 public void readBytes(byte[] b, int offset, int len) 38 throws IOException { 39 if (len < BUFFER_SIZE) { 40 for (int i = 0; i < len; i++) b[i + offset] = (byte)readByte(); 42 } else { long start = getFilePointer(); 44 seekInternal(start); 45 readInternal(b, offset, len); 46 47 bufferStart = start + len; bufferPosition = 0; 49 bufferLength = 0; } 51 } 52 53 private void refill() throws IOException { 54 long start = bufferStart + bufferPosition; 55 long end = start + BUFFER_SIZE; 56 if (end > length()) end = length(); 58 bufferLength = (int)(end - start); 59 if (bufferLength <= 0) 60 throw new IOException ("read past EOF"); 61 62 if (buffer == null) 63 buffer = new byte[BUFFER_SIZE]; readInternal(buffer, 0, bufferLength); 65 66 bufferStart = start; 67 bufferPosition = 0; 68 } 69 70 76 protected abstract void readInternal(byte[] b, int offset, int length) 77 throws IOException ; 78 79 public long getFilePointer() { return bufferStart + bufferPosition; } 80 81 public void seek(long pos) throws IOException { 82 if (pos >= bufferStart && pos < (bufferStart + bufferLength)) 83 bufferPosition = (int)(pos - bufferStart); else { 85 bufferStart = pos; 86 bufferPosition = 0; 87 bufferLength = 0; seekInternal(pos); 89 } 90 } 91 92 96 protected abstract void seekInternal(long pos) throws IOException ; 97 98 public Object clone() { 99 BufferedIndexInput clone = (BufferedIndexInput)super.clone(); 100 101 if (buffer != null) { 102 clone.buffer = new byte[BUFFER_SIZE]; 103 System.arraycopy(buffer, 0, clone.buffer, 0, bufferLength); 104 } 105 106 return clone; 107 } 108 109 } 110 | Popular Tags |