23
23
/** Captures the last N bytes of output. */
24
24
public class CircularOutputStream extends OutputStream {
25
25
private static final int DEFAULT_SIZE = 4096 ;
26
- private int start ;
27
26
private int end ;
28
27
private boolean filled = false ;
29
- private byte [] buffer ;
28
+ private final byte [] buffer ;
30
29
31
30
public CircularOutputStream (int maxSize ) {
32
31
buffer = new byte [maxSize ];
@@ -36,22 +35,57 @@ public CircularOutputStream() {
36
35
this (DEFAULT_SIZE );
37
36
}
38
37
38
+ @ Override
39
+ public void write (byte [] b ) {
40
+ // overridden to get rid of the IOException
41
+ write (b , 0 , b .length );
42
+ }
43
+
44
+ @ Override
45
+ public synchronized void write (byte [] b , int off , int len ) {
46
+ int bufferSize = buffer .length ;
47
+
48
+ while (len > 0 ) {
49
+ int chunk = Math .min (bufferSize , len );
50
+
51
+ if (bufferSize >= end + chunk ) {
52
+ System .arraycopy (b , off , buffer , end , chunk );
53
+ end += chunk ;
54
+ } else {
55
+ int space = bufferSize - end ;
56
+ System .arraycopy (b , off , buffer , end , space );
57
+ filled = true ;
58
+ end = chunk - space ;
59
+ System .arraycopy (b , off + space , buffer , 0 , end );
60
+ }
61
+
62
+ off += chunk ;
63
+ len -= chunk ;
64
+ }
65
+ }
66
+
39
67
@ Override
40
68
public synchronized void write (int b ) {
41
69
if (end == buffer .length ) {
42
70
filled = true ;
43
71
end = 0 ;
44
72
}
45
73
46
- if (filled && end == start ) {
47
- start = start == buffer .length - 1 ? 0 : start + 1 ;
48
- }
49
-
50
74
buffer [end ++] = (byte ) b ;
51
75
}
52
76
53
77
@ Override
54
- public String toString () {
78
+ public void flush () {
79
+ // overridden to get rid of the IOException
80
+ }
81
+
82
+ @ Override
83
+ public void close () {
84
+ // overridden to get rid of the IOException
85
+ }
86
+
87
+ @ Override
88
+ public synchronized String toString () {
55
89
int size = filled ? buffer .length : end ;
56
90
byte [] toReturn = new byte [size ];
57
91
@@ -61,13 +95,9 @@ public String toString() {
61
95
return new String (toReturn , Charset .defaultCharset ());
62
96
}
63
97
64
- int copyStart = buffer .length - start ;
65
- if (copyStart == buffer .length ) {
66
- copyStart = 0 ;
67
- }
68
-
69
- System .arraycopy (buffer , start , toReturn , 0 , copyStart );
70
- System .arraycopy (buffer , 0 , toReturn , copyStart , end );
98
+ int n = buffer .length - end ;
99
+ System .arraycopy (buffer , end , toReturn , 0 , n );
100
+ System .arraycopy (buffer , 0 , toReturn , n , end );
71
101
return new String (toReturn , Charset .defaultCharset ());
72
102
}
73
103
}
0 commit comments