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 || !EcmaStringAccessor::StringsAreEqual(info.pattern_, pattern)) {
51 return std::pair<JSTaggedValue, size_t>(JSTaggedValue::Hole(), 0);
52 }
53 groupName = info.newGroupNames_;
54 return std::pair<JSTaggedValue, size_t>(info.codeBuffer_, info.bufferSize_);
55 }
56
SetCache(EcmaString * pattern,const uint32_t flags,const JSTaggedValue codeBuffer,const size_t bufferSize,CVector<CString> groupName)57 void RegExpParserCache::SetCache(EcmaString *pattern, const uint32_t flags,
58 const JSTaggedValue codeBuffer, const size_t bufferSize,
59 CVector<CString> groupName)
60 {
61 size_t hash = GetHash(pattern, flags);
62 ParserKey &info = info_[hash];
63 info.pattern_ = pattern;
64 info.flags_ = flags;
65 info.codeBuffer_ = codeBuffer;
66 info.bufferSize_ = bufferSize;
67 info.newGroupNames_ = groupName;
68 }
69 } // namespace panda::ecmascript