Skip to content

Commit 11804c3

Browse files
committed
fix bug when using big yaml on the scanner
1 parent 4bdb72e commit 11804c3

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

staging/src/k8s.io/apimachinery/pkg/util/yaml/decoder.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,10 @@ type YAMLDecoder struct {
9292
// the caller in framing the chunk.
9393
func NewDocumentDecoder(r io.ReadCloser) io.ReadCloser {
9494
scanner := bufio.NewScanner(r)
95+
// the size of initial allocation for buffer 4k
96+
buf := make([]byte, 4*1024)
97+
// the maximum size used to buffer a token 5M
98+
scanner.Buffer(buf, 5*1024*1024)
9599
scanner.Split(splitYAMLDocument)
96100
return &YAMLDecoder{
97101
r: r,

staging/src/k8s.io/apimachinery/pkg/util/yaml/decoder_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,33 @@ stuff: 1
5454
}
5555
}
5656

57+
func TestBigYAML(t *testing.T) {
58+
d := `
59+
stuff: 1
60+
`
61+
maxLen := 5 * 1024 * 1024
62+
bufferLen := 4 * 1024
63+
// maxLen 5 M
64+
dd := strings.Repeat(d, 512*1024)
65+
r := NewDocumentDecoder(ioutil.NopCloser(bytes.NewReader([]byte(dd[:maxLen-1]))))
66+
b := make([]byte, bufferLen)
67+
n, err := r.Read(b)
68+
if err != io.ErrShortBuffer {
69+
t.Fatalf("expected ErrShortBuffer: %d / %v", n, err)
70+
}
71+
b = make([]byte, maxLen)
72+
n, err = r.Read(b)
73+
if err != nil {
74+
t.Fatalf("expected nil: %d / %v", n, err)
75+
}
76+
r = NewDocumentDecoder(ioutil.NopCloser(bytes.NewReader([]byte(dd))))
77+
b = make([]byte, maxLen)
78+
n, err = r.Read(b)
79+
if err != bufio.ErrTooLong {
80+
t.Fatalf("bufio.Scanner: token too long: %d / %v", n, err)
81+
}
82+
}
83+
5784
func TestYAMLDecoderCallsAfterErrShortBufferRestOfFrame(t *testing.T) {
5885
d := `---
5986
stuff: 1

0 commit comments

Comments
 (0)