blob: de656842f10bd4c343612ee5c95240fef840d656 (
plain) (
blame)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.handler;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Objects;
/**
* @author <a href="mailto:simon@yahoo-inc.com">Simon Thoresen Hult</a>
*/
abstract class AbstractContentOutputStream extends OutputStream {
public static final int BUFFERSIZE = 4096;
private ByteBuffer current;
@Override
public final void write(int b) {
if (current == null) {
current = ByteBuffer.allocate(BUFFERSIZE);
}
current.put((byte)b);
if (current.remaining() == 0) {
flush();
}
}
@Override
public final void write(byte[] buf, int offset, int length) {
Objects.requireNonNull(buf, "buf");
if (current == null) {
current = ByteBuffer.allocate(BUFFERSIZE + length);
}
int part = Math.min(length, current.remaining());
current.put(buf, offset, part);
if (current.remaining() == 0) {
flush();
}
if (part < length) {
write(buf, offset + part, length - part);
}
}
@Override
public final void write(byte[] buf) {
write(buf, 0, buf.length);
}
@Override
public final void flush() {
if (current == null || current.position() == 0) {
return;
}
ByteBuffer buf = current;
current = null;
buf.flip();
doFlush(buf);
}
@Override
public final void close() {
flush();
doClose();
}
protected abstract void doFlush(ByteBuffer buf);
protected abstract void doClose();
}
|