1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/mobile/android/base/mozglue/ByteBufferInputStream.java Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,64 @@ 1.4 +/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- 1.5 + * This Source Code Form is subject to the terms of the Mozilla Public 1.6 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.7 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.8 + 1.9 +package org.mozilla.gecko.mozglue; 1.10 + 1.11 +import java.io.InputStream; 1.12 +import java.nio.ByteBuffer; 1.13 + 1.14 +class ByteBufferInputStream extends InputStream { 1.15 + 1.16 + protected ByteBuffer mBuf; 1.17 + // Reference to a native object holding the data backing the ByteBuffer. 1.18 + private NativeReference mNativeRef; 1.19 + 1.20 + protected ByteBufferInputStream(ByteBuffer buffer, NativeReference ref) { 1.21 + mBuf = buffer; 1.22 + mNativeRef = ref; 1.23 + } 1.24 + 1.25 + @Override 1.26 + public int available() { 1.27 + return mBuf.remaining(); 1.28 + } 1.29 + 1.30 + @Override 1.31 + public void close() { 1.32 + mBuf = null; 1.33 + mNativeRef.release(); 1.34 + } 1.35 + 1.36 + @Override 1.37 + public int read() { 1.38 + if (!mBuf.hasRemaining() || mNativeRef.isReleased()) { 1.39 + return -1; 1.40 + } 1.41 + 1.42 + return mBuf.get() & 0xff; // Avoid sign extension 1.43 + } 1.44 + 1.45 + @Override 1.46 + public int read(byte[] buffer, int offset, int length) { 1.47 + if (!mBuf.hasRemaining() || mNativeRef.isReleased()) { 1.48 + return -1; 1.49 + } 1.50 + 1.51 + length = Math.min(length, mBuf.remaining()); 1.52 + mBuf.get(buffer, offset, length); 1.53 + return length; 1.54 + } 1.55 + 1.56 + @Override 1.57 + public long skip(long byteCount) { 1.58 + if (byteCount < 0 || mNativeRef.isReleased()) { 1.59 + return 0; 1.60 + } 1.61 + 1.62 + byteCount = Math.min(byteCount, mBuf.remaining()); 1.63 + mBuf.position(mBuf.position() + (int)byteCount); 1.64 + return byteCount; 1.65 + } 1.66 + 1.67 +}