1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.procedure2.util;
20
21 import java.io.IOException;
22 import java.io.OutputStream;
23 import java.util.Arrays;
24
25 import org.apache.hadoop.hbase.classification.InterfaceAudience;
26 import org.apache.hadoop.hbase.classification.InterfaceStability;
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43 @InterfaceAudience.Private
44 @InterfaceStability.Evolving
45 public class ByteSlot extends OutputStream {
46 private static final int LARGE_GROW_SIZE_THRESHOLD = 8 << 20;
47 private static final int LARGE_GROW_SIZE = 1 << 20;
48 private static final int RESET_THRESHOLD = 64 << 20;
49 private static final int GROW_ALIGN = 128;
50
51 private byte[] buf;
52 private int head;
53 private int size;
54
55 public void reset() {
56 if (buf != null && buf.length > RESET_THRESHOLD) {
57 buf = null;
58 }
59 head = 0;
60 size = 0;
61 }
62
63 public void markHead() {
64 head = size;
65 }
66
67 public int getHead() {
68 return head;
69 }
70
71 public int size() {
72 return size;
73 }
74
75 public byte[] getBuffer() {
76 return buf;
77 }
78
79 public void writeAt(int offset, int b) {
80 head = Math.min(head, offset);
81 buf[offset] = (byte)b;
82 }
83
84 @Override
85 public void write(int b) {
86 ensureCapacity(size + 1);
87 buf[size++] = (byte)b;
88 }
89
90 @Override
91 public void write(byte[] b, int off, int len) {
92 ensureCapacity(size + len);
93 System.arraycopy(b, off, buf, size, len);
94 size += len;
95 }
96
97 public void writeTo(final OutputStream stream) throws IOException {
98 if (head != 0) {
99 stream.write(buf, head, size - head);
100 stream.write(buf, 0, head);
101 } else {
102 stream.write(buf, 0, size);
103 }
104 }
105
106 private void ensureCapacity(int minCapacity) {
107 minCapacity = (minCapacity + (GROW_ALIGN - 1)) & -GROW_ALIGN;
108 if (buf == null) {
109 buf = new byte[minCapacity];
110 } else if (minCapacity > buf.length) {
111 int newCapacity;
112 if (buf.length <= LARGE_GROW_SIZE_THRESHOLD) {
113 newCapacity = buf.length << 1;
114 } else {
115 newCapacity = buf.length + LARGE_GROW_SIZE;
116 }
117 if (minCapacity > newCapacity) {
118 newCapacity = minCapacity;
119 }
120 buf = Arrays.copyOf(buf, newCapacity);
121 }
122 }
123 }