01: package it.unimi.dsi.mg4j.index;
02:
03: /*
04: * MG4J: Managing Gigabytes for Java
05: *
06: * Copyright (C) 2005-2007 Sebastiano Vigna
07: *
08: * This library is free software; you can redistribute it and/or modify it
09: * under the terms of the GNU Lesser General Public License as published by the Free
10: * Software Foundation; either version 2.1 of the License, or (at your option)
11: * any later version.
12: *
13: * This library is distributed in the hope that it will be useful, but
14: * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15: * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
16: * for more details.
17: *
18: * You should have received a copy of the GNU Lesser General Public License
19: * along with this program; if not, write to the Free Software
20: * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21: *
22: */
23:
24: import it.unimi.dsi.io.OutputBitStream;
25:
26: import java.io.File;
27: import java.io.FileNotFoundException;
28:
29: /** A special output bit stream with an additional
30: * method {@link #buffer()} that returns the internal buffer
31: * if the internal buffer contains all that has been written since
32: * the last call to {@link OutputBitStream#position(long) position(0)}.
33: *
34: * <p>This bit stream is used every time that it is necessary to cache quickly a bit stream.
35: * By sizing the buffer size appropriately, most of the times data written to the stream
36: * will be readable directly from the buffer. Remember to call {@link OutputBitStream#align()}
37: * before retrieving the buffer, or some bits might be still floating in the bit buffer.
38: */
39:
40: public final class CachingOutputBitStream extends OutputBitStream {
41:
42: public CachingOutputBitStream(final File file, final int bufferSize)
43: throws FileNotFoundException {
44: super (file, bufferSize);
45: }
46:
47: public CachingOutputBitStream(final String filename,
48: final int bufferSize) throws FileNotFoundException {
49: super (filename, bufferSize);
50: }
51:
52: /** Return the internal buffer, if it contains all data.
53: *
54: * <p>Note that this method should always be called after an {@link OutputBitStream#align()},
55: * or some bits might be still floating in the bit buffer.
56: *
57: * @return the internal buffer, if it contains the cached content written since the last call to
58: * {@link OutputBitStream#position(long) position(0)}, or <code>null</code>.
59: */
60:
61: public byte[] buffer() {
62: return (fileChannel != null || repositionableStream != null)
63: && position == 0 || wrapping ? buffer : null;
64: }
65: }
|