aboutsummaryrefslogtreecommitdiffstats
path: root/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/BitSet.java
blob: 385e3caa06e9d80bd2fab9317b8ca6797ff27440 (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
/*
 * Copyright (C) 2012, Google Inc. and others
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Distribution License v. 1.0 which is available at
 * https://www.eclipse.org/org/documents/edl-v10.php.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

package org.eclipse.jgit.internal.storage.file;

import java.util.Arrays;

import com.googlecode.javaewah.EWAHCompressedBitmap;

/**
 * A random access BitSet to supports efficient conversions to
 * EWAHCompressedBitmap.
 */
final class BitSet {

	private long[] words;

	BitSet(int initialCapacity) {
		words = new long[block(initialCapacity) + 1];
	}

	final void clear() {
		Arrays.fill(words, 0);
	}

	final void set(int position) {
		int block = block(position);
		if (block >= words.length) {
			long[] buf = new long[2 * block(position)];
			System.arraycopy(words, 0, buf, 0, words.length);
			words = buf;
		}
		words[block] |= mask(position);
	}

	final void clear(int position) {
		int block = block(position);
		if (block < words.length)
			words[block] &= ~mask(position);
	}

	final boolean get(int position) {
		int block = block(position);
		return block < words.length && (words[block] & mask(position)) != 0;
	}

	final EWAHCompressedBitmap toEWAHCompressedBitmap() {
		EWAHCompressedBitmap compressed = new EWAHCompressedBitmap(
				words.length);
		int runningEmptyWords = 0;
		long lastNonEmptyWord = 0;
		for (long word : words) {
			if (word == 0) {
				runningEmptyWords++;
				continue;
			}

			if (lastNonEmptyWord != 0)
				compressed.addWord(lastNonEmptyWord);

			if (runningEmptyWords > 0) {
				compressed.addStreamOfEmptyWords(false, runningEmptyWords);
				runningEmptyWords = 0;
			}

			lastNonEmptyWord = word;
		}
		int bitsThatMatter = 64 - Long.numberOfLeadingZeros(lastNonEmptyWord);
		if (bitsThatMatter > 0)
			compressed.addWord(lastNonEmptyWord, bitsThatMatter);
		return compressed;
	}

	private static final int block(int position) {
		return position >> 6;
	}

	private static final long mask(int position) {
		return 1L << position;
	}
}