File: ByteBufferRandomAccessFile.java

package info (click to toggle)
libsis-base-java 18.09~pre1%2Bgit20180928.45fbd31%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye
  • size: 1,292 kB
  • sloc: java: 9,037; ansic: 813; xml: 160; sh: 139; makefile: 37
file content (455 lines) | stat: -rw-r--r-- 10,682 bytes parent folder | download | duplicates (3)
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
/*
 * Copyright 2007 - 2018 ETH Zuerich, CISD and SIS.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ch.systemsx.cisd.base.io;

import java.io.EOFException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import ch.systemsx.cisd.base.convert.NativeData;
import ch.systemsx.cisd.base.exceptions.CheckedExceptionTunnel;
import ch.systemsx.cisd.base.exceptions.IOExceptionUnchecked;

/**
 * An implementation of {@link IRandomAccessFile} based on a {@link ByteBuffer}.
 * <p>
 * Does <i>not</i> implement {@link IRandomAccessFile#readLine()}.
 * 
 * @author Bernd Rinn
 */
public class ByteBufferRandomAccessFile implements IRandomAccessFile
{

    private final ByteBuffer buf;

    private void addToLength(int newItemLen)
    {
        final int rem = buf.remaining();
        if (newItemLen > rem)
        {
            buf.limit(buf.limit() + (newItemLen - rem));
        }
    }

    /**
     * Creates a {@link IRandomAccessFile} wrapper for the given <var>buf</var>.
     * 
     * @param buf The buffer to wrap.
     * @param initialLength The initially set length (corresponds to the {@link ByteBuffer#limit()}
     *            ).
     */
    public ByteBufferRandomAccessFile(ByteBuffer buf, int initialLength)
    {
        this(buf);
        setLength(initialLength);
    }

    /**
     * Creates a {@link IRandomAccessFile} wrapper for the given <var>buf</var>. Does not change the
     * {@link ByteBuffer#limit()} of <var>buf</var>.
     * 
     * @param buf The buffer to wrap.
     */
    public ByteBufferRandomAccessFile(ByteBuffer buf)
    {
        this.buf = buf;
    }

    /**
     * Creates a {@link IRandomAccessFile} wrapper for the given <var>array</var>.
     * 
     * @param array The byte array to wrap.
     * @param initialLength The initially set length.
     */
    public ByteBufferRandomAccessFile(byte[] array, int initialLength)
    {
        this(array);
        setLength(initialLength);
    }

    /**
     * Creates a {@link IRandomAccessFile} wrapper for the given <var>array</var>. The initial
     * {@link ByteBuffer#limit()} will be <code>array.length</code>.
     * 
     * @param array The byte array to wrap.
     */
    public ByteBufferRandomAccessFile(byte[] array)
    {
        this(ByteBuffer.wrap(array));
    }

    /**
     * Creates a {@link IRandomAccessFile} wrapper for a {@link ByteBuffer} with
     * <var>capacity</var>. The initial {@link ByteBuffer#limit()} will be <code>0</code>.
     * 
     * @param capacity The maximal size of the {@link ByteBuffer}.
     */
    public ByteBufferRandomAccessFile(int capacity)
    {
        this(ByteBuffer.allocate(capacity));
        setLength(0);
    }

    @Override
    public ByteOrder getByteOrder()
    {
        return buf.order();
    }

    @Override
    public void setByteOrder(ByteOrder byteOrder)
    {
        buf.order(byteOrder);
    }

    @Override
    public void readFully(byte[] b) throws IOExceptionUnchecked
    {
        readFully(b, 0, b.length);
    }

    @Override
    public void readFully(byte[] b, int off, int len) throws IOExceptionUnchecked
    {
        if (available0() == -1)
        {
            throw new IOExceptionUnchecked(new EOFException());
        } else
        {
            buf.get(b, off, len);
        }
    }

    @Override
    public int skipBytes(int n) throws IOExceptionUnchecked
    {
        if (n <= 0)
        {
            return 0;
        }
        final int pos = buf.position();
        final int len = buf.limit();
        final int newpos = Math.min(len, pos + n);
        buf.position(newpos);
        return (newpos - pos);
    }

    @Override
    public void close() throws IOExceptionUnchecked
    {
        // NOOP
    }

    @Override
    public int read() throws IOExceptionUnchecked
    {
        return buf.get() & 0xff;
    }

