format.go 8.72 KB
Newer Older
1 2 3 4 5 6
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package fmt

7
import (
8 9
	"bytes"
	"strconv"
10
	"utf8"
11
)
12

13
const (
14
	nByte = 64
15

16 17
	ldigits = "0123456789abcdef"
	udigits = "0123456789ABCDEF"
18
)
19

20
const (
21 22
	signed   = true
	unsigned = false
23 24
)

25 26 27 28
var padZeroBytes = make([]byte, nByte)
var padSpaceBytes = make([]byte, nByte)

var newline = []byte{'\n'}
29 30

func init() {
31
	for i := 0; i < nByte; i++ {
32 33
		padZeroBytes[i] = '0'
		padSpaceBytes[i] = ' '
34 35
	}
}
36

37 38 39
// A fmt is the raw formatter used by Printf etc.
// It prints into a bytes.Buffer that must be set up externally.
type fmt struct {
40 41
	intbuf [nByte]byte
	buf    *bytes.Buffer
42
	// width, precision
43 44
	wid  int
	prec int
45
	// flags
46 47 48 49 50 51
	widPresent  bool
	precPresent bool
	minus       bool
	plus        bool
	sharp       bool
	space       bool
52
	unicode     bool
53
	zero        bool
54 55
}

56
func (f *fmt) clearflags() {
57 58 59 60 61 62 63 64
	f.wid = 0
	f.widPresent = false
	f.prec = 0
	f.precPresent = false
	f.minus = false
	f.plus = false
	f.sharp = false
	f.space = false
65
	f.unicode = false
66
	f.zero = false
67 68
}

69
func (f *fmt) init(buf *bytes.Buffer) {
70 71
	f.buf = buf
	f.clearflags()
72 73
}

74
// Compute left and right padding widths (only one will be non-zero).
75
func (f *fmt) computePadding(width int) (padding []byte, leftWidth, rightWidth int) {
76 77
	left := !f.minus
	w := f.wid
78
	if w < 0 {
79 80
		left = false
		w = -w
81
	}
82
	w -= width
83
	if w > 0 {
84
		if left && f.zero {
85
			return padZeroBytes, w, 0
86
		}
87 88 89 90 91 92 93
		if left {
			return padSpaceBytes, w, 0
		} else {
			// can't be zero padding on the right
			return padSpaceBytes, 0, w
		}
	}
94
	return
95 96 97
}

// Generate n bytes of padding.
98
func (f *fmt) writePadding(n int, padding []byte) {
99
	for n > 0 {
100
		m := n
101 102
		if m > nByte {
			m = nByte
103
		}
104 105
		f.buf.Write(padding[0:m])
		n -= m
106 107 108 109
	}
}

// Append b to f.buf, padded on left (w > 0) or right (w < 0 or f.minus)
Robert Hencke's avatar
Robert Hencke committed
110
// clear flags afterwards.
111
func (f *fmt) pad(b []byte) {
112 113
	var padding []byte
	var left, right int
114 115 116 117 118 119
	if f.widPresent && f.wid != 0 {
		padding, left, right = f.computePadding(len(b))
	}
	if left > 0 {
		f.writePadding(left, padding)
	}
120
	f.buf.Write(b)
121 122 123 124 125
	if right > 0 {
		f.writePadding(right, padding)
	}
}

126
// append s to buf, padded on left (w > 0) or right (w < 0 or f.minus).
Robert Hencke's avatar
Robert Hencke committed
127
// clear flags afterwards.
128
func (f *fmt) padString(s string) {
129 130
	var padding []byte
	var left, right int
131
	if f.widPresent && f.wid != 0 {
132
		padding, left, right = f.computePadding(utf8.RuneCountInString(s))
133 134 135 136
	}
	if left > 0 {
		f.writePadding(left, padding)
	}
137
	f.buf.WriteString(s)
138 139
	if right > 0 {
		f.writePadding(right, padding)
140 141 142
	}
}

143
func putint(buf []byte, base, val uint64, digits string) int {
144
	i := len(buf) - 1
145
	for val >= base {
146 147 148
		buf[i] = digits[val%base]
		i--
		val /= base
149
	}
150 151
	buf[i] = digits[val]
	return i - 1
152 153
}

154 155
// fmt_boolean formats a boolean.
func (f *fmt) fmt_boolean(v bool) {
Rob Pike's avatar
Rob Pike committed
156
	if v {
157
		f.padString("true")
Rob Pike's avatar
Rob Pike committed
158
	} else {
159
		f.padString("false")
Rob Pike's avatar
Rob Pike committed
160 161 162
	}
}

