1 /* 2 * Copyright (c) 2025 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef COMMON_INTERFACES_OBJECTS_READONLY_HANDLE_H 17 #define COMMON_INTERFACES_OBJECTS_READONLY_HANDLE_H 18 19 #include "common_interfaces/objects/base_object.h" 20 21 namespace common { 22 template <typename T> 23 class ReadOnlyHandle { 24 public: ReadOnlyHandle(uintptr_t slot)25 inline explicit ReadOnlyHandle(uintptr_t slot) : address_(slot) 26 { 27 DCHECK_CC(slot != 0); 28 T::Cast(*reinterpret_cast<BaseObject **>(slot)); 29 } ReadOnlyHandle()30 inline ReadOnlyHandle() : address_(reinterpret_cast<uintptr_t>(nullptr)) {} 31 ~ReadOnlyHandle() = default; 32 DEFAULT_NOEXCEPT_MOVE_SEMANTIC_CC(ReadOnlyHandle); 33 DEFAULT_COPY_SEMANTIC_CC(ReadOnlyHandle); 34 GetAddress()35 uintptr_t GetAddress() const 36 { 37 return address_; 38 } 39 40 template <typename S> ReadOnlyHandle(const ReadOnlyHandle<S> & handle)41 explicit ReadOnlyHandle(const ReadOnlyHandle<S> &handle) : address_(handle.GetAddress()) 42 { 43 T::Cast(handle.GetBaseObject()); 44 } 45 46 template <typename S> Cast(const ReadOnlyHandle<S> & handle)47 static ReadOnlyHandle<T> Cast(const ReadOnlyHandle<S> &handle) 48 { 49 T::Cast(handle.GetTaggedValue().GetTaggedObject()); 50 return ReadOnlyHandle<T>(handle.GetAddress()); 51 } 52 GetBaseObject()53 BaseObject* GetBaseObject() const 54 { 55 if (GetAddress() == 0U) { 56 return nullptr; 57 } 58 // temporarily add ReadBarrier for JSHandle 59 return *reinterpret_cast<BaseObject **>(GetAddress()); 60 } 61 62 T *operator*() const 63 { 64 return T::Cast(GetBaseObject()); 65 } 66 67 T *operator->() const 68 { 69 return T::Cast(GetBaseObject()); 70 } 71 72 bool operator==(const ReadOnlyHandle<T> &other) const 73 { 74 return GetBaseObject() == other.GetBaseObject(); 75 } 76 77 bool operator!=(const ReadOnlyHandle<T> &other) const 78 { 79 return GetBaseObject() != other.GetBaseObject(); 80 } 81 IsEmpty()82 bool IsEmpty() const 83 { 84 return GetAddress() == 0U; 85 } 86 87 template <typename R> GetObject()88 R *GetObject() const 89 { 90 return reinterpret_cast<R *>(GetBaseObject()); 91 } 92 private: 93 uintptr_t address_; 94 }; 95 } 96 97 #endif //COMMON_INTERFACES_OBJECTS_READONLY_HANDLE_H 98