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 package org.eclipse.jgit.util.io;
45
46 import java.io.IOException;
47 import java.io.OutputStream;
48
49 import org.eclipse.jgit.diff.RawText;
50
51
52
53
54
55
56
57
58
59 public class AutoCRLFOutputStream extends OutputStream {
60
61 static final int BUFFER_SIZE = 8000;
62
63 private final OutputStream out;
64
65 private int buf = -1;
66
67 private byte[] binbuf = new byte[BUFFER_SIZE];
68
69 private byte[] onebytebuf = new byte[1];
70
71 private int binbufcnt = 0;
72
73 private boolean detectBinary;
74
75 private boolean isBinary;
76
77
78
79
80 public AutoCRLFOutputStream(OutputStream out) {
81 this(out, true);
82 }
83
84
85
86
87
88
89
90 public AutoCRLFOutputStream(OutputStream out, boolean detectBinary) {
91 this.out = out;
92 this.detectBinary = detectBinary;
93 }
94
95 @Override
96 public void write(int b) throws IOException {
97 onebytebuf[0] = (byte) b;
98 write(onebytebuf, 0, 1);
99 }
100
101 @Override
102 public void write(byte[] b) throws IOException {
103 int overflow = buffer(b, 0, b.length);
104 if (overflow > 0)
105 write(b, b.length - overflow, overflow);
106 }
107
108 @Override
109 public void write(byte[] b, final int startOff, final int startLen)
110 throws IOException {
111 final int overflow = buffer(b, startOff, startLen);
112 if (overflow < 0)
113 return;
114 final int off = startOff + startLen - overflow;
115 final int len = overflow;
116 if (len == 0)
117 return;
118 int lastw = off;
119 if (isBinary) {
120 out.write(b, off, len);
121 return;
122 }
123 for (int i = off; i < off + len; ++i) {
124 final byte c = b[i];
125 if (c == '\r') {
126 buf = '\r';
127 } else if (c == '\n') {
128 if (buf != '\r') {
129 if (lastw < i) {
130 out.write(b, lastw, i - lastw);
131 }
132 out.write('\r');
133 lastw = i;
134 }
135 buf = -1;
136 } else {
137 buf = -1;
138 }
139 }
140 if (lastw < off + len) {
141 out.write(b, lastw, off + len - lastw);
142 }
143 if (b[off + len - 1] == '\r')
144 buf = '\r';
145 }
146
147 private int buffer(byte[] b, int off, int len) throws IOException {
148 if (binbufcnt > binbuf.length)
149 return len;
150 int copy = Math.min(binbuf.length - binbufcnt, len);
151 System.arraycopy(b, off, binbuf, binbufcnt, copy);
152 binbufcnt += copy;
153 int remaining = len - copy;
154 if (remaining > 0)
155 decideMode();
156 return remaining;
157 }
158
159 private void decideMode() throws IOException {
160 if (detectBinary) {
161 isBinary = RawText.isBinary(binbuf, binbufcnt);
162 detectBinary = false;
163 }
164 int cachedLen = binbufcnt;
165 binbufcnt = binbuf.length + 1;
166 write(binbuf, 0, cachedLen);
167 }
168
169 @Override
170 public void flush() throws IOException {
171 if (binbufcnt <= binbuf.length)
172 decideMode();
173 buf = -1;
174 out.flush();
175 }
176
177 @Override
178 public void close() throws IOException {
179 flush();
180 out.close();
181 }
182 }