michael@0: /* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; 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.nio.ByteBuffer; michael@0: michael@0: // michael@0: // We must manually allocate direct buffers in JNI to work around a bug where Honeycomb's michael@0: // ByteBuffer.allocateDirect() grossly overallocates the direct buffer size. michael@0: // https://code.google.com/p/android/issues/detail?id=16941 michael@0: // michael@0: michael@0: public final class DirectBufferAllocator { michael@0: private DirectBufferAllocator() {} michael@0: michael@0: public static ByteBuffer allocate(int size) { michael@0: if (size <= 0) { michael@0: throw new IllegalArgumentException("Invalid size " + size); michael@0: } michael@0: michael@0: ByteBuffer directBuffer = nativeAllocateDirectBuffer(size); michael@0: if (directBuffer == null) { michael@0: throw new OutOfMemoryError("allocateDirectBuffer() returned null"); michael@0: } else if (!directBuffer.isDirect()) { michael@0: throw new AssertionError("allocateDirectBuffer() did not return a direct buffer"); michael@0: } michael@0: michael@0: return directBuffer; michael@0: } michael@0: michael@0: public static ByteBuffer free(ByteBuffer buffer) { michael@0: if (buffer == null) { michael@0: return null; michael@0: } michael@0: michael@0: if (!buffer.isDirect()) { michael@0: throw new IllegalArgumentException("buffer must be direct"); michael@0: } michael@0: michael@0: nativeFreeDirectBuffer(buffer); michael@0: return null; michael@0: } michael@0: michael@0: // These JNI methods are implemented in mozglue/android/nsGeckoUtils.cpp. michael@0: private static native ByteBuffer nativeAllocateDirectBuffer(long size); michael@0: private static native void nativeFreeDirectBuffer(ByteBuffer buf); michael@0: }