michael@0: /* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- michael@0: * This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: package org.mozilla.gecko.mozglue; michael@0: michael@0: import java.io.InputStream; michael@0: import java.nio.ByteBuffer; michael@0: michael@0: class ByteBufferInputStream extends InputStream { michael@0: michael@0: protected ByteBuffer mBuf; michael@0: // Reference to a native object holding the data backing the ByteBuffer. michael@0: private NativeReference mNativeRef; michael@0: michael@0: protected ByteBufferInputStream(ByteBuffer buffer, NativeReference ref) { michael@0: mBuf = buffer; michael@0: mNativeRef = ref; michael@0: } michael@0: michael@0: @Override michael@0: public int available() { michael@0: return mBuf.remaining(); michael@0: } michael@0: michael@0: @Override michael@0: public void close() { michael@0: mBuf = null; michael@0: mNativeRef.release(); michael@0: } michael@0: michael@0: @Override michael@0: public int read() { michael@0: if (!mBuf.hasRemaining() || mNativeRef.isReleased()) { michael@0: return -1; michael@0: } michael@0: michael@0: return mBuf.get() & 0xff; // Avoid sign extension michael@0: } michael@0: michael@0: @Override michael@0: public int read(byte[] buffer, int offset, int length) { michael@0: if (!mBuf.hasRemaining() || mNativeRef.isReleased()) { michael@0: return -1; michael@0: } michael@0: michael@0: length = Math.min(length, mBuf.remaining()); michael@0: mBuf.get(buffer, offset, length); michael@0: return length; michael@0: } michael@0: michael@0: @Override michael@0: public long skip(long byteCount) { michael@0: if (byteCount < 0 || mNativeRef.isReleased()) { michael@0: return 0; michael@0: } michael@0: michael@0: byteCount = Math.min(byteCount, mBuf.remaining()); michael@0: mBuf.position(mBuf.position() + (int)byteCount); michael@0: return byteCount; michael@0: } michael@0: michael@0: }