summaryrefslogtreecommitdiff
path: root/src/fmt/format.go
diff options
context:
space:
mode:
Diffstat (limited to 'src/fmt/format.go')
-rw-r--r--src/fmt/format.go52
1 files changed, 45 insertions, 7 deletions
diff --git a/src/fmt/format.go b/src/fmt/format.go
index 8aeffd7b2..355b73262 100644
--- a/src/fmt/format.go
+++ b/src/fmt/format.go
@@ -49,9 +49,14 @@ type fmt struct {
plus bool
sharp bool
space bool
- unicode bool
- uniQuote bool // Use 'x'= prefix for %U if printable.
- zero bool
+ // For the format %#v, we set this flag and
+ // clear the plus flag, since it is in effect
+ // a different, flagless format set at the top level.
+ // TODO: plusV could use this too.
+ sharpV bool
+ unicode bool
+ uniQuote bool // Use 'x'= prefix for %U if printable.
+ zero bool
}
func (f *fmt) clearflags() {
@@ -63,6 +68,7 @@ func (f *fmt) clearflags() {
f.plus = false
f.sharp = false
f.space = false
+ f.sharpV = false
f.unicode = false
f.uniQuote = false
f.zero = false
@@ -199,10 +205,36 @@ func (f *fmt) integer(a int64, base uint64, signedness bool, digits string) {
// block but it's not worth the duplication, so ua has 64 bits.
i := len(buf)
ua := uint64(a)
- for ua >= base {
- i--
- buf[i] = digits[ua%base]
- ua /= base
+ // use constants for the division and modulo for more efficient code.
+ // switch cases ordered by popularity.
+ switch base {
+ case 10:
+ for ua >= 10 {
+ i--
+ next := ua / 10
+ buf[i] = byte('0' + ua - next*10)
+ ua = next
+ }
+ case 16:
+ for ua >= 16 {
+ i--
+ buf[i] = digits[ua&0xF]
+ ua >>= 4
+ }
+ case 8:
+ for ua >= 8 {
+ i--
+ buf[i] = byte('0' + ua&7)
+ ua >>= 3
+ }
+ case 2:
+ for ua >= 2 {
+ i--
+ buf[i] = byte('0' + ua&1)
+ ua >>= 1
+ }
+ default:
+ panic("fmt: unknown base; can't happen")
}
i--
buf[i] = digits[ua]
@@ -314,11 +346,17 @@ func (f *fmt) fmt_sbx(s string, b []byte, digits string) {
// fmt_sx formats a string as a hexadecimal encoding of its bytes.
func (f *fmt) fmt_sx(s, digits string) {
+ if f.precPresent && f.prec < len(s) {
+ s = s[:f.prec]
+ }
f.fmt_sbx(s, nil, digits)
}
// fmt_bx formats a byte slice as a hexadecimal encoding of its bytes.
func (f *fmt) fmt_bx(b []byte, digits string) {
+ if f.precPresent && f.prec < len(b) {
+ b = b[:f.prec]
+ }
f.fmt_sbx("", b, digits)
}