Thu, 22 Jan 2015 13:21:57 +0100
Incorporate requested changes from Mozilla in review:
https://bugzilla.mozilla.org/show_bug.cgi?id=1123480#c6
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/. */
6 package org.mozilla.gecko.mozglue;
8 import java.io.InputStream;
9 import java.nio.ByteBuffer;
11 class ByteBufferInputStream extends InputStream {
13 protected ByteBuffer mBuf;
14 // Reference to a native object holding the data backing the ByteBuffer.
15 private NativeReference mNativeRef;
17 protected ByteBufferInputStream(ByteBuffer buffer, NativeReference ref) {
18 mBuf = buffer;
19 mNativeRef = ref;
20 }
22 @Override
23 public int available() {
24 return mBuf.remaining();
25 }
27 @Override
28 public void close() {
29 mBuf = null;
30 mNativeRef.release();
31 }
33 @Override
34 public int read() {
35 if (!mBuf.hasRemaining() || mNativeRef.isReleased()) {
36 return -1;
37 }
39 return mBuf.get() & 0xff; // Avoid sign extension
40 }
42 @Override
43 public int read(byte[] buffer, int offset, int length) {
44 if (!mBuf.hasRemaining() || mNativeRef.isReleased()) {
45 return -1;
46 }
48 length = Math.min(length, mBuf.remaining());
49 mBuf.get(buffer, offset, length);
50 return length;
51 }
53 @Override
54 public long skip(long byteCount) {
55 if (byteCount < 0 || mNativeRef.isReleased()) {
56 return 0;
57 }
59 byteCount = Math.min(byteCount, mBuf.remaining());
60 mBuf.position(mBuf.position() + (int)byteCount);
61 return byteCount;
62 }
64 }