1 /* 2 * Copyright (C) 2021 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 <nativehelper/ScopedLocalRef.h> 20 #include "ScopedBytes.h" 21 22 /** 23 * ScopedByteBufferArray manages the dynamic buffer array of ScopedBytesRW/ScopedBytesRO. 24 */ 25 class ScopedByteBufferArray { 26 public: ScopedByteBufferArray(JNIEnv * env,int isRW)27 ScopedByteBufferArray(JNIEnv* env, int isRW) 28 : mEnv(env), mIsRW(isRW) 29 { 30 mArrayPtr = NULL; 31 mArraySize = 0; 32 } 33 ~ScopedByteBufferArray()34 ~ScopedByteBufferArray() { 35 if(!mArrayPtr) { 36 return; 37 } 38 39 // Loop over arrary and release memory. 40 for (int i = 0; i < mArraySize; ++i) { 41 if (!mArrayPtr[i]) 42 continue; 43 44 if (mIsRW) { 45 jobject tmp = ((ScopedBytesRW*)mArrayPtr[i])->getObject(); 46 delete (ScopedBytesRW*)mArrayPtr[i]; 47 mEnv->DeleteLocalRef(tmp); 48 } else { 49 jobject tmp = ((ScopedBytesRO*)mArrayPtr[i])->getObject(); 50 delete (ScopedBytesRO*)mArrayPtr[i]; 51 mEnv->DeleteLocalRef(tmp); 52 } 53 } 54 delete[] mArrayPtr; 55 } 56 initArray(int size)57 bool initArray(int size) { 58 if (mArrayPtr) { 59 return false; 60 } 61 62 mArraySize = size; 63 64 if (mIsRW) { 65 mArrayPtr = (void**)(new ScopedBytesRW*[size]); 66 } 67 else { 68 mArrayPtr = (void**)(new ScopedBytesRO*[size]); 69 } 70 71 if (!mArrayPtr) { 72 return false; 73 } 74 75 for (int i=0; i<size; ++i) { 76 mArrayPtr[i] = 0; 77 } 78 79 return true; 80 } 81 isRW()82 bool isRW() const { 83 return mIsRW; 84 } 85 setArrayItem(int itemNo,void * item)86 bool setArrayItem(int itemNo, void* item) { 87 if (itemNo >= mArraySize || itemNo < 0) { 88 return false; 89 } 90 mArrayPtr[itemNo] = item; 91 return true; 92 } 93 94 private: 95 JNIEnv* const mEnv; 96 int mIsRW; 97 int mArraySize; 98 void** mArrayPtr; 99 }; 100