Version 6.4.0.0.beta1, tag libreoffice-6.4.0.0.beta1
[LibreOffice.git] / android / Bootstrap / src / org / libreoffice / kit / DirectBufferAllocator.java
blob99cb3a48620f145b65110c0feb32862d33075b99
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/. */
6 package org.libreoffice.kit;
8 import java.nio.ByteBuffer;
10 /**
11 * This is the common code for allocation and freeing of memory. For this direct ByteBuffer is used but
12 * in the past it was possible to use a JNI version of allocation because of a bug in old Android version.
14 public final class DirectBufferAllocator {
16 private static final String LOGTAG = DirectBufferAllocator.class.getSimpleName();
18 private DirectBufferAllocator() {
21 public static ByteBuffer allocate(int size) {
22 ByteBuffer directBuffer = ByteBuffer.allocateDirect(size);
23 if (directBuffer == null) {
24 if (size <= 0) {
25 throw new IllegalArgumentException("Invalid allocation size: " + size);
26 } else {
27 throw new OutOfMemoryError("allocateDirectBuffer() returned null");
29 } else if (!directBuffer.isDirect()) {
30 throw new AssertionError("allocateDirectBuffer() did not return a direct buffer");
33 return directBuffer;
36 public static ByteBuffer free(ByteBuffer buffer) {
37 if (buffer == null) {
38 return null;
41 if (!buffer.isDirect()) {
42 throw new IllegalArgumentException("ByteBuffer must be direct");
44 // can't free buffer - leave this to the VM
45 return null;
48 public static ByteBuffer guardedAllocate(int size) {
49 ByteBuffer buffer = null;
50 try {
51 buffer = allocate(size);
52 } catch (OutOfMemoryError oomException) {
53 return null;
55 return buffer;