Skip to content

Commit be0fe92

Browse files
committed
Improve bin printer for unprintable characters.
msgpack_object_print used fwrite to write binary data to a stream. The intention of the function is to produce a human-readable representation of the object for debugging purposes. Having arbitrary data dumped as is can cause issues with terminals that interpret it as control sequences. This change prints printable characters as is and unprintable characters as hex-escapes ("\xNN"). Note that UTF-8 encoded characters will now be printed as escaped sequence of UTF-8 bytes. This is an acceptable compromise, as doing otherwise would require a light form of UTF-8 decoding and BIN-typed objects should not be used to transport UTF-8 strings anyway (STR should be used instead).
1 parent 4218128 commit be0fe92

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

src/objectc.c

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
*/
1010
#include "msgpack/object.h"
1111
#include "msgpack/pack.h"
12+
#include <ctype.h>
1213
#include <stdio.h>
1314
#include <string.h>
1415

@@ -112,6 +113,21 @@ int msgpack_pack_object(msgpack_packer* pk, msgpack_object d)
112113
}
113114

114115

116+
static void msgpack_object_bin_print(FILE* out, msgpack_object_bin o)
117+
{
118+
size_t i;
119+
for (i = 0; i < o.size; i++) {
120+
if (o.ptr[i] == '"') {
121+
fputs("\\\"", out);
122+
} else if (isprint(o.ptr[i])) {
123+
fputc(o.ptr[i], out);
124+
} else {
125+
fprintf(out, "\\x%02x", (unsigned char)o.ptr[i]);
126+
}
127+
}
128+
}
129+
130+
115131
void msgpack_object_print(FILE* out, msgpack_object o)
116132
{
117133
switch(o.type) {
@@ -159,7 +175,7 @@ void msgpack_object_print(FILE* out, msgpack_object o)
159175

160176
case MSGPACK_OBJECT_BIN:
161177
fprintf(out, "\"");
162-
fwrite(o.via.bin.ptr, o.via.bin.size, 1, out);
178+
msgpack_object_bin_print(out, o.via.bin);
163179
fprintf(out, "\"");
164180
break;
165181

0 commit comments

Comments
 (0)