1/**
2 * Copyright (c) 2021-2022 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
16export default class BitSet {
17
18  private static readonly NUMBER_BITS_NUM = 64;
19
20  private readonly mBitArray: number[] = null;
21
22  private readonly mSize: number;
23
24  /**
25   * constructor
26   *
27   * @param {number} size, size of BitSet
28   */
29  constructor(size: number) {
30    this.mSize = size;
31    const allocSize = Math.ceil(size / BitSet.NUMBER_BITS_NUM);
32    this.mBitArray = new Array<number>(allocSize);
33    for (let i = 0; i < this.mBitArray.length; i++) {
34      this.mBitArray[i] = 0;
35    }
36  }
37
38  /**
39   * get the bit value of index
40   *
41   * @param {number} index, index of BitSet
42   * @return {boolean} true if set
43   */
44  get(index: number): boolean {
45    if (index < 0 || index >= this.mSize) {
46      return false;
47    }
48
49    const arrayIndex = Math.floor(index / BitSet.NUMBER_BITS_NUM);
50    const bitIndex = index % BitSet.NUMBER_BITS_NUM;
51    return (this.mBitArray[arrayIndex] & (1 << bitIndex)) != 0;
52  }
53
54  /**
55   * set the bit value of index as true
56   *
57   * @param {number} index, index of BitSet
58   */
59  set(index: number) {
60    if (index < 0 || index >= this.mSize) {
61      return;
62    }
63
64    const arrayIndex = Math.floor(index / BitSet.NUMBER_BITS_NUM);
65    const bitIndex = index % BitSet.NUMBER_BITS_NUM;
66    this.mBitArray[arrayIndex] |= 1 << bitIndex;
67  }
68
69  /**
70   * call all the bit value of the BitSet
71   *
72   */
73  clear() {
74    this.mBitArray.fill(0);
75  }
76}