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.InputStream;
23 import java.io.OutputStream;
24 import java.nio.ByteBuffer;
25
26 import org.apache.hadoop.hbase.classification.InterfaceAudience;
27 import org.apache.hadoop.hbase.nio.ByteBuff;
28 import org.apache.hadoop.hbase.nio.SingleByteBuff;
29
30
31
32
33
34 @InterfaceAudience.Private
35 public class UVLongTool{
36
37 public static final byte
38 BYTE_7_RIGHT_BITS_SET = 127,
39 BYTE_LEFT_BIT_SET = -128;
40
41 public static final long
42 LONG_7_RIGHT_BITS_SET = 127,
43 LONG_8TH_BIT_SET = 128;
44
45 public static final byte[]
46 MAX_VALUE_BYTES = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1, 127 };
47
48
49
50
51 public static int numBytes(long in) {
52 if (in == 0) {
53 return 1;
54 }
55 return (70 - Long.numberOfLeadingZeros(in)) / 7;
56 }
57
58 public static byte[] getBytes(long value) {
59 int numBytes = numBytes(value);
60 byte[] bytes = new byte[numBytes];
61 long remainder = value;
62 for (int i = 0; i < numBytes - 1; ++i) {
63 bytes[i] = (byte) ((remainder & LONG_7_RIGHT_BITS_SET) | LONG_8TH_BIT_SET);
64 remainder >>= 7;
65 }
66 bytes[numBytes - 1] = (byte) (remainder & LONG_7_RIGHT_BITS_SET);
67 return bytes;
68 }
69
70 public static int writeBytes(long value, OutputStream os) throws IOException {
71 int numBytes = numBytes(value);
72 long remainder = value;
73 for (int i = 0; i < numBytes - 1; ++i) {
74
75 os.write((byte) ((remainder & LONG_7_RIGHT_BITS_SET) | LONG_8TH_BIT_SET));
76 remainder >>= 7;
77 }
78
79 os.write((byte) (remainder & LONG_7_RIGHT_BITS_SET));
80 return numBytes;
81 }
82
83
84
85 public static long getLong(byte[] bytes) {
86 return getLong(new SingleByteBuff(ByteBuffer.wrap(bytes)), 0);
87 }
88
89 public static long getLong(ByteBuff buf, int offset) {
90 long value = 0;
91 for (int i = 0;; ++i) {
92 byte b = buf.get(offset + i);
93 long shifted = BYTE_7_RIGHT_BITS_SET & b;
94 shifted <<= 7 * i;
95 value |= shifted;
96 if (b >= 0) {
97 break;
98 }
99 }
100 return value;
101 }
102
103 public static long getLong(InputStream is) throws IOException {
104 long value = 0;
105 int i = 0;
106 int b;
107 do {
108 b = is.read();
109 long shifted = BYTE_7_RIGHT_BITS_SET & b;
110 shifted <<= 7 * i;
111 value |= shifted;
112 ++i;
113 } while (b > Byte.MAX_VALUE);
114 return value;
115 }
116 }