blob: fec46e8065444560148119bc6ebbfae26fd5a72b [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:
Ian Rogers8288dde2014-11-04 11:42:02 -080051 JNIEnv* const mEnv;
52 const jobject mObject;
Brian Carlstrom3d9d2142013-05-10 14:09:30 -070053 jbyteArray mByteArray;
54
55protected:
56 jbyte* mPtr;
57
58private:
Ian Rogers8288dde2014-11-04 11:42:02 -080059 DISALLOW_COPY_AND_ASSIGN(ScopedBytes);
Brian Carlstrom3d9d2142013-05-10 14:09:30 -070060};
61
62class ScopedBytesRO : public ScopedBytes<true> {
63public:
64 ScopedBytesRO(JNIEnv* env, jobject object) : ScopedBytes<true>(env, object) {}
65 const jbyte* get() const {
66 return mPtr;
67 }
68};
69
70class ScopedBytesRW : public ScopedBytes<false> {
71public:
72 ScopedBytesRW(JNIEnv* env, jobject object) : ScopedBytes<false>(env, object) {}
73 jbyte* get() {
74 return mPtr;
75 }
76};
77
78#endif // SCOPED_BYTES_H_included