From 304c9ab4e25d446cf29a38b0cf2bf82a84d6a6ac Mon Sep 17 00:00:00 2001 From: Masaaki Goshima Date: Thu, 7 May 2020 14:21:29 +0900 Subject: [PATCH] Fix decoder for int and string type --- decode_int.go | 32 ++++++++++++++++++++++++-------- decode_string.go | 5 +++-- 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/decode_int.go b/decode_int.go index 07e6276..6a50e4d 100644 --- a/decode_int.go +++ b/decode_int.go @@ -38,26 +38,42 @@ func (d *intDecoder) parseInt(b []byte) int64 { return sum } +var ( + numTable = [256]bool{ + '0': true, + '1': true, + '2': true, + '3': true, + '4': true, + '5': true, + '6': true, + '7': true, + '8': true, + '9': true, + } +) + func (d *intDecoder) decodeByte(buf []byte, cursor int) ([]byte, int, error) { - buflen := len(buf) - for ; cursor < buflen; cursor++ { + for { switch buf[cursor] { case ' ', '\n', '\t', '\r': + cursor++ continue case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': start := cursor cursor++ - for ; cursor < buflen; cursor++ { - tk := int(buf[cursor]) - if int('0') <= tk && tk <= int('9') { - continue - } - break + LOOP: + if numTable[buf[cursor]] { + cursor++ + goto LOOP } num := buf[start:cursor] return num, cursor, nil + default: + goto ERROR } } +ERROR: return nil, 0, errors.New("unexpected error number") } diff --git a/decode_string.go b/decode_string.go index d2d4a9e..701e00e 100644 --- a/decode_string.go +++ b/decode_string.go @@ -25,8 +25,6 @@ func (d *stringDecoder) decode(buf []byte, cursor int, p uintptr) (int, error) { func (d *stringDecoder) decodeByte(buf []byte, cursor int) ([]byte, int, error) { for { switch buf[cursor] { - case '\000': - return nil, 0, errors.New("unexpected error key delimiter") case ' ', '\n', '\t', '\r': cursor++ case '"': @@ -62,7 +60,10 @@ func (d *stringDecoder) decodeByte(buf []byte, cursor int) ([]byte, int, error) } cursor += 5 return []byte{'n', 'u', 'l', 'l'}, cursor, nil + default: + goto ERROR } } +ERROR: return nil, 0, errors.New("unexpected error key delimiter") }