summaryrefslogtreecommitdiffstats
path: root/crawl-ref/source/bitary.cc
blob: d822dcd3274898c8cee8aba0be67cb12055cef8e (plain) (blame)
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
68
69
70
71
72
73
74
75
76
/*
 *  File:         bitary.cc
 *  Summary:      Bit array data type.
 *  Created by:   Robert Vollmert
 */

#include "AppHdr.h"

#include "bitary.h"

#include "debug.h"

#define LONGSIZE (sizeof(unsigned long)*8)

bit_array::bit_array(unsigned long s)
    : size(s)
{
    nwords = (int) ((size + LONGSIZE - 1) / LONGSIZE);
    data = new unsigned long[nwords];
    reset();
}

bit_array::~bit_array()
{
    delete[] data;
}

void bit_array::reset()
{
    for (int w = 0; w < nwords; ++w)
        data[w] = 0;
}

bool bit_array::get(unsigned long index) const
{
    ASSERT(index < size);
    int w = index / LONGSIZE;
    int b = index % LONGSIZE;
    return (data[w] & (1UL << b));
}

void bit_array::set(unsigned long index, bool value)
{
    ASSERT(index < size);
    int w = index / LONGSIZE;
    int b = index % LONGSIZE;
    if (value)
        data[w] |= (1UL << b);
    else
        data[w] &= ~(1UL << b);
}

bit_array& bit_array::operator |= (const bit_array& other)
{
    ASSERT(size == other.size);
    for (int w = 0; w < nwords; ++w)
        data[w] |= other.data[w];
    return (*this);
}

bit_array& bit_array::operator &= (const bit_array& other)
{
    ASSERT(size == other.size);
    for (int w = 0; w < nwords; ++w)
        data[w] &= other.data[w];
    return (*this);
}

bit_array bit_array::operator & (const bit_array& other) const
{
    ASSERT(size == other.size);
    bit_array res = bit_array(size);
    for (int w = 0; w < nwords; ++w)
        res.data[w] = data[w] & other.data[w];
    return (res);
}