blob: 949cd88e580843cb82f219b80ca861caa8889f12 (
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
|
package com.yahoo.io;
import com.yahoo.text.Utf8;
import java.io.IOException;
import java.nio.ByteBuffer;
public class Utf8ByteWriter extends AbstractByteWriter {
private ByteBuffer myBuf;
public Utf8ByteWriter(int initialBuffer) {
super(Utf8.getNewEncoder());
myBuf = ByteBuffer.allocate(initialBuffer);
}
@Override
public void send(ByteBuffer src) throws IOException {
if (myBuf.remaining() < src.remaining()) {
ByteBuffer newBuf = ByteBuffer.allocate(Integer.highestOneBit(myBuf.position()+src.remaining()) << 1);
myBuf.flip();
newBuf.put(myBuf);
myBuf = newBuf;
}
myBuf.put(src);
}
@Override
public void flush() throws IOException {
buffer.flush();
}
@Override
public void close() throws IOException {
buffer.flush();
myBuf.flip();
}
/**
* Return a buffer ready for read. Must only be called after writer has been closed.
* @return A flipped ByteBuffer
*/
public ByteBuffer getBuf() {
if (myBuf.position() != 0) {
throw new IllegalStateException("Call close() befor getBuf(), pos=" + myBuf.position() + ", limit=" + myBuf.limit());
}
return myBuf;
}
}
|