blob: abeb3952ca30325be19f05b0e193c0f7f4872211 [file] [log] [blame]
Andreas Gamped299c072017-10-17 10:50:00 -07001/*
2 * Copyright (C) 2010 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#ifndef SCOPED_BYTES_H_
18#define SCOPED_BYTES_H_
19
20#include "jni.h"
21#include "nativehelper_utils.h"
22
23/**
24 * ScopedBytesRO and ScopedBytesRW attempt to paper over the differences between byte[]s and
25 * ByteBuffers. This in turn helps paper over the differences between non-direct ByteBuffers backed
26 * by byte[]s, direct ByteBuffers backed by bytes[]s, and direct ByteBuffers not backed by byte[]s.
27 * (On Android, this last group only contains MappedByteBuffers.)
28 */
29template<bool readOnly>
30class ScopedBytes {
31public:
32 ScopedBytes(JNIEnv* env, jobject object)
33 : mEnv(env), mObject(object), mByteArray(NULL), mPtr(NULL)
34 {
35 if (mObject == NULL) {
36 jniThrowNullPointerException(mEnv, NULL);
37 } else if (mEnv->IsInstanceOf(mObject, JniConstants::byteArrayClass)) {
38 mByteArray = reinterpret_cast<jbyteArray>(mObject);
39 mPtr = mEnv->GetByteArrayElements(mByteArray, NULL);
40 } else {
41 mPtr = reinterpret_cast<jbyte*>(mEnv->GetDirectBufferAddress(mObject));
42 }
43 }
44
45 ~ScopedBytes() {
46 if (mByteArray != NULL) {
47 mEnv->ReleaseByteArrayElements(mByteArray, mPtr, readOnly ? JNI_ABORT : 0);
48 }
49 }
50
51private:
52 JNIEnv* const mEnv;
53 const jobject mObject;
54 jbyteArray mByteArray;
55
56protected:
57 jbyte* mPtr;
58
59private:
60 DISALLOW_COPY_AND_ASSIGN(ScopedBytes);
61};
62
63class ScopedBytesRO : public ScopedBytes<true> {
64public:
65 ScopedBytesRO(JNIEnv* env, jobject object) : ScopedBytes<true>(env, object) {}
66 const jbyte* get() const {
67 return mPtr;
68 }
69};
70
71class ScopedBytesRW : public ScopedBytes<false> {
72public:
73 ScopedBytesRW(JNIEnv* env, jobject object) : ScopedBytes<false>(env, object) {}
74 jbyte* get() {
75 return mPtr;
76 }
77};
78
79#endif // SCOPED_BYTES_H_