|
1 /* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- |
|
2 * This Source Code Form is subject to the terms of the Mozilla Public |
|
3 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
5 |
|
6 package org.mozilla.gecko.mozglue; |
|
7 |
|
8 import java.io.InputStream; |
|
9 import java.nio.ByteBuffer; |
|
10 |
|
11 class ByteBufferInputStream extends InputStream { |
|
12 |
|
13 protected ByteBuffer mBuf; |
|
14 // Reference to a native object holding the data backing the ByteBuffer. |
|
15 private NativeReference mNativeRef; |
|
16 |
|
17 protected ByteBufferInputStream(ByteBuffer buffer, NativeReference ref) { |
|
18 mBuf = buffer; |
|
19 mNativeRef = ref; |
|
20 } |
|
21 |
|
22 @Override |
|
23 public int available() { |
|
24 return mBuf.remaining(); |
|
25 } |
|
26 |
|
27 @Override |
|
28 public void close() { |
|
29 mBuf = null; |
|
30 mNativeRef.release(); |
|
31 } |
|
32 |
|
33 @Override |
|
34 public int read() { |
|
35 if (!mBuf.hasRemaining() || mNativeRef.isReleased()) { |
|
36 return -1; |
|
37 } |
|
38 |
|
39 return mBuf.get() & 0xff; // Avoid sign extension |
|
40 } |
|
41 |
|
42 @Override |
|
43 public int read(byte[] buffer, int offset, int length) { |
|
44 if (!mBuf.hasRemaining() || mNativeRef.isReleased()) { |
|
45 return -1; |
|
46 } |
|
47 |
|
48 length = Math.min(length, mBuf.remaining()); |
|
49 mBuf.get(buffer, offset, length); |
|
50 return length; |
|
51 } |
|
52 |
|
53 @Override |
|
54 public long skip(long byteCount) { |
|
55 if (byteCount < 0 || mNativeRef.isReleased()) { |
|
56 return 0; |
|
57 } |
|
58 |
|
59 byteCount = Math.min(byteCount, mBuf.remaining()); |
|
60 mBuf.position(mBuf.position() + (int)byteCount); |
|
61 return byteCount; |
|
62 } |
|
63 |
|
64 } |