From: Gustav Westling Date: Thu, 6 Jul 2017 18:30:26 +0000 (+0200) Subject: encoding/base32: make NoPadding Encoding's DecodedLen return exact size X-Git-Tag: go1.9rc1~94 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=d1340ee2e91a873d689cf11b74022f60476cd729;p=gostls13.git encoding/base32: make NoPadding Encoding's DecodedLen return exact size CL 47341 added support for decoding non-padded messages. But DecodedLen still returned a multiple of 5 for messages without a padding, even though it is possible to calculate the len exactly when using NoPadding. This change makes DecodedLen return the exact number of bytes that will be written. A change to the decoding logic is also made so that it can handle this case. DecodedLen now has the same behaviour as DecodedLen in encoding/base64. Fixes #20854 Change-Id: I729e0b1c0946c866fb675c854f835f366dd4b5a4 Reviewed-on: https://go-review.googlesource.com/47710 Reviewed-by: Brad Fitzpatrick Run-TryBot: Brad Fitzpatrick TryBot-Result: Gobot Gobot --- diff --git a/src/encoding/base32/base32.go b/src/encoding/base32/base32.go index 0270e8f4d4..bf341b54f3 100644 --- a/src/encoding/base32/base32.go +++ b/src/encoding/base32/base32.go @@ -341,7 +341,11 @@ func (enc *Encoding) decode(dst, src []byte) (n int, end bool, err error) { case 2: dst[0] = dbuf[0]<<3 | dbuf[1]>>2 } - dst = dst[5:] + + if !end { + dst = dst[5:] + } + switch dlen { case 2: n += 1 @@ -495,8 +499,7 @@ func NewDecoder(enc *Encoding, r io.Reader) io.Reader { // corresponding to n bytes of base32-encoded data. func (enc *Encoding) DecodedLen(n int) int { if enc.padChar == NoPadding { - // +6 represents the missing padding - return (n + 6) / 8 * 5 + return n * 5 / 8 } return n / 8 * 5 diff --git a/src/encoding/base32/base32_test.go b/src/encoding/base32/base32_test.go index 6fe292b476..56b229d15a 100644 --- a/src/encoding/base32/base32_test.go +++ b/src/encoding/base32/base32_test.go @@ -551,13 +551,13 @@ func TestEncodedDecodedLen(t *testing.T) { }}, {"NoPadding", StdEncoding.WithPadding(NoPadding), []test{ {0, 0, 0}, - {1, 2, 5}, - {2, 4, 5}, + {1, 2, 1}, + {2, 4, 2}, {5, 8, 5}, - {6, 10, 10}, - {7, 12, 10}, + {6, 10, 6}, + {7, 12, 7}, {10, 16, 10}, - {11, 18, 15}, + {11, 18, 11}, }}, } { t.Run(test.name, func(t *testing.T) {