    @Override
    public int read(byte[] b) throws IOExceptionUnchecked
    {
        return read(b, 0, b.length);
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOExceptionUnchecked
    {
        final int bytesRead = Math.min(available0(), len);
        if (bytesRead < 0)
        {
            return bytesRead;
        }
        buf.get(b, off, bytesRead);
        return bytesRead;
    }

    @Override
    public long skip(long n) throws IOExceptionUnchecked
    {
        if (n > Integer.MAX_VALUE)
        {
            throw new IndexOutOfBoundsException();
        }
        return skipBytes((int) n);
    }
    
    private int available0() throws IOExceptionUnchecked
    {
        return (buf.remaining() == 0) ? -1 : buf.remaining();
    }

    @Override
    public int available() throws IOExceptionUnchecked
    {
        return buf.remaining();
    }

    @Override
    public void mark(int readlimit)
    {
        buf.mark();
    }

    @Override
    public void reset() throws IOExceptionUnchecked
    {
        buf.reset();
    }

    @Override
    public boolean markSupported()
    {
        return true;
    }

    @Override
    public void flush() throws IOExceptionUnchecked
    {
        // NOOP
    }

    @Override
    public void synchronize() throws IOExceptionUnchecked
    {
        // NOOP
    }

    @Override
    public long getFilePointer() throws IOExceptionUnchecked
    {
        return buf.position();
    }

    @Override
    public void seek(long pos) throws IOExceptionUnchecked
    {
        buf.position((int) pos);
    }

    @Override
    public long length() throws IOExceptionUnchecked
    {
        return buf.limit();
    }

    @Override
    public void setLength(long newLength) throws IOExceptionUnchecked
    {
        buf.limit((int) newLength);
    }

    @Override
    public boolean readBoolean() throws IOExceptionUnchecked
    {
        return buf.get() != 0;
    }

    @Override
    public byte readByte() throws IOExceptionUnchecked
    {
        return buf.get();
    }

    @Override
    public int readUnsignedByte() throws IOExceptionUnchecked
    {
        return buf.get() & 0xff;
    }

    @Override
    public short readShort() throws IOExceptionUnchecked
    {
        return buf.getShort();
    }

    @Override
    public int readUnsignedShort() throws IOExceptionUnchecked
    {
        return buf.getShort() & 0xffff;
    }

    @Override
    public char readChar() throws IOExceptionUnchecked
    {
        return buf.getChar();
    }

    @Override
    public int readInt() throws IOExceptionUnchecked
    {
        return buf.getInt();
    }

    @Override
    public long readLong() throws IOExceptionUnchecked
    {
        return buf.getLong();
    }

    @Override
    public float readFloat() throws IOExceptionUnchecked
    {
        return buf.getFloat();
    }

    @Override
    public double readDouble() throws IOExceptionUnchecked
    {
        return buf.getDouble();
    }

    /**
     * @throws UnsupportedOperationException
     */
    @Override
    public String readLine() throws UnsupportedOperationException
    {
        throw new UnsupportedOperationException();
    }

    @Override
    public String readUTF()
    {
        try
        {
            final byte[] strBuf = new byte[readUnsignedShort()];
            buf.get(strBuf);
            return new String(strBuf, "UTF-8");
        } catch (UnsupportedEncodingException ex)
        {
            throw CheckedExceptionTunnel.wrapIfNecessary(ex);
        }
    }

    @Override
    public void write(int b) throws IOExceptionUnchecked
    {
        addToLength(1);
        buf.put((byte) b);
    }

    @Override
    public void write(byte[] b) throws IOExceptionUnchecked
    {
        addToLength(b.length);
        buf.put(b);
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOExceptionUnchecked
    {
        addToLength(len);
        buf.put(b, off, len);
    }

    @Override
    public void writeBoolean(boolean v) throws IOExceptionUnchecked
    {
        addToLength(1);
        buf.put((byte) (v ? 1 : 0));
    }

    @Override
    public void writeByte(int v) throws IOExceptionUnchecked
    {
        write((byte) v);
    }

    @Override
    public void writeShort(int v) throws IOExceptionUnchecked
    {
        addToLength(NativeData.SHORT_SIZE);
        buf.putShort((short) v);
    }

    @Override
    public void writeChar(int v) throws IOExceptionUnchecked
    {
        addToLength(NativeData.CHAR_SIZE);
        buf.putChar((char) v);
    }

    @Override
    public void writeInt(int v) throws IOExceptionUnchecked
    {
        addToLength(NativeData.INT_SIZE);
        buf.putInt(v);
    }

    @Override
    public void writeLong(long v) throws IOExceptionUnchecked
    {
        addToLength(NativeData.LONG_SIZE);
        buf.putLong(v);
    }

    @Override
    public void writeFloat(float v) throws IOExceptionUnchecked
    {
        addToLength(NativeData.FLOAT_SIZE);
        buf.putFloat(v);
    }

    @Override
    public void writeDouble(double v) throws IOExceptionUnchecked
    {
        addToLength(NativeData.DOUBLE_SIZE);
        buf.putDouble(v);
    }

    @Override
    public void writeBytes(String s) throws IOExceptionUnchecked
    {
        final int len = s.length();
        addToLength(len);
        for (int i = 0; i < len; i++)
        {
            buf.put((byte) s.charAt(i));
        }
    }

    @Override
    public void writeChars(String s) throws IOExceptionUnchecked
    {
        final int len = s.length();
        addToLength(NativeData.CHAR_SIZE * len);
        for (int i = 0; i < len; i++)
        {
            final int v = s.charAt(i);
            buf.put((byte) ((v >>> 8) & 0xFF));
            buf.put((byte) ((v >>> 0) & 0xFF));
        }
    }

    @Override
    public void writeUTF(String str) throws UnsupportedOperationException
    {
        try
        {
            final byte[] strBuf = str.getBytes("UTF-8");
            addToLength(NativeData.SHORT_SIZE + strBuf.length);
            writeShort(strBuf.length);
            write(strBuf);
        } catch (UnsupportedEncodingException ex)
        {
            throw CheckedExceptionTunnel.wrapIfNecessary(ex);
        }
    }

}