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