• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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  */
28 template<bool readOnly>
29 class ScopedBytes {
30 public:
ScopedBytes(JNIEnv * env,jobject object)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 
~ScopedBytes()44     ~ScopedBytes() {
45         if (mByteArray != NULL) {
46             mEnv->ReleaseByteArrayElements(mByteArray, mPtr, readOnly ? JNI_ABORT : 0);
47         }
48     }
49 
50 private:
51     JNIEnv* mEnv;
52     jobject mObject;
53     jbyteArray mByteArray;
54 
55 protected:
56     jbyte* mPtr;
57 
58 private:
59     // Disallow copy and assignment.
60     ScopedBytes(const ScopedBytes&);
61     void operator=(const ScopedBytes&);
62 };
63 
64 class ScopedBytesRO : public ScopedBytes<true> {
65 public:
ScopedBytesRO(JNIEnv * env,jobject object)66     ScopedBytesRO(JNIEnv* env, jobject object) : ScopedBytes<true>(env, object) {}
get()67     const jbyte* get() const {
68         return mPtr;
69     }
70 };
71 
72 class ScopedBytesRW : public ScopedBytes<false> {
73 public:
ScopedBytesRW(JNIEnv * env,jobject object)74     ScopedBytesRW(JNIEnv* env, jobject object) : ScopedBytes<false>(env, object) {}
get()75     jbyte* get() {
76         return mPtr;
77     }
78 };
79 
80 #endif  // SCOPED_BYTES_H_included
81