2222import com .fasterxml .jackson .core .base .GeneratorBase ;
2323import com .fasterxml .jackson .core .io .SerializedString ;
2424import com .fasterxml .jackson .core .json .JsonWriteContext ;
25+ import com .fasterxml .jackson .databind .ObjectMapper ;
2526import org .msgpack .core .MessagePack ;
2627import org .msgpack .core .MessagePacker ;
2728import org .msgpack .core .buffer .OutputStreamBufferOutput ;
@@ -42,6 +43,8 @@ public class MessagePackGenerator
4243 private static final Charset DEFAULT_CHARSET = Charset .forName ("UTF-8" );
4344 private final MessagePacker messagePacker ;
4445 private static ThreadLocal <OutputStreamBufferOutput > messageBufferOutputHolder = new ThreadLocal <OutputStreamBufferOutput >();
46+ private final OutputStream output ;
47+ private final MessagePack .PackerConfig packerConfig ;
4548 private LinkedList <StackItem > stack ;
4649 private StackItem rootStackItem ;
4750
@@ -97,20 +100,35 @@ List<Object> getKeys()
97100 }
98101 }
99102
100- public MessagePackGenerator (int features , ObjectCodec codec , OutputStream out , MessagePack .PackerConfig packerConfig )
103+ public MessagePackGenerator (
104+ int features ,
105+ ObjectCodec codec ,
106+ OutputStream out ,
107+ MessagePack .PackerConfig packerConfig ,
108+ boolean reuseResourceInGenerator )
101109 throws IOException
102110 {
103111 super (features , codec );
104- OutputStreamBufferOutput messageBufferOutput = messageBufferOutputHolder .get ();
105- if (messageBufferOutput == null ) {
106- messageBufferOutput = new OutputStreamBufferOutput (out );
112+ this .output = out ;
113+
114+ OutputStreamBufferOutput messageBufferOutput ;
115+ if (reuseResourceInGenerator ) {
116+ messageBufferOutput = messageBufferOutputHolder .get ();
117+ if (messageBufferOutput == null ) {
118+ messageBufferOutput = new OutputStreamBufferOutput (out );
119+ messageBufferOutputHolder .set (messageBufferOutput );
120+ }
121+ else {
122+ messageBufferOutput .reset (out );
123+ }
107124 }
108125 else {
109- messageBufferOutput . reset (out );
126+ messageBufferOutput = new OutputStreamBufferOutput (out );
110127 }
111- messageBufferOutputHolder .set (messageBufferOutput );
112-
113128 this .messagePacker = packerConfig .newPacker (messageBufferOutput );
129+
130+ this .packerConfig = packerConfig ;
131+
114132 this .stack = new LinkedList <StackItem >();
115133 }
116134
@@ -224,7 +242,11 @@ else if (v instanceof MessagePackExtensionType) {
224242 messagePacker .writePayload (extData );
225243 }
226244 else {
227- throw new IllegalArgumentException (v .toString ());
245+ messagePacker .flush ();
246+ MessagePackFactory messagePackFactory = new MessagePackFactory (packerConfig );
247+ messagePackFactory .setReuseResourceInGenerator (false );
248+ ObjectMapper objectMapper = new ObjectMapper (messagePackFactory );
249+ output .write (objectMapper .writeValueAsBytes (v ));
228250 }
229251 }
230252
0 commit comments