File: bitset.cpp

package info (click to toggle)
icu 78.2-1
  • links: PTS
  • area: main
  • in suites: experimental
  • size: 123,992 kB
  • sloc: cpp: 527,891; ansic: 112,789; sh: 4,983; makefile: 4,657; perl: 3,199; python: 2,933; xml: 749; sed: 36; lisp: 12
file content (67 lines) | stat: -rw-r--r-- 1,949 bytes parent folder | download | duplicates (9)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
***********************************************************************
* © 2016 and later: Unicode, Inc. and others.
* License & terms of use: http://www.unicode.org/copyright.html
***********************************************************************
***********************************************************************
* Copyright (c) 2002-2005, International Business Machines
* Corporation and others.  All Rights Reserved.
***********************************************************************
* 2002-09-20 aliu Created.
*/

#include "unicode/utypes.h"
#include "cmemory.h"
#include "bitset.h"

// TODO: have a separate capacity, so the len can just be set to
// zero in the clearAll() method, and growth can be smarter.

const int32_t SLOP = 8;

const int32_t BYTES_PER_WORD = sizeof(int32_t);

BitSet::BitSet() {
    len = SLOP;
    data = static_cast<int32_t*>(uprv_malloc(len * BYTES_PER_WORD));
    clearAll();
}

BitSet::~BitSet() {
    uprv_free(data);
}

UBool BitSet::get(int32_t bitIndex) const {
    uint32_t longIndex = bitIndex >> 5;
    int32_t bitInLong = bitIndex & 0x1F;
    return (longIndex < len) ? (((data[longIndex] >> bitInLong) & 1) != 0)
        : false;
}

void BitSet::set(int32_t bitIndex) {
    uint32_t longIndex = bitIndex >> 5;
    int32_t bitInLong = bitIndex & 0x1F;
    if (longIndex >= len) {
        ensureCapacity(longIndex+1);
    }
    data[longIndex] |= (1 << bitInLong);
}

void BitSet::clearAll() {
    for (uint32_t i=0; i<len; ++i) data[i] = 0;
}

void BitSet::ensureCapacity(uint32_t minLen) {
    uint32_t newLen = len;
    while (newLen < minLen) newLen <<= 1; // grow exponentially
    int32_t* newData = static_cast<int32_t*>(uprv_malloc(newLen * BYTES_PER_WORD));
    uprv_memcpy(newData, data, len * BYTES_PER_WORD);
    uprv_free(data);
    data = newData;
    int32_t* p = data + len;
    int32_t* limit = data + newLen;
    while (p < limit) *p++ = 0;
    len = newLen;
}

//eof