1 52 53 package com.go.trove.io; 54 55 import java.io.*; 56 57 70 public class PushbackPositionReader extends PositionReader { 71 72 private int mMaxPushback; 73 74 75 private int[] mCharacters; 76 77 78 private int[] mPositions; 79 80 81 private int mCursor; 82 83 84 private int mPushback; 85 86 public PushbackPositionReader(Reader reader) { 87 this(reader, 0); 88 } 89 90 public PushbackPositionReader(Reader reader, int pushback) { 91 super(reader); 92 93 pushback += 2; 95 96 mMaxPushback = pushback; 97 mCharacters = new int[pushback]; 98 mPositions = new int[pushback]; 99 mCursor = 0; 100 mPushback = 0; 101 } 102 103 106 public int getStartPosition() { 107 int back = mCursor - 2; 108 if (back < 0) back += mMaxPushback; 109 110 return mPositions[back]; 111 } 112 113 public int read() throws IOException { 114 int c; 115 116 if (mPushback > 0) { 117 mPushback--; 118 119 mPosition = mPositions[mCursor]; 120 c = mCharacters[mCursor++]; 121 if (mCursor >= mMaxPushback) mCursor = 0; 122 123 return c; 124 } 125 126 c = super.read(); 127 128 mPositions[mCursor] = mPosition; 129 mCharacters[mCursor++] = c; 130 if (mCursor >= mMaxPushback) mCursor = 0; 131 132 return c; 133 } 134 135 public int peek() throws IOException { 136 int c = read(); 137 unread(); 138 return c; 139 } 140 141 150 public void unread(int amount) throws IOException { 151 for (int i=0; i<amount; i++) { 152 unread(); 153 } 154 } 155 156 164 public void unread() throws IOException { 165 mPushback++; 166 167 if (mPushback > mMaxPushback - 2) { 168 throw new IOException(this.getClass().getName() + 169 ": pushback exceeded " + (mMaxPushback - 2)); 170 } 171 172 if ((--mCursor) < 0) mCursor += mMaxPushback; 173 174 if (mCursor > 0) { 175 mPosition = mPositions[mCursor - 1]; 176 } 177 else { 178 mPosition = mPositions[mMaxPushback - 1]; 179 } 180 181 unreadHook(mCharacters[mCursor]); 182 } 183 184 188 protected void unreadHook(int c) { 189 } 190 } 191 | Popular Tags |