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