From: Joe Tsai Date: Thu, 10 Aug 2017 21:41:44 +0000 (-0700) Subject: archive/tar: simplify toASCII and parseString X-Git-Tag: go1.10beta1~1630 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=1d81251599fd1b8f9da888e10c1054c96d1e1fb1;p=gostls13.git archive/tar: simplify toASCII and parseString Use a simple []byte instead of bytes.Buffer to create a string. Use bytes.IndexByte instead of our own for loop. Change-Id: Ic4a1161d79017fd3af086a05c53d5f20a5f09326 Reviewed-on: https://go-review.googlesource.com/54752 Reviewed-by: Avelino Reviewed-by: Ian Lance Taylor Run-TryBot: Joe Tsai --- diff --git a/src/archive/tar/strconv.go b/src/archive/tar/strconv.go index 929770c25c..16d060c231 100644 --- a/src/archive/tar/strconv.go +++ b/src/archive/tar/strconv.go @@ -27,13 +27,13 @@ func toASCII(s string) string { if isASCII(s) { return s } - var buf bytes.Buffer + b := make([]byte, 0, len(s)) for _, c := range s { if c < 0x80 && c != 0x00 { - buf.WriteByte(byte(c)) + b = append(b, byte(c)) } } - return buf.String() + return string(b) } type parser struct { @@ -47,11 +47,10 @@ type formatter struct { // parseString parses bytes as a NUL-terminated C-style string. // If a NUL byte is not found then the whole slice is returned as a string. func (*parser) parseString(b []byte) string { - n := 0 - for n < len(b) && b[n] != 0 { - n++ + if i := bytes.IndexByte(b, 0); i >= 0 { + return string(b[:i]) } - return string(b[0:n]) + return string(b) } // Write s into b, terminating it with a NUL if there is room. @@ -75,7 +74,7 @@ func (f *formatter) formatString(b []byte, s string) { // that the first byte can only be either 0x80 or 0xff. Thus, the first byte is // equivalent to the sign bit in two's complement form. func fitsInBase256(n int, x int64) bool { - var binBits = uint(n-1) * 8 + binBits := uint(n-1) * 8 return n >= 9 || (x >= -1<