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 package org.waarp.compress.zstdsafe;
35
36 import org.waarp.compress.MalformedInputException;
37
38 import static org.waarp.compress.zstdsafe.Constants.*;
39 import static org.waarp.compress.zstdsafe.UnsafeUtil.*;
40
41 final class Util {
42 private Util() {
43 }
44
45 public static int highestBit(final int value) {
46 return 31 - Integer.numberOfLeadingZeros(value);
47 }
48
49 public static boolean isPowerOf2(final int value) {
50 return (value & (value - 1)) == 0;
51 }
52
53 public static int mask(final int bits) {
54 return (1 << bits) - 1;
55 }
56
57 public static void verify(final boolean condition, final int offset,
58 final String reason) {
59 if (!condition) {
60 throw new MalformedInputException(offset, reason);
61 }
62 }
63
64 public static void checkArgument(final boolean condition,
65 final String reason) {
66 if (!condition) {
67 throw new IllegalArgumentException(reason);
68 }
69 }
70
71 public static void checkState(final boolean condition, final String reason) {
72 if (!condition) {
73 throw new IllegalStateException(reason);
74 }
75 }
76
77 public static MalformedInputException fail(final int offset,
78 final String reason) {
79 throw new MalformedInputException(offset, reason);
80 }
81
82 public static int cycleLog(final int hashLog,
83 final CompressionParameters.Strategy strategy) {
84 int cycleLog = hashLog;
85 if (strategy == CompressionParameters.Strategy.BTLAZY2 ||
86 strategy == CompressionParameters.Strategy.BTOPT ||
87 strategy == CompressionParameters.Strategy.BTULTRA) {
88 cycleLog = hashLog - 1;
89 }
90 return cycleLog;
91 }
92
93 public static void put24BitLittleEndian(final byte[] outputBase,
94 final int outputAddress,
95 final int value) {
96 putShort(outputBase, outputAddress, (short) value);
97 outputBase[outputAddress + SIZE_OF_SHORT] = (byte) (value >>> Short.SIZE);
98 }
99
100
101 public static int minTableLog(final int inputSize, final int maxSymbolValue) {
102 if (inputSize <= 1) {
103 throw new IllegalArgumentException(
104 "Not supported. RLE should be used instead");
105 }
106
107 final int minBitsSrc = highestBit((inputSize - 1)) + 1;
108 final int minBitsSymbols = highestBit(maxSymbolValue) + 2;
109 return Math.min(minBitsSrc, minBitsSymbols);
110 }
111 }