163 164 165
// integer; interprets prec but not wid.  Once formatted, result is sent to pad()
// and then flags are cleared.
func (f *fmt) integer(a int64, base uint64, signedness bool, digits string) {
166
	var buf []byte = f.intbuf[0:]
167
	negative := signedness == signed && a < 0
168
	if negative {
169
		a = -a
170
	}
171 172 173

	// two ways to ask for extra leading zero digits: %.3d or %03d.
	// apparently the first cancels the second.
174
	prec := 0
175
	if f.precPresent {
176 177
		prec = f.prec
		f.zero = false
178
	} else if f.zero && f.widPresent && !f.minus && f.wid > 0 {
179
		prec = f.wid
180
		if negative || f.plus || f.space {
181
			prec-- // leave room for sign
182 183
		}
	}
184

185 186 187 188
	// format a into buf, ending at buf[i].  (printing is easier right-to-left.)
	// a is made into unsigned ua.  we could make things
	// marginally faster by splitting the 32-bit case out into a separate
	// block but it's not worth the duplication, so ua has 64 bits.
189 190
	i := len(f.intbuf)
	ua := uint64(a)
191
	for ua >= base {
192 193 194
		i--
		buf[i] = digits[ua%base]
		ua /= base
195
	}
196 197
	i--
	buf[i] = digits[ua]
198
	for i > 0 && prec > nByte-i {
199 200
		i--
		buf[i] = '0'
201 202
	}

203
	// Various prefixes: 0x, -, etc.
Rob Pike's avatar
Rob Pike committed
204 205 206
	if f.sharp {
		switch base {
		case 8:
207
			if buf[i] != '0' {
208 209
				i--
				buf[i] = '0'
Rob Pike's avatar
Rob Pike committed
210 211
			}
		case 16:
212 213 214 215
			i--
			buf[i] = 'x' + digits[10] - 'a'
			i--
			buf[i] = '0'
Rob Pike's avatar
Rob Pike committed
216 217
		}
	}
218 219 220 221 222 223
	if f.unicode {
		i--
		buf[i] = '+'
		i--
		buf[i] = 'U'
	}
Rob Pike's avatar
Rob Pike committed
224

225
	if negative {
226 227
		i--
		buf[i] = '-'
228
	} else if f.plus {
229 230
		i--
		buf[i] = '+'
231
	} else if f.space {
232 233
		i--
		buf[i] = ' '
234
	}
235
	f.pad(buf[i:])
236 237
}

Rob Pike's avatar
Rob Pike committed
238 239 240 241 242 243 244 245 246 247
// truncate truncates the string to the specified precision, if present.
func (f *fmt) truncate(s string) string {
	if f.precPresent && f.prec < utf8.RuneCountInString(s) {
		n := f.prec
		for i := range s {
			if n == 0 {
				s = s[:i]
				break
			}
			n--
248 249
		}
	}
Rob Pike's avatar
Rob Pike committed
250 251 252 253 254 255
	return s
}

// fmt_s formats a string.
func (f *fmt) fmt_s(s string) {
	s = f.truncate(s)
256
	f.padString(s)
257 258
}

259 260
// fmt_sx formats a string as a hexadecimal encoding of its bytes.
func (f *fmt) fmt_sx(s string) {
261
	t := ""
262
	for i := 0; i < len(s); i++ {
263
		if i > 0 && f.space {
264
			t += " "
265
		}
266 267 268
		v := s[i]
		t += string(ldigits[v>>4])
		t += string(ldigits[v&0xF])
269
	}
270
	f.padString(t)
271 272
}

273 274
// fmt_sX formats a string as an uppercase hexadecimal encoding of its bytes.
func (f *fmt) fmt_sX(s string) {
275
	t := ""
276
	for i := 0; i < len(s); i++ {
Rob Pike's avatar
Rob Pike committed
277 278 279
		if i > 0 && f.space {
			t += " "
		}
280 281 282
		v := s[i]
		t += string(udigits[v>>4])
		t += string(udigits[v&0xF])
283
	}
284
	f.padString(t)
285 286
}

287 288
// fmt_q formats a string as a double-quoted, escaped Go string constant.
func (f *fmt) fmt_q(s string) {
Rob Pike's avatar
Rob Pike committed
289
	s = f.truncate(s)
290
	var quoted string
291
	if f.sharp && strconv.CanBackquote(s) {
292
		quoted = "`" + s + "`"
293
	} else {
294
		quoted = strconv.Quote(s)
295
	}
296
	f.padString(quoted)
297 298 299 300 301 302 303
}

// fmt_qc formats the integer as a single-quoted, escaped Go character constant.
// If the character is not valid Unicode, it will print '\ufffd'.
func (f *fmt) fmt_qc(c int64) {
	quoted := strconv.QuoteRune(int(c))
	f.padString(quoted)
304 305
}

306
// floating-point
307

308
func doPrec(f *fmt, def int) int {
309
	if f.precPresent {
310
		return f.prec
Rob Pike's avatar
Rob Pike committed
311
	}
312
	return def
Rob Pike's avatar
Rob Pike committed
313 314
}

