1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45 package org.eclipse.jgit.util.io;
46
47 import static java.nio.charset.StandardCharsets.UTF_8;
48
49 import java.io.ByteArrayInputStream;
50 import java.io.ByteArrayOutputStream;
51 import java.io.IOException;
52 import java.io.InputStream;
53 import java.io.OutputStream;
54
55 import org.junit.Assert;
56 import org.junit.Test;
57
58 public class AutoCRLFOutputStreamTest {
59
60 @Test
61 public void test() throws IOException {
62 assertNoCrLf("", "");
63 assertNoCrLf("\r", "\r");
64 assertNoCrLf("\r\n", "\n");
65 assertNoCrLf("\r\n", "\r\n");
66 assertNoCrLf("\r\r", "\r\r");
67 assertNoCrLf("\r\n\r", "\n\r");
68 assertNoCrLf("\r\n\r\r", "\r\n\r\r");
69 assertNoCrLf("\r\n\r\n", "\r\n\r\n");
70 assertNoCrLf("\r\n\r\n\r", "\n\r\n\r");
71 assertNoCrLf("\0\n", "\0\n");
72 }
73
74 @Test
75 public void testBoundary() throws IOException {
76 for (int i = AutoCRLFOutputStream.BUFFER_SIZE - 10; i < AutoCRLFOutputStream.BUFFER_SIZE + 10; i++) {
77 String s1 = Strings.repeat("a", i);
78 assertNoCrLf(s1, s1);
79 String s2 = Strings.repeat("\0", i);
80 assertNoCrLf(s2, s2);
81 }
82 }
83
84 private void assertNoCrLf(String string, String string2) throws IOException {
85 assertNoCrLfHelper(string, string2);
86
87
88 assertNoCrLfHelper("\u00e5" + string, "\u00e5" + string2);
89 assertNoCrLfHelper("\u00e5" + string + "\u00e5", "\u00e5" + string2
90 + "\u00e5");
91 assertNoCrLfHelper(string + "\u00e5", string2 + "\u00e5");
92 }
93
94 private void assertNoCrLfHelper(String expect, String input)
95 throws IOException {
96 byte[] inbytes = input.getBytes(UTF_8);
97 byte[] expectBytes = expect.getBytes(UTF_8);
98 for (int i = -4; i < 5; ++i) {
99 int size = Math.abs(i);
100 byte[] buf = new byte[size];
101 try (InputStream in = new ByteArrayInputStream(inbytes);
102 ByteArrayOutputStream bos = new ByteArrayOutputStream();
103 OutputStream out = new AutoCRLFOutputStream(bos)) {
104 if (i > 0) {
105 int n;
106 while ((n = in.read(buf)) >= 0) {
107 out.write(buf, 0, n);
108 }
109 } else if (i < 0) {
110 int n;
111 while ((n = in.read(buf)) >= 0) {
112 byte[] b = new byte[n];
113 System.arraycopy(buf, 0, b, 0, n);
114 out.write(b);
115 }
116 } else {
117 int c;
118 while ((c = in.read()) != -1)
119 out.write(c);
120 }
121 out.flush();
122 byte[] actualBytes = bos.toByteArray();
123 Assert.assertEquals("bufsize=" + size, encode(expectBytes),
124 encode(actualBytes));
125 }
126 }
127 }
128
129 String encode(byte[] in) {
130 StringBuilder str = new StringBuilder();
131 for (byte b : in) {
132 if (b < 32)
133 str.append(0xFF & b);
134 else {
135 str.append("'");
136 str.append((char) b);
137 str.append("'");
138 }
139 str.append(' ');
140 }
141 return str.toString();
142 }
143
144 }