Skip to content

Commit c875d7c

Browse files
committed
speedup pack_bin, ext, str; catch short reads
1 parent d29184b commit c875d7c

File tree

1 file changed

+7
-10
lines changed

1 file changed

+7
-10
lines changed

shared-module/msgpack/__init__.c

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,9 @@ STATIC void read(msgpack_stream_t *s, void *buf, mp_uint_t size) {
6767
if (ret == 0) {
6868
mp_raise_msg(&mp_type_EOFError, NULL);
6969
}
70+
if (ret < size) {
71+
mp_raise_ValueError(translate("short read"));
72+
}
7073
}
7174

7275
STATIC uint8_t read1(msgpack_stream_t *s) {
@@ -92,7 +95,7 @@ STATIC uint32_t read4(msgpack_stream_t *s) {
9295
}
9396

9497
STATIC size_t read_size(msgpack_stream_t *s, uint8_t len_index) {
95-
size_t res;
98+
size_t res = 0;
9699
switch (len_index) {
97100
case 0: res = (size_t)read1(s); break;
98101
case 1: res = (size_t)read2(s); break;
@@ -181,9 +184,7 @@ STATIC void pack_int(msgpack_stream_t *s, int32_t x) {
181184

182185
STATIC void pack_bin(msgpack_stream_t *s, const uint8_t* data, size_t len) {
183186
write_size(s, 0xc4, len);
184-
for (size_t i=0; i<len; i++) {
185-
write1(s, data[i]);
186-
}
187+
if (len > 0) write(s, data, len);
187188
}
188189

189190
STATIC void pack_ext(msgpack_stream_t *s, int8_t code, const uint8_t* data, size_t len) {
@@ -201,9 +202,7 @@ STATIC void pack_ext(msgpack_stream_t *s, int8_t code, const uint8_t* data, siz
201202
write_size(s, 0xc7, len);
202203
}
203204
write1(s, code); // type byte
204-
for (size_t i=0; i<len; i++) {
205-
write1(s, data[i]);
206-
}
205+
if (len > 0) write(s, data, len);
207206
}
208207

209208
STATIC void pack_str(msgpack_stream_t *s, const char* str, size_t len) {
@@ -212,9 +211,7 @@ STATIC void pack_str(msgpack_stream_t *s, const char* str, size_t len) {
212211
} else {
213212
write_size(s, 0xd9, len);
214213
}
215-
for (size_t l=0; l<len; l++) {
216-
write1(s, str[l]);
217-
}
214+
if (len > 0) write(s, str, len);
218215
}
219216

220217
STATIC void pack_array(msgpack_stream_t *s, size_t len) {

0 commit comments

Comments
 (0)