1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.util.vint;
20
21 import java.io.IOException;
22 import java.io.OutputStream;
23
24 import org.apache.hadoop.hbase.classification.InterfaceAudience;
25 import org.apache.hadoop.hbase.nio.ByteBuff;
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 @InterfaceAudience.Private
52 public class UFIntTool {
53
54 private static final int NUM_BITS_IN_LONG = 64;
55
56 public static long maxValueForNumBytes(int numBytes) {
57 return (1L << (numBytes * 8)) - 1;
58 }
59
60 public static int numBytes(final long value) {
61 if (value == 0) {
62 return 1;
63 }
64 return (NUM_BITS_IN_LONG + 7 - Long.numberOfLeadingZeros(value)) / 8;
65 }
66
67 public static byte[] getBytes(int outputWidth, final long value) {
68 byte[] bytes = new byte[outputWidth];
69 writeBytes(outputWidth, value, bytes, 0);
70 return bytes;
71 }
72
73 public static void writeBytes(int outputWidth, final long value, byte[] bytes, int offset) {
74 bytes[offset + outputWidth - 1] = (byte) value;
75 for (int i = outputWidth - 2; i >= 0; --i) {
76 bytes[offset + i] = (byte) (value >>> (outputWidth - i - 1) * 8);
77 }
78 }
79
80 private static final long[] MASKS = new long[] {
81 (long) 255,
82 (long) 255 << 8,
83 (long) 255 << 16,
84 (long) 255 << 24,
85 (long) 255 << 32,
86 (long) 255 << 40,
87 (long) 255 << 48,
88 (long) 255 << 56
89 };
90
91 public static void writeBytes(int outputWidth, final long value, OutputStream os) throws IOException {
92 for (int i = outputWidth - 1; i >= 0; --i) {
93 os.write((byte) ((value & MASKS[i]) >>> (8 * i)));
94 }
95 }
96
97 public static long fromBytes(final byte[] bytes) {
98 long value = 0;
99 value |= bytes[0] & 0xff;
100 for (int i = 1; i < bytes.length; ++i) {
101 value <<= 8;
102 value |= bytes[i] & 0xff;
103 }
104 return value;
105 }
106
107 public static long fromBytes(final ByteBuff buf, final int offset, final int width) {
108 long value = 0;
109 value |= buf.get(offset + 0) & 0xff;
110 for (int i = 1; i < width; ++i) {
111 value <<= 8;
112 value |= buf.get(i + offset) & 0xff;
113 }
114 return value;
115 }
116
117 }