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 #pragma once 18 19 #include <jni.h> 20 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 */ 29 template<bool readOnly> 30 class ScopedBytes { 31 public: ScopedBytes(JNIEnv * env,jobject object)32 ScopedBytes(JNIEnv* env, jobject object) 33 : mEnv(env), mObject(object), mByteArray(nullptr), mPtr(nullptr) 34 { 35 if (mObject == nullptr) { 36 jniThrowNullPointerException(mEnv); 37 } else { 38 jclass byteArrayClass = env->FindClass("[B"); 39 if (mEnv->IsInstanceOf(mObject, byteArrayClass)) { 40 mByteArray = reinterpret_cast<jbyteArray>(mObject); 41 mPtr = mEnv->GetByteArrayElements(mByteArray, nullptr); 42 } else { 43 mPtr = reinterpret_cast<jbyte*>(mEnv->GetDirectBufferAddress(mObject)); 44 } 45 mEnv->DeleteLocalRef(byteArrayClass); 46 } 47 } 48 ~ScopedBytes()49 ~ScopedBytes() { 50 if (mByteArray != nullptr) { 51 mEnv->ReleaseByteArrayElements(mByteArray, mPtr, readOnly ? JNI_ABORT : 0); 52 } 53 } 54 55 private: 56 JNIEnv* const mEnv; 57 const jobject mObject; 58 jbyteArray mByteArray; 59 60 protected: 61 jbyte* mPtr; 62 63 private: 64 DISALLOW_COPY_AND_ASSIGN(ScopedBytes); 65 }; 66 67 class ScopedBytesRO : public ScopedBytes<true> { 68 public: ScopedBytesRO(JNIEnv * env,jobject object)69 ScopedBytesRO(JNIEnv* env, jobject object) : ScopedBytes<true>(env, object) {} get()70 const jbyte* get() const { 71 return mPtr; 72 } 73 }; 74 75 class ScopedBytesRW : public ScopedBytes<false> { 76 public: ScopedBytesRW(JNIEnv * env,jobject object)77 ScopedBytesRW(JNIEnv* env, jobject object) : ScopedBytes<false>(env, object) {} get()78 jbyte* get() { 79 return mPtr; 80 } 81 }; 82 83