1717
1818import org .msgpack .core .buffer .MessageBuffer ;
1919import org .msgpack .core .buffer .MessageBufferOutput ;
20- import org .msgpack .core .buffer .OutputStreamBufferOutput ;
2120import org .msgpack .value .Value ;
2221
2322import java .io .Closeable ;
24- import java .io .OutputStream ;
2523import java .math .BigInteger ;
2624import java .io .IOException ;
2725import java .nio .ByteBuffer ;
@@ -82,7 +80,6 @@ public MessagePacker(MessageBufferOutput out) {
8280 public MessagePacker (MessageBufferOutput out , MessagePack .Config config ) {
8381 this .config = checkNotNull (config , "config is null" );
8482 this .out = checkNotNull (out , "MessageBufferOutput is null" );
85- this .buffer = MessageBuffer .newBuffer (config .getPackerBufferSize ());
8683 this .position = 0 ;
8784 }
8885
@@ -103,14 +100,25 @@ private void prepareEncoder() {
103100 }
104101 }
105102
103+ private void prepareBuffer () throws IOException {
104+ if (buffer == null ) {
105+ buffer = out .next (config .getPackerBufferSize ());
106+ }
107+ }
108+
109+
106110 public void flush () throws IOException {
111+ if (buffer == null ) {
112+ return ;
113+ }
114+
107115 if (position == buffer .size ()) {
108116 out .flush (buffer );
109117 }
110118 else {
111119 out .flush (buffer .slice (0 , position ));
112120 }
113- buffer = out . next ( config . getPackerBufferSize ()) ;
121+ buffer = null ;
114122 position = 0 ;
115123 }
116124
@@ -124,10 +132,10 @@ public void close() throws IOException {
124132 }
125133
126134 private void ensureCapacity (int numBytesToWrite ) throws IOException {
127- if (position + numBytesToWrite < buffer .size ())
128- return ;
129-
130- flush ();
135+ if (buffer == null || position + numBytesToWrite >= buffer .size ()) {
136+ flush () ;
137+ buffer = out . next ( Math . max ( config . getPackerBufferSize (), numBytesToWrite ));
138+ }
131139 }
132140
133141
@@ -335,6 +343,7 @@ public MessagePacker packString(String s) throws IOException {
335343
336344 flush ();
337345
346+ prepareBuffer ();
338347 boolean isExtended = false ;
339348 ByteBuffer encodeBuffer = buffer .toByteBuffer (position , buffer .size ()-position );
340349 encoder .reset ();
@@ -525,8 +534,10 @@ public MessagePacker writePayload(byte[] src, int off, int len) throws IOExcepti
525534 else {
526535 int cursor = 0 ;
527536 while (cursor < len ) {
528- if (position >= buffer .size ())
537+ if (buffer != null && position >= buffer .size ()) {
529538 flush ();
539+ }
540+ prepareBuffer ();
530541 int writeLen = Math .min (buffer .size () - position , len - cursor );
531542 buffer .putBytes (position , src , off + cursor , writeLen );
532543 position += writeLen ;
0 commit comments