Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions msgpack-core/src/main/java/org/msgpack/core/MessagePacker.java
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ public class MessagePacker implements Closeable {

private int position;

/**
* Total read byte size
*/
private long totalWrittenBytes;

/**
* String encoder
*/
Expand Down Expand Up @@ -96,9 +101,13 @@ public MessageBufferOutput reset(MessageBufferOutput out) throws IOException {
MessageBufferOutput old = this.out;
this.out = newOut;
this.position = 0;
this.totalWrittenBytes = 0;
return old;
}

public long getTotalWritternBytes() {
return totalWrittenBytes;
}

private void prepareEncoder() {
if(encoder == null) {
Expand Down Expand Up @@ -138,6 +147,7 @@ public void close() throws IOException {
}

private void ensureCapacity(int numBytesToWrite) throws IOException {
totalWrittenBytes += numBytesToWrite;
if(buffer == null || position + numBytesToWrite >= buffer.size()) {
flush();
buffer = out.next(Math.max(config.getPackerBufferSize(), numBytesToWrite));
Expand Down Expand Up @@ -355,10 +365,12 @@ public MessagePacker packString(String s) throws IOException {
encoder.reset();
while(in.hasRemaining()) {
try {
int originalEncodeBuffer = encodeBuffer.position();
CoderResult cr = encoder.encode(in, encodeBuffer, true);

if(cr.isUnderflow()) {
cr = encoder.flush(encodeBuffer);
totalWrittenBytes += encodeBuffer.position() - originalEncodeBuffer;
}

if(cr.isOverflow()) {
Expand Down Expand Up @@ -499,6 +511,7 @@ public MessagePacker packRawStringHeader(int len) throws IOException {


public MessagePacker writePayload(ByteBuffer src) throws IOException {
totalWrittenBytes += src.remaining();
if(src.remaining() >= config.getPackerRawDataCopyingThreshold()) {
// Use the source ByteBuffer directly to avoid memory copy

Expand All @@ -523,6 +536,7 @@ public MessagePacker writePayload(ByteBuffer src) throws IOException {
position += writeLen;
}
}

return this;
}

Expand Down Expand Up @@ -555,6 +569,7 @@ public MessagePacker writePayload(byte[] src, int off, int len) throws IOExcepti
cursor += writeLen;
}
}
totalWrittenBytes += len;
return this;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,23 @@ class MessagePackerTest extends MessagePackSpec {
up1.hasNext shouldBe false
up1.close
}

}

"compute totalWrittenBytes" in {
val out = new ByteArrayOutputStream
val packerTotalWrittenBytes = IOUtil.withResource(msgpack.newPacker(out)) { packer =>

packer.packByte(0)
.packBoolean(true)
.packShort(12)
.packInt(1024)
.packLong(Long.MaxValue)
.packString("foobar")
.flush()

packer.getTotalWritternBytes
}

out.toByteArray.length shouldBe packerTotalWrittenBytes
}
}