summaryrefslogtreecommitdiffstats
path: root/base/util/src/netscape/security/util/BitArray.java
blob: ab77c226e20ad1bf522dab51f01221a883d1ed41 (plain)
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package netscape.security.util;

import java.io.ByteArrayOutputStream;

/**
 * A packed array of booleans.
 * 
 * @author Joshua Bloch
 * @author Douglas Hoover
 * @version 1.2 97/12/10
 */

public class BitArray {

    private byte[] repn;
    private int length;

    private static final int BITS_PER_UNIT = 8;

    private static int subscript(int idx) {
        return idx / BITS_PER_UNIT;
    }

    private static int position(int idx) { // bits big-endian in each unit
        return 1 << (BITS_PER_UNIT - 1 - (idx % BITS_PER_UNIT));
    }

    /**
     * Creates a BitArray of the specified size, initialized to zeros.
     */
    public BitArray(int length) throws IllegalArgumentException {
        if (length < 0) {
            throw new IllegalArgumentException("Negative length for BitArray");
        }

        this.length = length;

        repn = new byte[(length + BITS_PER_UNIT - 1) / BITS_PER_UNIT];
    }

    /**
     * Creates a BitArray of the specified size, initialized from the
     * specified byte array. The most significant bit of a[0] gets
     * index zero in the BitArray. The array a must be large enough
     * to specify a value for every bit in the BitArray. In other words,
     * 8*a.length >= length.
     */
    public BitArray(int length, byte[] a) throws IllegalArgumentException {

        if (length < 0) {
            throw new IllegalArgumentException("Negative length for BitArray");
        }
        if (a.length * BITS_PER_UNIT < length) {
            throw new IllegalArgumentException("Byte array too short to represent " +
                           "bit array of given length");
        }

        this.length = length;

        int repLength = ((length + BITS_PER_UNIT - 1) / BITS_PER_UNIT);
        int unusedBits = repLength * BITS_PER_UNIT - length;
        byte bitMask = (byte) (0xFF << unusedBits);

        /* 
         normalize the representation:
          1. discard extra bytes
          2. zero out extra bits in the last byte
         */
        repn = new byte[repLength];
        System.arraycopy(a, 0, repn, 0, repLength);
        if (repn.length > 0)
            repn[repn.length - 1] = (byte) (repn[repn.length - 1] & bitMask);
    }

    /**
     * Create a BitArray whose bits are those of the given array
     * of Booleans.
     */
    public BitArray(boolean[] bits) {
        length = bits.length;
        repn = new byte[(length + 7) / 8];

        for (int i = 0; i < length; i++) {
            set(i, bits[i]);
        }
    }

    /**
     * Copy constructor (for cloning).
     */
    private BitArray(BitArray ba) {
        length = ba.length;
        repn = (byte[]) ba.repn.clone();
    }

    /**
     * Returns the indexed bit in this BitArray.
     */
    public boolean get(int index) throws ArrayIndexOutOfBoundsException {
        if (index < 0 || index >= length) {
            throw new ArrayIndexOutOfBoundsException(Integer.toString(index));
        }

        return (repn[subscript(index)] & position(index)) != 0;
    }

    /**
     * Sets the indexed bit in this BitArray.
     */
    public void set(int index, boolean value)
            throws ArrayIndexOutOfBoundsException {
        if (index < 0 || index >= length) {
            throw new ArrayIndexOutOfBoundsException(Integer.toString(index));
        }
        int idx = subscript(index);
        int bit = position(index);

        if (value) {
            repn[idx] |= bit;
        } else {
            repn[idx] &= ~bit;
        }
    }

    /**
     * Returns the length of this BitArray.
     */
    public int length() {
        return length;
    }

    /**
     * Returns a Byte array containing the contents of this BitArray.
     * The bit stored at index zero in this BitArray will be copied
     * into the most significant bit of the zeroth element of the
     * returned byte array. The last byte of the returned byte array
     * will be contain zeros in any bits that do not have corresponding
     * bits in the BitArray. (This matters only if the BitArray's size
     * is not a multiple of 8.)
     */
    public byte[] toByteArray() {
        return (byte[]) repn.clone();
    }

    public boolean equals(Object obj) {
        if (obj == this)
            return true;
        if (obj == null || !(obj instanceof BitArray))
            return false;

        BitArray ba = (BitArray) obj;

        if (ba.length != length)
            return false;

        for (int i = 0; i < repn.length; i += 1) {
            if (repn[i] != ba.repn[i])
                return false;
        }
        return true;
    }

    /**
     * Return a boolean array with the same bit values a this BitArray.
     */
    public boolean[] toBooleanArray() {
        boolean[] bits = new boolean[length];

        for (int i = 0; i < length; i++) {
            bits[i] = get(i);
        }
        return bits;
    }

    /**
     * Returns a hash code value for this bit array.
     * 
     * @return a hash code value for this bit array.
     */
    public int hashCode() {
        int hashCode = 0;

        for (int i = 0; i < repn.length; i++)
            hashCode = 31 * hashCode + repn[i];

        return hashCode ^ length;
    }

    public Object clone() {
        return new BitArray(this);
    }

    private static final byte[][] NYBBLE = {
            { (byte) '0', (byte) '0', (byte) '0', (byte) '0' },
            { (byte) '0', (byte) '0', (byte) '0', (byte) '1' },
            { (byte) '0', (byte) '0', (byte) '1', (byte) '0' },
            { (byte) '0', (byte) '0', (byte) '1', (byte) '1' },
            { (byte) '0', (byte) '1', (byte) '0', (byte) '0' },
            { (byte) '0', (byte) '1', (byte) '0', (byte) '1' },
            { (byte) '0', (byte) '1', (byte) '1', (byte) '0' },
            { (byte) '0', (byte) '1', (byte) '1', (byte) '1' },
            { (byte) '1', (byte) '0', (byte) '0', (byte) '0' },
            { (byte) '1', (byte) '0', (byte) '0', (byte) '1' },
            { (byte) '1', (byte) '0', (byte) '1', (byte) '0' },
            { (byte) '1', (byte) '0', (byte) '1', (byte) '1' },
            { (byte) '1', (byte) '1', (byte) '0', (byte) '0' },
            { (byte) '1', (byte) '1', (byte) '0', (byte) '1' },
            { (byte) '1', (byte) '1', (byte) '1', (byte) '0' },
            { (byte) '1', (byte) '1', (byte) '1', (byte) '1' }
    };

    private static final int BYTES_PER_LINE = 8;

    /**
     * Returns a string representation of this BitArray.
     */
    public String toString() {
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        for (int i = 0; i < repn.length - 1; i++) {
            out.write(NYBBLE[(repn[i] >> 4) & 0x0F], 0, 4);
            out.write(NYBBLE[repn[i] & 0x0F], 0, 4);

            if (i % BYTES_PER_LINE == BYTES_PER_LINE - 1) {
                out.write('\n');
            } else {
                out.write(' ');
            }
        }

        // in last byte of repn, use only the valid bits
        for (int i = BITS_PER_UNIT * (repn.length - 1); i < length; i++) {
            out.write(get(i) ? '1' : '0');
        }

        return new String(out.toByteArray());

    }

}