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(EcmaString * pattern,const uint32_t flags)39 size_t RegExpParserCache::GetHash(EcmaString *pattern, const uint32_t flags)
40 {
41 auto hashcode = EcmaStringAccessor(pattern).GetHashcode();
42 return (hashcode ^ flags) % CACHE_SIZE;
43 }
44
GetCache(EcmaString * pattern,const uint32_t flags,CVector<CString> & groupName)45 std::pair<JSTaggedValue, size_t> RegExpParserCache::GetCache(EcmaString *pattern, const uint32_t flags,
46 CVector<CString> &groupName)
47 {
48 size_t hash = GetHash(pattern, flags);
49 ParserKey &info = info_[hash];
50 if (info.flags_ != flags || info.pattern_ == nullptr ||
51 !EcmaStringAccessor::StringsAreEqual(info.pattern_, pattern)) {
52 return std::pair<JSTaggedValue, size_t>(JSTaggedValue::Hole(), 0);
53 }
54 groupName = info.newGroupNames_;
55 return std::pair<JSTaggedValue, size_t>(info.codeBuffer_, info.bufferSize_);
56 }
57
SetCache(EcmaString * pattern,const uint32_t flags,const JSTaggedValue codeBuffer,const size_t bufferSize,CVector<CString> groupName)58 void RegExpParserCache::SetCache(EcmaString *pattern, const uint32_t flags,
59 const JSTaggedValue codeBuffer, const size_t bufferSize,
60 CVector<CString> groupName)
61 {
62 size_t hash = GetHash(pattern, flags);
63 ParserKey &info = info_[hash];
64 info.pattern_ = pattern;
65 info.flags_ = flags;
66 info.codeBuffer_ = codeBuffer;
67 info.bufferSize_ = bufferSize;
68 info.newGroupNames_ = groupName;
69 }
70 } // namespace panda::ecmascript