From 57058327c837fbfe64f2c4e4422b82a25c123eda Mon Sep 17 00:00:00 2001 From: Rob Pike Date: Mon, 13 Apr 2015 12:41:11 -0700 Subject: [PATCH] fmt: empty byte slices should print nothing in hex The documentation is clear that formats like %02x applied to a byte slice are per-element, so the result should be nothing if the slice is empty. It's not, because the top-level padding routine is called. It shouldn't be: the loop does the padding for us. Fixes #10430. Change-Id: I04ea0e804c0f2e70fff3701e5bf22acc90e890da Reviewed-on: https://go-review.googlesource.com/8864 Reviewed-by: Ian Lance Taylor --- src/fmt/fmt_test.go | 8 ++++++++ src/fmt/format.go | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/fmt/fmt_test.go b/src/fmt/fmt_test.go index c14bd2f45c..146977ace1 100644 --- a/src/fmt/fmt_test.go +++ b/src/fmt/fmt_test.go @@ -394,6 +394,8 @@ var fmtTests = []struct { {"%v", &slice, "&[1 2 3 4 5]"}, {"%v", &islice, "&[1 hello 2.5 ]"}, {"%v", &bslice, "&[1 2 3 4 5]"}, + {"%v", []byte{1}, "[1]"}, + {"%v", []byte{}, "[]"}, // complexes with %v {"%v", 1 + 2i, "(1+2i)"}, @@ -447,6 +449,12 @@ var fmtTests = []struct { {"%d", []int{1, 2, 15}, `[1 2 15]`}, {"%d", []byte{1, 2, 15}, `[1 2 15]`}, {"%q", []string{"a", "b"}, `["a" "b"]`}, + {"% 02x", []byte{1}, "01"}, + {"% 02x", []byte{1, 2, 3}, "01 02 03"}, + // Special care for empty slices. + {"%x", []byte{}, ""}, + {"%02x", []byte{}, ""}, + {"% 02x", []byte{}, ""}, // renamings {"%v", renamedBool(true), "true"}, diff --git a/src/fmt/format.go b/src/fmt/format.go index 4d97d1443e..86673aba6a 100644 --- a/src/fmt/format.go +++ b/src/fmt/format.go @@ -335,7 +335,7 @@ func (f *fmt) fmt_sbx(s string, b []byte, digits string) { } buf = append(buf, digits[c>>4], digits[c&0xF]) } - f.pad(buf) + f.buf.Write(buf) } // fmt_sx formats a string as a hexadecimal encoding of its bytes.