1/* 2 * Copyright (c) 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 16import type {INameGenerator, NameGeneratorOptions} from './INameGenerator'; 17 18/** 19 * @Desc: a name generator which use given identifiers to get incremental obfuscated name 20 */ 21export class DictionaryNameGenerator implements INameGenerator { 22 private readonly mDictionaryList: string[]; 23 private readonly mReservedNames: Set<string>; 24 25 private mDictIndex: number; 26 private mTransformNumber: number; 27 28 /** 29 * 30 * @param options: {dictionaryList: list} 31 */ 32 constructor(options?: NameGeneratorOptions) { 33 this.mDictionaryList = (options && options.dictionaryList) ? options.dictionaryList : ['hello', 'world', 'dictionary', 'light', 'thunder', 'storm']; 34 this.mReservedNames = options?.reservedNames; 35 36 this.mDictIndex = 0; 37 this.mTransformNumber = 0; 38 } 39 40 /** 41 * @return: null for end 42 */ 43 public getName(): string { 44 if (this.mDictIndex >= this.mDictionaryList.length) { 45 return null; 46 } 47 48 let originIdentifier: string[] = Array.from(this.mDictionaryList[this.mDictIndex].toLowerCase()); 49 const BINARY_RADIX: number = 2; 50 let binary: string = this.mTransformNumber.toString(BINARY_RADIX).split('').reverse().join(''); 51 let countTrue: number = 0; 52 for (let i = 0; i < binary.length; i++) { 53 if (binary[i] === '1') { 54 originIdentifier[i] = originIdentifier[i].toUpperCase(); 55 countTrue += 1; 56 } 57 } 58 59 this.mTransformNumber += 1; 60 if (countTrue >= originIdentifier.length) { 61 this.mDictIndex += 1; 62 this.mTransformNumber = 0; 63 } 64 65 if (this.mReservedNames?.has(originIdentifier.join(''))) { 66 return this.getName(); 67 } 68 69 return originIdentifier.join(''); 70 } 71 72 public reset(): void { 73 this.mDictIndex = 0; 74 this.mTransformNumber = 0; 75 } 76} 77