Skip to content

Commit

Permalink
encoding/base64: correct DecodedLen overestimate for unpadded encodings
Browse files Browse the repository at this point in the history
While we're at it, add tests for EncodedLen and DecodedLen.

Fixes #14803.

Change-Id: I200c72cf11c51669b8d9f70c6e57ece359f7ae61
Reviewed-on: https://go-review.googlesource.com/20649
Reviewed-by: Ian Lance Taylor <iant@golang.org>
Run-TryBot: Ian Lance Taylor <iant@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
  • Loading branch information
cespare authored and ianlancetaylor committed Mar 15, 2016
1 parent 95c6c5f commit 87151c8
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/encoding/base64/base64.go
Expand Up @@ -459,7 +459,7 @@ func NewDecoder(enc *Encoding, r io.Reader) io.Reader {
func (enc *Encoding) DecodedLen(n int) int {
if enc.padChar == NoPadding {
// Unpadded data may end with partial block of 2-3 characters.
return (n*6 + 7) / 8
return n * 6 / 8
}
// Padded base64 should always be a multiple of 4 characters in length.
return n / 4 * 3
Expand Down
45 changes: 45 additions & 0 deletions src/encoding/base64/base64_test.go
Expand Up @@ -234,6 +234,51 @@ func TestDecodeCorrupt(t *testing.T) {
}
}

func TestEncodedLen(t *testing.T) {
for _, tt := range []struct {
enc *Encoding
n int
want int
}{
{RawStdEncoding, 0, 0},
{RawStdEncoding, 1, 2},
{RawStdEncoding, 2, 3},
{RawStdEncoding, 3, 4},
{RawStdEncoding, 7, 10},
{StdEncoding, 0, 0},
{StdEncoding, 1, 4},
{StdEncoding, 2, 4},
{StdEncoding, 3, 4},
{StdEncoding, 4, 8},
{StdEncoding, 7, 12},
} {
if got := tt.enc.EncodedLen(tt.n); got != tt.want {
t.Errorf("EncodedLen(%d): got %d, want %d", tt.n, got, tt.want)
}
}
}

func TestDecodedLen(t *testing.T) {
for _, tt := range []struct {
enc *Encoding
n int
want int
}{
{RawStdEncoding, 0, 0},
{RawStdEncoding, 2, 1},
{RawStdEncoding, 3, 2},
{RawStdEncoding, 4, 3},
{RawStdEncoding, 10, 7},
{StdEncoding, 0, 0},
{StdEncoding, 4, 3},
{StdEncoding, 8, 6},
} {
if got := tt.enc.DecodedLen(tt.n); got != tt.want {
t.Errorf("DecodedLen(%d): got %d, want %d", tt.n, got, tt.want)
}
}
}

func TestBig(t *testing.T) {
n := 3*1000 + 1
raw := make([]byte, n)
Expand Down

0 comments on commit 87151c8

Please sign in to comment.