blob: c2b09c1d15d76b6ec147f1f3d5c9dc096f57d4e9 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "android_nio_utils.h"
18
Derek Sollenbergerc5882c42019-10-25 11:11:32 -040019#include <nativehelper/JNIHelp.h>
Andreas Gampe987f79f2014-11-18 17:29:46 -080020
Orion Hodsonb0461eb2019-04-15 22:13:59 +010021namespace android {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022
Orion Hodsonb0461eb2019-04-15 22:13:59 +010023AutoBufferPointer::AutoBufferPointer(JNIEnv* env, jobject nioBuffer, jboolean commit)
24 : fEnv(env), fCommit(commit) {
25 jlong pointer = jniGetNioBufferPointer(fEnv, nioBuffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026 if (pointer != 0L) {
Orion Hodsonb0461eb2019-04-15 22:13:59 +010027 // Buffer is backed by a direct buffer.
28 fArray = nullptr;
29 fElements = nullptr;
30 fPointer = reinterpret_cast<void*>(pointer);
31 } else {
32 // Buffer is backed by a managed array.
33 jint byteOffset = jniGetNioBufferBaseArrayOffset(fEnv, nioBuffer);
34 fArray = jniGetNioBufferBaseArray(fEnv, nioBuffer);
35 fElements = fEnv->GetPrimitiveArrayCritical(fArray, /* isCopy= */ nullptr);
36 fPointer = reinterpret_cast<void*>(reinterpret_cast<char*>(fElements) + byteOffset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038}
39
Orion Hodsonb0461eb2019-04-15 22:13:59 +010040AutoBufferPointer::~AutoBufferPointer() {
Orion Hodsone522c992019-04-15 16:14:51 +010041 if (nullptr != fArray) {
Orion Hodsonb0461eb2019-04-15 22:13:59 +010042 fEnv->ReleasePrimitiveArrayCritical(fArray, fElements, fCommit ? 0 : JNI_ABORT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043 }
44}
Orion Hodsonb0461eb2019-04-15 22:13:59 +010045
46} // namespace android