1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.hadoop.hbase.io;
19
20 import static org.junit.Assert.assertEquals;
21
22 import java.io.ByteArrayOutputStream;
23 import java.io.DataInputStream;
24 import java.io.DataOutputStream;
25 import java.nio.ByteBuffer;
26
27 import org.apache.hadoop.hbase.testclassification.SmallTests;
28 import org.apache.hadoop.hbase.util.Bytes;
29 import org.junit.Test;
30 import org.junit.experimental.categories.Category;
31
32 @Category(SmallTests.class)
33 public class TestByteBufferInputStream {
34
35 @Test
36 public void testReads() throws Exception {
37 ByteArrayOutputStream bos = new ByteArrayOutputStream(100);
38 DataOutputStream dos = new DataOutputStream(bos);
39 String s = "test";
40 int i = 128;
41 dos.write(1);
42 dos.writeInt(i);
43 dos.writeBytes(s);
44 dos.writeLong(12345L);
45 dos.writeShort(2);
46 dos.flush();
47 ByteBuffer bb = ByteBuffer.wrap(bos.toByteArray());
48
49
50
51 ByteBufferInputStream bbis = new ByteBufferInputStream(bb);
52 assertEquals(15 + s.length(), bbis.available());
53 assertEquals(1, bbis.read());
54 byte[] ib = new byte[4];
55 bbis.read(ib);
56 assertEquals(i, Bytes.toInt(ib));
57 byte[] sb = new byte[s.length()];
58 bbis.read(sb);
59 assertEquals(s, Bytes.toString(sb));
60 byte[] lb = new byte[8];
61 bbis.read(lb);
62 assertEquals(12345, Bytes.toLong(lb));
63 assertEquals(2, bbis.available());
64 ib = new byte[4];
65 int read = bbis.read(ib, 0, ib.length);
66
67 assertEquals(2, read);
68 assertEquals(2, Bytes.toShort(ib));
69 assertEquals(0, bbis.available());
70
71 assertEquals(-1, bbis.read());
72 bbis.close();
73
74 bb = ByteBuffer.wrap(bos.toByteArray());
75 bbis = new ByteBufferInputStream(bb);
76 DataInputStream dis = new DataInputStream(bbis);
77 dis.read();
78 assertEquals(i, dis.readInt());
79 dis.close();
80 }
81 }