-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCheckedFrequencyTable.java
More file actions
94 lines (68 loc) · 2.33 KB
/
Copy pathCheckedFrequencyTable.java
File metadata and controls
94 lines (68 loc) · 2.33 KB
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
package nayuki.arithcode;
/**
* A wrapper that checks the preconditions (arguments) and postconditions (return value) of all the frequency table methods.
* Useful for finding faults in a frequency table implementation. Current this does not check arithmetic overflow conditions.
*/
public final class CheckedFrequencyTable implements FrequencyTable {
// The underlying frequency table that holds the data.
private FrequencyTable freqTable;
public CheckedFrequencyTable(FrequencyTable freq) {
if (freq == null)
throw new NullPointerException();
freqTable = freq;
}
public int getSymbolLimit() {
int result = freqTable.getSymbolLimit();
if (result <= 0)
throw new IllegalStateException("Non-positive symbol limit");
return result;
}
public int get(int symbol) {
checkSymbolInRange(symbol);
int result = freqTable.get(symbol);
if (result < 0)
throw new IllegalStateException("Negative symbol frequency");
return result;
}
public int getTotal() {
int result = freqTable.getTotal();
if (result < 0)
throw new IllegalStateException("Negative total frequency");
return result;
}
public int getLow(int symbol) {
checkSymbolInRange(symbol);
int low = freqTable.getLow (symbol);
int high = freqTable.getHigh(symbol);
int total = freqTable.getTotal();
if (!(0 <= low && low <= high && high <= total))
throw new IllegalStateException("Symbol low cumulative frequency out of range");
return low;
}
public int getHigh(int symbol) {
checkSymbolInRange(symbol);
int low = freqTable.getLow (symbol);
int high = freqTable.getHigh(symbol);
int total = freqTable.getTotal();
if (!(0 <= low && low <= high && high <= total))
throw new IllegalStateException("Symbol high cumulative frequency out of range");
return high;
}
public String toString() {
return "CheckFrequencyTable (" + freqTable.toString() + ")";
}
public void set(int symbol, int freq) {
checkSymbolInRange(symbol);
if (freq < 0)
throw new IllegalArgumentException("Negative symbol frequency");
freqTable.set(symbol, freq);
}
public void increment(int symbol) {
checkSymbolInRange(symbol);
freqTable.increment(symbol);
}
private void checkSymbolInRange(int symbol) {
if (symbol < 0 || symbol >= getSymbolLimit())
throw new IllegalArgumentException("Symbol out of range");
}
}