Skip to content

Commit 7e26440

Browse files
committed
reduce allocation in error preview by limiting buffer size (close #122)
1 parent 8f183bb commit 7e26440

File tree

1 file changed

+45
-1
lines changed

1 file changed

+45
-1
lines changed

error.go

+45-1
Original file line numberDiff line numberDiff line change
@@ -347,11 +347,55 @@ func typeof(v interface{}) (s string) {
347347
}
348348
}
349349

350+
type limitWriter struct {
351+
buf []byte
352+
off int
353+
}
354+
355+
func (w *limitWriter) Write(bs []byte) (int, error) {
356+
n := copy(w.buf[w.off:], bs)
357+
if w.off += n; w.off == len(w.buf) {
358+
panic(true)
359+
}
360+
return n, nil
361+
}
362+
363+
func (w *limitWriter) WriteByte(b byte) error {
364+
w.buf[w.off] = b
365+
w.off++
366+
if w.off == len(w.buf) {
367+
panic(true)
368+
}
369+
return nil
370+
}
371+
372+
func (w *limitWriter) WriteString(s string) (int, error) {
373+
n := copy(w.buf[w.off:], s)
374+
if w.off += n; w.off == len(w.buf) {
375+
panic(true)
376+
}
377+
return n, nil
378+
}
379+
380+
func (w *limitWriter) String() string {
381+
return string(w.buf[:w.off])
382+
}
383+
384+
func jsonLimitedMarshal(v interface{}, n int) (s string) {
385+
w := &limitWriter{buf: make([]byte, n)}
386+
defer func() {
387+
recover()
388+
s = w.String()
389+
}()
390+
(&encoder{w: w}).encode(v)
391+
return
392+
}
393+
350394
func preview(v interface{}) string {
351395
if v == nil {
352396
return ""
353397
}
354-
s := jsonMarshal(v)
398+
s := jsonLimitedMarshal(v, 32)
355399
if l := 30; len(s) > l {
356400
var trailing string
357401
switch v.(type) {

0 commit comments

Comments
 (0)