Skip to content

Commit 7b7737d

Browse files
committed
make stripNewlines always copy while filtering newlines
1 parent 3a757e6 commit 7b7737d

File tree

1 file changed

+14
-16
lines changed

1 file changed

+14
-16
lines changed

src/encoding/base32/base32.go

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -364,19 +364,17 @@ func (enc *Encoding) decode(dst, src []byte) (n int, end bool, err error) {
364364
// New line characters (\r and \n) are ignored.
365365
func (enc *Encoding) Decode(dst, src []byte) (n int, err error) {
366366
buf := make([]byte, len(src))
367-
copy(buf, src)
368-
l := stripNewlines(buf)
367+
l := stripNewlines(buf, src)
369368
n, _, err = enc.decode(dst, buf[:l])
370369
return
371370
}
372371

373372
// DecodeString returns the bytes represented by the base32 string s.
374373
func (enc *Encoding) DecodeString(s string) ([]byte, error) {
375-
dbuf := make([]byte, enc.DecodedLen(len(s)))
376-
src := []byte(s)
377-
l := stripNewlines(src)
378-
n, _, err := enc.decode(dbuf, src[:l])
379-
return dbuf[:n], err
374+
buf := []byte(s)
375+
l := stripNewlines(buf, buf)
376+
n, _, err := enc.decode(buf, buf[:l])
377+
return buf[:n], err
380378
}
381379

382380
type decoder struct {
@@ -492,24 +490,24 @@ type newlineFilteringReader struct {
492490
}
493491

494492
// stripNewlines removes newline characters and returns the number
495-
// of non-newline characters moved to the beginning of p.
496-
func stripNewlines(p []byte) int {
493+
// of non-newline characters copied to dst.
494+
func stripNewlines(dst, src []byte) int {
497495
offset := 0
498-
for i, b := range p {
499-
if b != '\r' && b != '\n' {
500-
if i > offset {
501-
p[offset] = b
502-
}
503-
offset++
496+
for _, b := range src {
497+
if b == '\r' || b == '\n' {
498+
continue
504499
}
500+
dst[offset] = b
501+
offset++
505502
}
506503
return offset
507504
}
508505

509506
func (r *newlineFilteringReader) Read(p []byte) (int, error) {
510507
n, err := r.wrapped.Read(p)
511508
for n > 0 {
512-
offset := stripNewlines(p[:n])
509+
s := p[0:n]
510+
offset := stripNewlines(s, s)
513511
if err != nil || offset > 0 {
514512
return offset, err
515513
}

0 commit comments

Comments
 (0)