mobile/android/base/mozglue/DirectBufferAllocator.java

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/mobile/android/base/mozglue/DirectBufferAllocator.java	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,50 @@
     1.4 +/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; 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.nio.ByteBuffer;
    1.12 +
    1.13 +//
    1.14 +// We must manually allocate direct buffers in JNI to work around a bug where Honeycomb's
    1.15 +// ByteBuffer.allocateDirect() grossly overallocates the direct buffer size.
    1.16 +// https://code.google.com/p/android/issues/detail?id=16941
    1.17 +//
    1.18 +
    1.19 +public final class DirectBufferAllocator {
    1.20 +    private DirectBufferAllocator() {}
    1.21 +
    1.22 +    public static ByteBuffer allocate(int size) {
    1.23 +        if (size <= 0) {
    1.24 +            throw new IllegalArgumentException("Invalid size " + size);
    1.25 +        }
    1.26 +
    1.27 +        ByteBuffer directBuffer = nativeAllocateDirectBuffer(size);
    1.28 +        if (directBuffer == null) {
    1.29 +            throw new OutOfMemoryError("allocateDirectBuffer() returned null");
    1.30 +        } else if (!directBuffer.isDirect()) {
    1.31 +            throw new AssertionError("allocateDirectBuffer() did not return a direct buffer");
    1.32 +        }
    1.33 +
    1.34 +        return directBuffer;
    1.35 +    }
    1.36 +
    1.37 +    public static ByteBuffer free(ByteBuffer buffer) {
    1.38 +        if (buffer == null) {
    1.39 +            return null;
    1.40 +        }
    1.41 +
    1.42 +        if (!buffer.isDirect()) {
    1.43 +            throw new IllegalArgumentException("buffer must be direct");
    1.44 +        }
    1.45 +
    1.46 +        nativeFreeDirectBuffer(buffer);
    1.47 +        return null;
    1.48 +    }
    1.49 +
    1.50 +    // These JNI methods are implemented in mozglue/android/nsGeckoUtils.cpp.
    1.51 +    private static native ByteBuffer nativeAllocateDirectBuffer(long size);
    1.52 +    private static native void nativeFreeDirectBuffer(ByteBuffer buf);
    1.53 +}

mercurial