1 /*
2 * Copyright (c) 2021 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 #include "ecmascript/regexp/regexp_parser_cache.h"
17
18 namespace panda::ecmascript {
RegExpParserCache()19 RegExpParserCache::RegExpParserCache()
20 {
21 Clear();
22 }
23
~RegExpParserCache()24 RegExpParserCache::~RegExpParserCache()
25 {
26 Clear();
27 }
28
Clear()29 void RegExpParserCache::Clear()
30 {
31 for (ParserKey &info : info_) {
32 info.pattern_ = nullptr;
33 info.flags_ = UINT32_MAX; // flags cannot be UINT32_MAX, so it means invalid.
34 info.codeBuffer_ = JSTaggedValue::Hole();
35 info.bufferSize_ = 0;
36 }
37 }
38
GetHash(const JSThread * thread,EcmaString * pattern,const uint32_t flags)39 size_t RegExpParserCache::GetHash(const JSThread *thread, EcmaString *pattern, const uint32_t flags)
40 {
41 auto hashcode = EcmaStringAccessor(pattern).GetHashcode(thread);
42 return (hashcode ^ flags) % CACHE_SIZE;
43 }
44
GetCache(const JSThread * thread,EcmaString * pattern,const uint32_t flags,CVector<CString> & groupName)45 std::pair<JSTaggedValue, size_t> RegExpParserCache::GetCache(const JSThread *thread,
46 EcmaString *pattern, const uint32_t flags,
47 CVector<CString> &groupName)
48 {
49 size_t hash = GetHash(thread, pattern, flags);
50 ParserKey &info = info_[hash];
51 if (info.flags_ != flags || info.pattern_ == nullptr ||
52 !EcmaStringAccessor::StringsAreEqual(thread, info.pattern_, pattern)) {
53 return std::pair<JSTaggedValue, size_t>(JSTaggedValue::Hole(), 0);
54 }
55 groupName = info.newGroupNames_;
56 return std::pair<JSTaggedValue, size_t>(info.codeBuffer_, info.bufferSize_);
57 }
58
SetCache(const JSThread * thread,EcmaString * pattern,const uint32_t flags,const JSTaggedValue codeBuffer,const size_t bufferSize,CVector<CString> groupName)59 void RegExpParserCache::SetCache(const JSThread *thread,
60 EcmaString *pattern, const uint32_t flags,
61 const JSTaggedValue codeBuffer, const size_t bufferSize,
62 CVector<CString> groupName)
63 {
64 size_t hash = GetHash(thread, pattern, flags);
65 ParserKey &info = info_[hash];
66 info.pattern_ = pattern;
67 info.flags_ = flags;
68 info.codeBuffer_ = codeBuffer;
69 info.bufferSize_ = bufferSize;
70 info.newGroupNames_ = groupName;
71 }
72 } // namespace panda::ecmascript