1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.giraph.utils;
19
20 import org.junit.Assert;
21 import org.junit.Test;
22
23 import java.io.IOException;
24 import java.io.UTFDataFormatException;
25
26 import static org.junit.Assert.assertEquals;
27
28 public class TestUnsafeByteArrayOutputStream {
29 @Test
30 public void testWriteBytes() throws IOException {
31 UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream();
32 int length = os.getByteArray().length;
33
34 StringBuilder sb = new StringBuilder();
35 for (int i = 0; i < length; i++) {
36 sb.append("\u00ea");
37 }
38
39 String s = sb.toString();
40 os.writeBytes(s);
41
42 UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream(os.getByteArray());
43
44 for (int i = 0; i < s.length(); i++) {
45 assertEquals((byte) s.charAt(i), is.readByte());
46 }
47
48 os.close();
49 }
50
51 @Test
52 public void testWriteChars() throws IOException {
53 UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream();
54 int length = os.getByteArray().length;
55
56 StringBuilder sb = new StringBuilder();
57 for (int i = 0; i < length; i++) {
58 sb.append("\u10ea");
59 }
60
61 String s = sb.toString();
62 os.writeChars(s);
63
64 UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream(os.getByteArray());
65
66 for (int i = 0; i < s.length(); i++) {
67 assertEquals(s.charAt(i), is.readChar());
68 }
69
70 os.close();
71 }
72
73 @Test
74 public void testWriteUTF() throws IOException {
75 StringBuilder sb = new StringBuilder();
76 for (int i = 0; i < 20; i++) {
77 sb.append("\u06ea");
78 }
79
80 String s = sb.toString();
81
82 assertEquals(s, writeAndReadUTF(s));
83 }
84
85 @Test
86 public void testWriteLongUTF() throws IOException {
87 int maxLength = 65535;
88 StringBuilder sb = new StringBuilder();
89 for (int i = 0; i < maxLength; i++) {
90 sb.append("a");
91 }
92
93 String s = sb.toString();
94
95 assertEquals(s, writeAndReadUTF(s));
96
97 s = sb.append("a").toString();
98 try {
99 writeAndReadUTF(s);
100 throw new IllegalStateException("Exception expected");
101 } catch (Exception e) {
102 Assert.assertTrue(e instanceof UTFDataFormatException);
103 }
104 }
105
106 private String writeAndReadUTF(String s) throws IOException {
107 UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream();
108 os.writeUTF(s);
109 os.close();
110 UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream(os.getByteArray());
111 return is.readUTF();
112 }
113 }