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
michael@0 | 1 | /* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*- |
michael@0 | 2 | * This Source Code Form is subject to the terms of the Mozilla Public |
michael@0 | 3 | * License, v. 2.0. If a copy of the MPL was not distributed with this |
michael@0 | 4 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
michael@0 | 5 | |
michael@0 | 6 | package org.mozilla.gecko.mozglue; |
michael@0 | 7 | |
michael@0 | 8 | import java.nio.ByteBuffer; |
michael@0 | 9 | |
michael@0 | 10 | // |
michael@0 | 11 | // We must manually allocate direct buffers in JNI to work around a bug where Honeycomb's |
michael@0 | 12 | // ByteBuffer.allocateDirect() grossly overallocates the direct buffer size. |
michael@0 | 13 | // https://code.google.com/p/android/issues/detail?id=16941 |
michael@0 | 14 | // |
michael@0 | 15 | |
michael@0 | 16 | public final class DirectBufferAllocator { |
michael@0 | 17 | private DirectBufferAllocator() {} |
michael@0 | 18 | |
michael@0 | 19 | public static ByteBuffer allocate(int size) { |
michael@0 | 20 | if (size <= 0) { |
michael@0 | 21 | throw new IllegalArgumentException("Invalid size " + size); |
michael@0 | 22 | } |
michael@0 | 23 | |
michael@0 | 24 | ByteBuffer directBuffer = nativeAllocateDirectBuffer(size); |
michael@0 | 25 | if (directBuffer == null) { |
michael@0 | 26 | throw new OutOfMemoryError("allocateDirectBuffer() returned null"); |
michael@0 | 27 | } else if (!directBuffer.isDirect()) { |
michael@0 | 28 | throw new AssertionError("allocateDirectBuffer() did not return a direct buffer"); |
michael@0 | 29 | } |
michael@0 | 30 | |
michael@0 | 31 | return directBuffer; |
michael@0 | 32 | } |
michael@0 | 33 | |
michael@0 | 34 | public static ByteBuffer free(ByteBuffer buffer) { |
michael@0 | 35 | if (buffer == null) { |
michael@0 | 36 | return null; |
michael@0 | 37 | } |
michael@0 | 38 | |
michael@0 | 39 | if (!buffer.isDirect()) { |
michael@0 | 40 | throw new IllegalArgumentException("buffer must be direct"); |
michael@0 | 41 | } |
michael@0 | 42 | |
michael@0 | 43 | nativeFreeDirectBuffer(buffer); |
michael@0 | 44 | return null; |
michael@0 | 45 | } |
michael@0 | 46 | |
michael@0 | 47 | // These JNI methods are implemented in mozglue/android/nsGeckoUtils.cpp. |
michael@0 | 48 | private static native ByteBuffer nativeAllocateDirectBuffer(long size); |
michael@0 | 49 | private static native void nativeFreeDirectBuffer(ByteBuffer buf); |
michael@0 | 50 | } |