315
// Add a plus sign or space to the floating-point string representation if missing and required.
316
func (f *fmt) plusSpace(s string) {
317 318 319 320 321 322 323
	if s[0] != '-' {
		if f.plus {
			s = "+" + s
		} else if f.space {
			s = " " + s
		}
	}
324
	f.padString(s)
325 326
}

327
// fmt_e64 formats a float64 in the form -1.23e+12.
328
func (f *fmt) fmt_e64(v float64) { f.plusSpace(strconv.Ftoa64(v, 'e', doPrec(f, 6))) }
329

330
// fmt_E64 formats a float64 in the form -1.23E+12.
331
func (f *fmt) fmt_E64(v float64) { f.plusSpace(strconv.Ftoa64(v, 'E', doPrec(f, 6))) }
Russ Cox's avatar
Russ Cox committed
332

333
// fmt_f64 formats a float64 in the form -1.23.
334
func (f *fmt) fmt_f64(v float64) { f.plusSpace(strconv.Ftoa64(v, 'f', doPrec(f, 6))) }
335

336
// fmt_g64 formats a float64 in the 'f' or 'e' form according to size.
337
func (f *fmt) fmt_g64(v float64) { f.plusSpace(strconv.Ftoa64(v, 'g', doPrec(f, -1))) }
338

339
// fmt_g64 formats a float64 in the 'f' or 'E' form according to size.
340
func (f *fmt) fmt_G64(v float64) { f.plusSpace(strconv.Ftoa64(v, 'G', doPrec(f, -1))) }
Russ Cox's avatar
Russ Cox committed
341

342
// fmt_fb64 formats a float64 in the form -123p3 (exponent is power of 2).
343
func (f *fmt) fmt_fb64(v float64) { f.plusSpace(strconv.Ftoa64(v, 'b', 0)) }
344

345 346 347
// float32
// cannot defer to float64 versions
// because it will get rounding wrong in corner cases.
Rob Pike's avatar
Rob Pike committed
348

349
// fmt_e32 formats a float32 in the form -1.23e+12.
350
func (f *fmt) fmt_e32(v float32) { f.plusSpace(strconv.Ftoa32(v, 'e', doPrec(f, 6))) }
351

352
// fmt_E32 formats a float32 in the form -1.23E+12.
353
func (f *fmt) fmt_E32(v float32) { f.plusSpace(strconv.Ftoa32(v, 'E', doPrec(f, 6))) }
Russ Cox's avatar
Russ Cox committed
354

355
// fmt_f32 formats a float32 in the form -1.23.
356
func (f *fmt) fmt_f32(v float32) { f.plusSpace(strconv.Ftoa32(v, 'f', doPrec(f, 6))) }
357

358
// fmt_g32 formats a float32 in the 'f' or 'e' form according to size.
359
func (f *fmt) fmt_g32(v float32) { f.plusSpace(strconv.Ftoa32(v, 'g', doPrec(f, -1))) }
360

361
// fmt_G32 formats a float32 in the 'f' or 'E' form according to size.
362
func (f *fmt) fmt_G32(v float32) { f.plusSpace(strconv.Ftoa32(v, 'G', doPrec(f, -1))) }
Russ Cox's avatar
Russ Cox committed
363

364
// fmt_fb32 formats a float32 in the form -123p3 (exponent is power of 2).
365
func (f *fmt) fmt_fb32(v float32) { f.padString(strconv.Ftoa32(v, 'b', 0)) }
366

367 368
// fmt_c64 formats a complex64 according to the verb.
func (f *fmt) fmt_c64(v complex64, verb int) {
Ken Thompson's avatar
PTAL  
Ken Thompson committed
369 370 371
	f.buf.WriteByte('(')
	r := real(v)
	for i := 0; ; i++ {
372
		switch verb {
Ken Thompson's avatar
PTAL  
Ken Thompson committed
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
		case 'e':
			f.fmt_e32(r)
		case 'E':
			f.fmt_E32(r)
		case 'f':
			f.fmt_f32(r)
		case 'g':
			f.fmt_g32(r)
		case 'G':
			f.fmt_G32(r)
		}
		if i != 0 {
			break
		}
		f.plus = true
		r = imag(v)
	}
	f.buf.Write(irparenBytes)
}

393 394
// fmt_c128 formats a complex128 according to the verb.
func (f *fmt) fmt_c128(v complex128, verb int) {
Ken Thompson's avatar
PTAL  
Ken Thompson committed
395 396 397
	f.buf.WriteByte('(')
	r := real(v)
	for i := 0; ; i++ {
398
		switch verb {
Ken Thompson's avatar
PTAL  
Ken Thompson committed
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
		case 'e':
			f.fmt_e64(r)
		case 'E':
			f.fmt_E64(r)
		case 'f':
			f.fmt_f64(r)
		case 'g':
			f.fmt_g64(r)
		case 'G':
			f.fmt_G64(r)
		}
		if i != 0 {
			break
		}
		f.plus = true
		r = imag(v)
	}
	f.buf.Write(irparenBytes)
}