1 /* 2 * Copyright (c) 2021-2023 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 ECMASCRIPT_DFX_HPROF_STRING_HASHMAP_H 17 #define ECMASCRIPT_DFX_HPROF_STRING_HASHMAP_H 18 19 #include "ecmascript/ecma_vm.h" 20 #include "ecmascript/mem/c_containers.h" 21 #include "ecmascript/mem/c_string.h" 22 23 namespace panda::ecmascript { 24 using StringKey = uint64_t; 25 using StringId = uint64_t; 26 27 // An Implementation for Native StringTable without Auto Mem-Management 28 // To make sure when using String, it still stays where it was. 29 class StringHashMap { 30 public: StringHashMap(const EcmaVM * vm)31 explicit StringHashMap(const EcmaVM *vm) : vm_(vm) 32 { 33 ASSERT(vm_ != nullptr); 34 } ~StringHashMap()35 ~StringHashMap() 36 { 37 Clear(); 38 } 39 NO_MOVE_SEMANTIC(StringHashMap); 40 NO_COPY_SEMANTIC(StringHashMap); 41 /* 42 * The ID is the seat number in JSON file Range from 0~string_table_.size() 43 */ 44 StringId GetStringId(const CString *cstr) const; 45 /* 46 * Get all keys sorted by insert order 47 */ GetOrderedKeyStorage()48 const CVector<StringKey> &GetOrderedKeyStorage() const 49 { 50 return orderedKey_; 51 } 52 /* 53 * Get string by its hash key 54 */ 55 CString *GetStringByKey(StringKey key) const; GetCapcity()56 size_t GetCapcity() const 57 { 58 ASSERT(orderedKey_.size() == hashmap_.size()); 59 return orderedKey_.size(); 60 } 61 /* 62 * For external call to use this StringTable 63 */ 64 CString *GetString(const CString &cstr); 65 66 private: 67 StringKey GenerateStringKey(const CString *cstr) const; 68 CString *FindOrInsertString(const CString *cstr); 69 CString *FormatString(CString *cstr) const; 70 /* 71 * Free all memory 72 */ 73 void Clear(); 74 const EcmaVM *vm_; 75 CVector<StringKey> orderedKey_; // Used for Serialize Order 76 size_t index_ {2}; // 2: Offset the String-Table Header 77 CUnorderedMap<StringKey, StringId> indexMap_; 78 CUnorderedMap<StringKey, CString *> hashmap_; 79 }; 80 } // namespace panda::ecmascript 81 #endif // ECMASCRIPT_DFX_HPROF_STRING_HASHMAP_H 82