Skip to content

Commit 2ddf6d7

Browse files
authored
Merge pull request #266 from ceshihao/fix_base64_with_whitespace
fix base64 contains newline case
2 parents 6c702ce + 6a6742f commit 2ddf6d7

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

misc_tests/jsoniter_array_test.go

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@ package misc_tests
33
import (
44
"bytes"
55
"encoding/json"
6+
"testing"
7+
68
"github.com/json-iterator/go"
79
"github.com/stretchr/testify/require"
8-
"testing"
910
)
1011

1112
func Test_empty_array(t *testing.T) {
@@ -168,6 +169,17 @@ func Test_decode_byte_array_from_base64(t *testing.T) {
168169
should.Equal([]byte{1, 2, 3}, data)
169170
}
170171

172+
func Test_decode_byte_array_from_base64_with_newlines(t *testing.T) {
173+
should := require.New(t)
174+
data := []byte{}
175+
err := json.Unmarshal([]byte(`"A\rQ\nID"`), &data)
176+
should.Nil(err)
177+
should.Equal([]byte{1, 2, 3}, data)
178+
err = jsoniter.Unmarshal([]byte(`"A\rQ\nID"`), &data)
179+
should.Nil(err)
180+
should.Equal([]byte{1, 2, 3}, data)
181+
}
182+
171183
func Test_decode_byte_array_from_array(t *testing.T) {
172184
should := require.New(t)
173185
data := []byte{}

reflect_native.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
package jsoniter
22

33
import (
4+
"bytes"
45
"encoding/base64"
5-
"github.com/modern-go/reflect2"
66
"reflect"
77
"strconv"
88
"unsafe"
9+
10+
"github.com/modern-go/reflect2"
911
)
1012

1113
const ptrSize = 32 << uintptr(^uintptr(0)>>63)
@@ -418,6 +420,10 @@ func (codec *base64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) {
418420
case StringValue:
419421
encoding := base64.StdEncoding
420422
src := iter.SkipAndReturnBytes()
423+
// New line characters (\r and \n) are ignored.
424+
// Refer to https://golang.org/pkg/encoding/base64/#Encoding.Decode
425+
src = bytes.Replace(src, []byte(`\r`), []byte{}, -1)
426+
src = bytes.Replace(src, []byte(`\n`), []byte{}, -1)
421427
src = src[1 : len(src)-1]
422428
decodedLen := encoding.DecodedLen(len(src))
423429
dst := make([]byte, decodedLen)

0 commit comments

Comments
 (0)