File size: 7,393 Bytes
2795186
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
/*
 Copyright  2002-2005 MySQL AB, 2008 Sun Microsystems

 This program is free software; you can redistribute it and/or modify
 it under the terms of version 2 of the GNU General Public License as
 published by the Free Software Foundation.

 There are special exceptions to the terms and conditions of the GPL
 as it is applied to this software. View the full text of the
 exception in file EXCEPTIONS-CONNECTOR-J in the directory of this
 software distribution.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


 */

package com.mysql.jdbc.util;

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

import com.mysql.jdbc.log.Log;

/**
 * A non-blocking buffered input stream. Reads more if it can, won't block to
 * fill the buffer, only blocks to satisfy a request of read(byte[])
 * 
 * @author Mark Matthews
 * 
 * @version $Id: ReadAheadInputStream.java,v 1.1.2.1 2005/05/13 18:58:39
 *          mmatthews Exp $
 */
public class ReadAheadInputStream extends InputStream {

	private final static int DEFAULT_BUFFER_SIZE = 4096;

	private InputStream underlyingStream;

	private byte buf[];

	protected int endOfCurrentData;

	protected int currentPosition;

	protected boolean doDebug = false;
	
	protected Log log;

	private void fill(int readAtLeastTheseManyBytes) throws IOException {
		checkClosed();

		this.currentPosition = 0; /* no mark: throw away the buffer */

		this.endOfCurrentData = currentPosition;

		// Read at least as many bytes as the caller wants, but don't
		// block to fill the whole buffer (like java.io.BufferdInputStream
		// does)

		int bytesToRead = Math.min(this.buf.length - currentPosition,
				readAtLeastTheseManyBytes);

		int bytesAvailable = this.underlyingStream.available();

		if (bytesAvailable > bytesToRead) {

			// Great, there's more available, let's grab those
			// bytes too! (read-ahead)

			bytesToRead = Math.min(this.buf.length - currentPosition,
					bytesAvailable);
		}

		if (this.doDebug) {
			StringBuffer debugBuf = new StringBuffer();
			debugBuf.append("  ReadAheadInputStream.fill(");
			debugBuf.append(readAtLeastTheseManyBytes);
			debugBuf.append("), buffer_size=");
			debugBuf.append(this.buf.length);
			debugBuf.append(", current_position=");
			debugBuf.append(currentPosition);
			debugBuf.append(", need to read ");
			debugBuf.append(Math.min(this.buf.length - currentPosition,
					readAtLeastTheseManyBytes));
			debugBuf.append(" bytes to fill request,");

			if (bytesAvailable > 0) {
				debugBuf.append(" underlying InputStream reports ");
				debugBuf.append(bytesAvailable);

				debugBuf.append(" total bytes available,");
			}

			debugBuf.append(" attempting to read ");
			debugBuf.append(bytesToRead);
			debugBuf.append(" bytes.");

			if (this.log != null) {
				this.log.logTrace(debugBuf.toString());
			} else {
				System.err.println(debugBuf.toString());
			}
		}

		int n = this.underlyingStream.read(this.buf, currentPosition,
				bytesToRead);

		if (n > 0) {
			endOfCurrentData = n + currentPosition;
		}
	}

	private int readFromUnderlyingStreamIfNecessary(byte[] b, int off, int len)
			throws IOException {
		checkClosed();

		int avail = endOfCurrentData - currentPosition;

		if (this.doDebug) {
			StringBuffer debugBuf = new StringBuffer();
			debugBuf.append("ReadAheadInputStream.readIfNecessary(");
			debugBuf.append(b);
			debugBuf.append(",");
			debugBuf.append(off);
			debugBuf.append(",");
			debugBuf.append(len);
			debugBuf.append(")");

			if (avail <= 0) {
				debugBuf
						.append(" not all data available in buffer, must read from stream");

				if (len >= this.buf.length) {
					debugBuf
							.append(", amount requested > buffer, returning direct read() from stream");
				}
			}

			if (this.log != null) {
				this.log.logTrace(debugBuf.toString());
			} else {
				System.err.println(debugBuf.toString());
			}
		}

		if (avail <= 0) {

			if (len >= this.buf.length) {
				return this.underlyingStream.read(b, off, len);
			}

			fill(len);

			avail = endOfCurrentData - currentPosition;

			if (avail <= 0)
				return -1;
		}

		int bytesActuallyRead = (avail < len) ? avail : len;

		System.arraycopy(this.buf, currentPosition, b, off, bytesActuallyRead);

		this.currentPosition += bytesActuallyRead;

		return bytesActuallyRead;
	}

	public synchronized int read(byte b[], int off, int len) throws IOException {
		checkClosed(); // Check for closed stream
		if ((off | len | (off + len) | (b.length - (off + len))) < 0) {
			throw new IndexOutOfBoundsException();
		} else if (len == 0) {
			return 0;
		}

		int totalBytesRead = 0;

		while (true) {
			int bytesReadThisRound = readFromUnderlyingStreamIfNecessary(b, off
					+ totalBytesRead, len - totalBytesRead);

			// end-of-stream?
			if (bytesReadThisRound <= 0) {
				if (totalBytesRead == 0) {
					totalBytesRead = bytesReadThisRound;
				}

				break;
			}

			totalBytesRead += bytesReadThisRound;

			// Read _at_least_ enough bytes
			if (totalBytesRead >= len) {
				break;
			}

			// Nothing to read?
			if (this.underlyingStream.available() <= 0) {
				break;
			}
		}

		return totalBytesRead;
	}

	public int read() throws IOException {
		checkClosed();

		if (currentPosition >= endOfCurrentData) {
			fill(1);
			if (currentPosition >= endOfCurrentData)
				return -1;
		}

		return this.buf[currentPosition++] & 0xff;
	}

	public int available() throws IOException {
		checkClosed();

		return this.underlyingStream.available()
				+ (this.endOfCurrentData - this.currentPosition);
	}

	private void checkClosed() throws IOException {

		if (this.buf == null) {
			throw new IOException("Stream closed");
		}
	}

	/**
	 * 
	 */
	public ReadAheadInputStream(InputStream toBuffer, boolean debug, Log logTo) {
		this(toBuffer, DEFAULT_BUFFER_SIZE, debug, logTo);
	}

	public ReadAheadInputStream(InputStream toBuffer, int bufferSize,
			boolean debug,
			Log logTo) {
		this.underlyingStream = toBuffer;
		this.buf = new byte[bufferSize];
		this.doDebug = debug;
		this.log = logTo;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.io.Closeable#close()
	 */
	public void close() throws IOException {
		if (this.underlyingStream != null) {
			try {
				this.underlyingStream.close();
			} finally {
				this.underlyingStream = null;
				this.buf = null;
				this.log = null;
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.io.InputStream#markSupported()
	 */
	public boolean markSupported() {
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.io.InputStream#skip(long)
	 */
	public long skip(long n) throws IOException {
		checkClosed();
		if (n <= 0) {
			return 0;
		}

		long bytesAvailInBuffer = this.endOfCurrentData - this.currentPosition;

		if (bytesAvailInBuffer <= 0) {

			fill((int) n);
			bytesAvailInBuffer = this.endOfCurrentData - this.currentPosition;
			if (bytesAvailInBuffer <= 0)
				return 0;
		}

		long bytesSkipped = (bytesAvailInBuffer < n) ? bytesAvailInBuffer : n;
		this.currentPosition += bytesSkipped;
		return bytesSkipped;
	}
}