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