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* const mEnv; 52 const jobject mObject; 53 jbyteArray mByteArray; 54 55 protected: 56 jbyte* mPtr; 57 58 private: 59 DISALLOW_COPY_AND_ASSIGN(ScopedBytes); 60 }; 61 62 class ScopedBytesRO : public ScopedBytes<true> { 63 public: ScopedBytesRO(JNIEnv * env,jobject object)64 ScopedBytesRO(JNIEnv* env, jobject object) : ScopedBytes<true>(env, object) {} get()65 const jbyte* get() const { 66 return mPtr; 67 } 68 }; 69 70 class ScopedBytesRW : public ScopedBytes<false> { 71 public: ScopedBytesRW(JNIEnv * env,jobject object)72 ScopedBytesRW(JNIEnv* env, jobject object) : ScopedBytes<false>(env, object) {} get()73 jbyte* get() { 74 return mPtr; 75 } 76 }; 77 78 #endif // SCOPED_BYTES_H_included 79