Beispiel #1
0
// Format makes Unit satisfy the fmt.Formatter interface. The unit is formatted
// with dimensions appended. If the power if the dimension is not zero or one,
// symbol^power is appended, if the power is one, just the symbol is appended
// and if the power is zero, nothing is appended. Dimensions are appended
// in order by symbol name with positive powers ahead of negative powers.
func (u *Unit) Format(fs fmt.State, c rune) {
	if u == nil {
		fmt.Fprint(fs, "<nil>")
	}
	switch c {
	case 'v':
		if fs.Flag('#') {
			fmt.Fprintf(fs, "&%#v", *u)
			return
		}
		fallthrough
	case 'e', 'E', 'f', 'F', 'g', 'G':
		p, pOk := fs.Precision()
		w, wOk := fs.Width()
		switch {
		case pOk && wOk:
			fmt.Fprintf(fs, "%*.*"+string(c), w, p, u.value)
		case pOk:
			fmt.Fprintf(fs, "%.*"+string(c), p, u.value)
		case wOk:
			fmt.Fprintf(fs, "%*"+string(c), w, u.value)
		default:
			fmt.Fprintf(fs, "%"+string(c), u.value)
		}
	default:
		fmt.Fprintf(fs, "%%!%c(*Unit=%g)", c, u)
		return
	}
	if u.formatted == "" && len(u.dimensions) > 0 {
		u.formatted = u.dimensions.String()
	}
	fmt.Fprintf(fs, " %s", u.formatted)
}
Beispiel #2
0
// Format may call Sprint(f) or Fprint(f) etc. to generate its output.
func (e *goof) Format(f fmt.State, c rune) {
	s := e.getMessage(e.includeFieldsInFormat)
	fs := &bytes.Buffer{}
	fs.WriteRune('%')
	if f.Flag('+') {
		fs.WriteRune('+')
	}
	if f.Flag('-') {
		fs.WriteRune('-')
	}
	if f.Flag('#') {
		fs.WriteRune('#')
	}
	if f.Flag(' ') {
		fs.WriteRune(' ')
	}
	if f.Flag('0') {
		fs.WriteRune('0')
	}
	if w, ok := f.Width(); ok {
		fs.WriteString(fmt.Sprintf("%d", w))
	}
	if p, ok := f.Precision(); ok {
		fs.WriteString(fmt.Sprintf("%d", p))
	}
	fs.WriteRune(c)
	fmt.Fprintf(f, fs.String(), s)
}
Beispiel #3
0
func (m Mass) Format(fs fmt.State, c rune) {
	switch c {
	case 'v':
		if fs.Flag('#') {
			fmt.Fprintf(fs, "%T(%v)", m, float64(m))
			return
		}
		fallthrough
	case 'e', 'E', 'f', 'F', 'g', 'G':
		p, pOk := fs.Precision()
		w, wOk := fs.Width()
		switch {
		case pOk && wOk:
			fmt.Fprintf(fs, "%*.*"+string(c), w, p, float64(m))
		case pOk:
			fmt.Fprintf(fs, "%.*"+string(c), p, float64(m))
		case wOk:
			fmt.Fprintf(fs, "%*"+string(c), w, float64(m))
		default:
			fmt.Fprintf(fs, "%"+string(c), float64(m))
		}
		fmt.Fprint(fs, " kg")
	default:
		fmt.Fprintf(fs, "%%!%c(%T=%g kg)", c, m, float64(m))
		return
	}
}
Beispiel #4
0
func (st *stacktrace) Format(f fmt.State, c rune) {
	var text string
	if f.Flag('+') && !f.Flag('#') && c == 's' { // "%+s"
		text = formatFull(st)
	} else if f.Flag('#') && !f.Flag('+') && c == 's' { // "%#s"
		text = formatBrief(st)
	} else {
		text = map[Format]func(*stacktrace) string{
			FormatFull:  formatFull,
			FormatBrief: formatBrief,
		}[DefaultFormat](st)
	}

	formatString := "%"
	// keep the flags recognized by fmt package
	for _, flag := range "-+# 0" {
		if f.Flag(int(flag)) {
			formatString += string(flag)
		}
	}
	if width, has := f.Width(); has {
		formatString += fmt.Sprint(width)
	}
	if precision, has := f.Precision(); has {
		formatString += "."
		formatString += fmt.Sprint(precision)
	}
	formatString += string(c)
	fmt.Fprintf(f, formatString, text)
}
Beispiel #5
0
func (af *ansiFormatter) Format(f fmt.State, c rune) {
	// reconstruct the format string in bf
	bf := new(bytes.Buffer)
	bf.WriteByte('%')
	for _, x := range []byte{'-', '+', '#', ' ', '0'} {
		if f.Flag(int(x)) {
			bf.WriteByte(x)
		}
	}
	if w, ok := f.Width(); ok {
		fmt.Fprint(bf, w)
	}
	if p, ok := f.Precision(); ok {
		fmt.Fprintf(bf, ".%d", p)
	}
	bf.WriteRune(c)
	format := bf.String()

	if len(af.codes) == 0 {
		fmt.Fprintf(f, format, af.value)
		return
	}

	fmt.Fprintf(f, "\x1b[%d", af.codes[0])
	for _, code := range af.codes[1:] {
		fmt.Fprintf(f, ";%d", code)
	}
	f.Write([]byte{'m'})
	fmt.Fprintf(f, format, af.value)
	fmt.Fprint(f, "\x1b[0m")
}
Beispiel #6
0
func (e escapable) Format(f fmt.State, c rune) {
	s := "%"
	for i := 0; i < 128; i++ {
		if f.Flag(i) {
			s += string(i)
		}
	}
	if w, ok := f.Width(); ok {
		s += fmt.Sprintf("%d", w)
	}
	if p, ok := f.Precision(); ok {
		s += fmt.Sprintf(".%d", p)
	}
	// If we have an uppercase format char and a slice, format each slice
	// element
	if unicode.IsUpper(c) && reflect.TypeOf(e.x).Kind() == reflect.Slice {
		s += strings.ToLower(string(c))
		v := reflect.ValueOf(e.x)
		for i := 0; i < v.Len(); i++ {
			formatted := fmt.Sprintf(s, v.Index(i))
			io.WriteString(f, ReadableEscapeArg(formatted))
			if i+1 != v.Len() {
				io.WriteString(f, " ")
			}
		}
		return
	}
	s += string(c)
	formatted := fmt.Sprintf(s, e.x)
	io.WriteString(f, ReadableEscapeArg(formatted))
}
Beispiel #7
0
// TODO: Implement left/right align
func (b ByteSize) Format(f fmt.State, c rune) {
	var decimal bool
	switch c {
	case 'd':
		decimal = true
	case 'b':
		decimal = false
	case 'v':
		fmt.Fprintf(f, "%s", b.String())
		return
	default:
		fmt.Fprintf(f, "%%!%c(ByteSize=%s)", c, b.String())
		return
	}

	unit, divisor := b.UnitDivisor(decimal)
	fmtstring := "%"

	if w, ok := f.Width(); ok {
		fmtstring += fmt.Sprintf("%d", w-len(unit)-1)
	}
	if p, ok := f.Precision(); ok {
		fmtstring += fmt.Sprintf(".%d", p)
	}
	fmtstring += "f %s"

	fmt.Fprintf(f, fmtstring, float64(b)/float64(divisor), unit)
}
Beispiel #8
0
func format(b Bed, fs fmt.State, c rune) {
	bv := reflect.ValueOf(b)
	if bv.IsNil() {
		fmt.Fprint(fs, "<nil>")
		return
	}
	bv = bv.Elem()
	switch c {
	case 'v':
		if fs.Flag('#') {
			fmt.Fprintf(fs, "&%#v", bv.Interface())
			return
		}
		fallthrough
	case 's':
		width, _ := fs.Width()
		if !b.canBed(width) {
			fmt.Fprintf(fs, "%%!(BADWIDTH)%T", b)
			return
		}
		if width == 0 {
			width = bv.NumField()
		}
		for i := 0; i < width; i++ {
			f := bv.Field(i).Interface()
			if i >= rgbField {
				switch i {
				case rgbField:
					rv := reflect.ValueOf(f)
					if reflect.DeepEqual(rv.Interface(), color.RGBA{}) {
						fs.Write([]byte{'0'})
					} else {
						fmt.Fprintf(fs, "%d,%d,%d",
							rv.Field(0).Interface(), rv.Field(1).Interface(), rv.Field(2).Interface())
					}
				case blockCountField:
					fmt.Fprint(fs, f)
				case blockSizesField, blockStartsField:
					av := reflect.ValueOf(f)
					l := av.Len()
					for j := 0; j < l; j++ {
						fmt.Fprint(fs, av.Index(j).Interface())
						if j < l-1 {
							fs.Write([]byte{','})
						}
					}
				}
			} else {
				fmt.Fprint(fs, f)
			}
			if i < width-1 {
				fs.Write([]byte{'\t'})
			}
		}
	default:
		fmt.Fprintf(fs, "%%!%c(%T=%3s)", c, b, b)
	}
}
Beispiel #9
0
// We implement fmt.Formatter interface just so we can left-align the cards.
func (s Suit) Format(f fmt.State, c int) {
	x := stringTable[s]
	f.Write([]byte(x))
	if w, ok := f.Width(); ok {
		for i := 0; i < w-len(x); i++ {
			f.Write([]byte{' '})
		}
	}
}
Beispiel #10
0
func (fo formatter) passThrough(f fmt.State, c rune) {
	s := "%"
	for i := 0; i < 128; i++ {
		if f.Flag(i) {
			s += string(i)
		}
	}
	if w, ok := f.Width(); ok {
		s += fmt.Sprintf("%d", w)
	}
	if p, ok := f.Precision(); ok {
		s += fmt.Sprintf(".%d", p)
	}
	s += string(c)
	fmt.Fprintf(f, s, fo.x)
}
Beispiel #11
0
func (r Range) Format(f fmt.State, c int) {
	i := byte(0)
	for ; i < r.Min; i++ {
		f.Write([]byte{'X'})
	}
	for ; float64(i)+0.5 < r.Mean; i++ {
		f.Write([]byte{'x'})
	}
	for ; i < r.Max; i++ {
		f.Write([]byte{'.'})
	}
	if w, ok := f.Width(); ok {
		for ; i < byte(w); i++ {
			f.Write([]byte{' '})
		}
	}
}
Beispiel #12
0
func (e escapable) Format(f fmt.State, c rune) {
	s := "%"
	for i := 0; i < 128; i++ {
		if f.Flag(i) {
			s += string(i)
		}
	}
	if w, ok := f.Width(); ok {
		s += fmt.Sprintf("%d", w)
	}
	if p, ok := f.Precision(); ok {
		s += fmt.Sprintf(".%d", p)
	}
	s += string(c)
	formatted := fmt.Sprintf(s, e.x)
	io.WriteString(f, ReadableEscapeArg(formatted))
}
Beispiel #13
0
func defaultFormat(v interface{}, f fmt.State, c rune) {
	buf := make([]string, 0, 10)
	buf = append(buf, "%")
	for i := 0; i < 128; i++ {
		if f.Flag(i) {
			buf = append(buf, string(i))
		}
	}

	if w, ok := f.Width(); ok {
		buf = append(buf, strconv.Itoa(w))
	}
	if p, ok := f.Precision(); ok {
		buf = append(buf, "."+strconv.Itoa(p))
	}
	buf = append(buf, string(c))
	format := strings.Join(buf, "")
	fmt.Fprintf(f, format, v)
}
Beispiel #14
0
func formatString(fs fmt.State, c rune) string {
	w, wOk := fs.Width()
	p, pOk := fs.Precision()
	var b bytes.Buffer
	b.WriteByte('%')
	for _, f := range "+-# 0" {
		if fs.Flag(int(f)) {
			b.WriteRune(f)
		}
	}
	if wOk {
		fmt.Fprint(&b, w)
	}
	if pOk {
		b.WriteByte('.')
		fmt.Fprint(&b, p)
	}
	b.WriteRune(c)
	return b.String()
}
Beispiel #15
0
func (x *M_Cmd) Format(f fmt.State, c int) {
	if c == 'v' && f.Flag('#') && x != nil {
		fmt.Fprintf(f, "M_%s", M_Cmd_name[int32(*x)])
		return
	}

	s := "%"
	for i := 0; i < 128; i++ {
		if f.Flag(i) {
			s += string(i)
		}
	}
	if w, ok := f.Width(); ok {
		s += fmt.Sprintf("%d", w)
	}
	if p, ok := f.Precision(); ok {
		s += fmt.Sprintf(".%d", p)
	}
	s += string(c)
	fmt.Fprintf(f, s, (*int32)(x))
}
Beispiel #16
0
Datei: ct.go Projekt: 0-T-0/ct
// Format allows text to satisfy the fmt.Formatter interface. The format
// behaviour is the same as for fmt.Print.
func (t text) Format(fs fmt.State, c rune) {
	if t.Mode&activeBits != 0 {
		t.Mode.set(fs)
	}

	w, wOk := fs.Width()
	p, pOk := fs.Precision()
	var (
		b          bytes.Buffer
		prevString bool
	)
	b.WriteByte('%')
	for _, f := range "+-# 0" {
		if fs.Flag(int(f)) {
			b.WriteRune(f)
		}
	}
	if wOk {
		fmt.Fprint(&b, w)
	}
	if pOk {
		b.WriteByte('.')
		fmt.Fprint(&b, p)
	}
	b.WriteRune(c)
	format := b.String()

	for _, v := range t.v {
		isString := v != nil && doesString(v)
		if isString && prevString {
			fs.Write([]byte{' '})
		}
		prevString = isString
		fmt.Fprintf(fs, format, v)
	}

	if t.Mode&activeBits != 0 && t.Mode&activeBits != Reset && t.Mode&NoResetAfter == 0 {
		t.reset(fs)
	}
}
Beispiel #17
0
// Format may call Sprint(f) or Fprint(f) etc. to generate its output.
func (k fileKey) Format(f fmt.State, c rune) {
	fs := &bytes.Buffer{}
	fs.WriteRune('%')
	if f.Flag('+') {
		fs.WriteRune('+')
	}
	if f.Flag('-') {
		fs.WriteRune('-')
	}
	if f.Flag('#') {
		fs.WriteRune('#')
	}
	if f.Flag(' ') {
		fs.WriteRune(' ')
	}
	if f.Flag('0') {
		fs.WriteRune('0')
	}
	if w, ok := f.Width(); ok {
		fs.WriteString(fmt.Sprintf("%d", w))
	}
	if p, ok := f.Precision(); ok {
		fs.WriteString(fmt.Sprintf("%d", p))
	}
	var (
		s  string
		cc = c
	)
	if c == 'k' {
		s = k.key()
		cc = 's'
	} else {
		s = k.String()
	}
	fs.WriteRune(cc)
	fmt.Fprintf(f, fs.String(), s)
}
Beispiel #18
0
// Format implements fmt.Formatter. It accepts all the regular
// formats for floating-point numbers ('e', 'E', 'f', 'F', 'g',
// 'G') as well as 'b', 'p', and 'v'. See (*Float).Text for the
// interpretation of 'b' and 'p'. The 'v' format is handled like
// 'g'.
// Format also supports specification of the minimum precision
// in digits, the output field width, as well as the format verbs
// '+' and ' ' for sign control, '0' for space or zero padding,
// and '-' for left or right justification. See the fmt package
// for details.
func (x *Float) Format(s fmt.State, format rune) {
	prec, hasPrec := s.Precision()
	if !hasPrec {
		prec = 6 // default precision for 'e', 'f'
	}

	switch format {
	case 'e', 'E', 'f', 'b', 'p':
		// nothing to do
	case 'F':
		// (*Float).Text doesn't support 'F'; handle like 'f'
		format = 'f'
	case 'v':
		// handle like 'g'
		format = 'g'
		fallthrough
	case 'g', 'G':
		if !hasPrec {
			prec = -1 // default precision for 'g', 'G'
		}
	default:
		fmt.Fprintf(s, "%%!%c(*big.Float=%s)", format, x.String())
		return
	}
	var buf []byte
	buf = x.Append(buf, byte(format), prec)
	if len(buf) == 0 {
		buf = []byte("?") // should never happen, but don't crash
	}
	// len(buf) > 0

	var sign string
	switch {
	case buf[0] == '-':
		sign = "-"
		buf = buf[1:]
	case buf[0] == '+':
		// +Inf
		sign = "+"
		if s.Flag(' ') {
			sign = " "
		}
		buf = buf[1:]
	case s.Flag('+'):
		sign = "+"
	case s.Flag(' '):
		sign = " "
	}

	var padding int
	if width, hasWidth := s.Width(); hasWidth && width > len(sign)+len(buf) {
		padding = width - len(sign) - len(buf)
	}

	switch {
	case s.Flag('0') && !x.IsInf():
		// 0-padding on left
		writeMultiple(s, sign, 1)
		writeMultiple(s, "0", padding)
		s.Write(buf)
	case s.Flag('-'):
		// padding on right
		writeMultiple(s, sign, 1)
		s.Write(buf)
		writeMultiple(s, " ", padding)
	default:
		// padding on left
		writeMultiple(s, " ", padding)
		writeMultiple(s, sign, 1)
		s.Write(buf)
	}
}
Beispiel #19
0
// Format is a support routine for fmt.Formatter. It accepts
// the formats 'b' (binary), 'o' (octal), 'd' (decimal), 'x'
// (lowercase hexadecimal), and 'X' (uppercase hexadecimal).
// Also supported are the full suite of package fmt's format
// verbs for integral types, including '+', '-', and ' '
// for sign control, '#' for leading zero in octal and for
// hexadecimal, a leading "0x" or "0X" for "%#x" and "%#X"
// respectively, specification of minimum digits precision,
// output field width, space or zero padding, and left or
// right justification.
//
func (x *Int) Format(s fmt.State, ch int) {
	cs := charset(ch)

	// special cases
	switch {
	case cs == "":
		// unknown format
		fmt.Fprintf(s, "%%!%c(big.Int=%s)", ch, x.String())
		return
	case x == nil:
		fmt.Fprint(s, "<nil>")
		return
	}

	// determine sign character
	sign := ""
	switch {
	case x.neg:
		sign = "-"
	case s.Flag('+'): // supersedes ' ' when both specified
		sign = "+"
	case s.Flag(' '):
		sign = " "
	}

	// determine prefix characters for indicating output base
	prefix := ""
	if s.Flag('#') {
		switch ch {
		case 'o': // octal
			prefix = "0"
		case 'x': // hexadecimal
			prefix = "0x"
		case 'X':
			prefix = "0X"
		}
	}

	// determine digits with base set by len(cs) and digit characters from cs
	digits := x.abs.string(cs)

	// number of characters for the three classes of number padding
	var left int   // space characters to left of digits for right justification ("%8d")
	var zeroes int // zero characters (actually cs[0]) as left-most digits ("%.8d")
	var right int  // space characters to right of digits for left justification ("%-8d")

	// determine number padding from precision: the least number of digits to output
	precision, precisionSet := s.Precision()
	if precisionSet {
		switch {
		case len(digits) < precision:
			zeroes = precision - len(digits) // count of zero padding
		case digits == "0" && precision == 0:
			return // print nothing if zero value (x == 0) and zero precision ("." or ".0")
		}
	}

	// determine field pad from width: the least number of characters to output
	length := len(sign) + len(prefix) + zeroes + len(digits)
	if width, widthSet := s.Width(); widthSet && length < width { // pad as specified
		switch d := width - length; {
		case s.Flag('-'):
			// pad on the right with spaces; supersedes '0' when both specified
			right = d
		case s.Flag('0') && !precisionSet:
			// pad with zeroes unless precision also specified
			zeroes = d
		default:
			// pad on the left with spaces
			left = d
		}
	}

	// print number as [left pad][sign][prefix][zero pad][digits][right pad]
	writeMultiple(s, " ", left)
	writeMultiple(s, sign, 1)
	writeMultiple(s, prefix, 1)
	writeMultiple(s, "0", zeroes)
	writeMultiple(s, digits, 1)
	writeMultiple(s, " ", right)
}
Beispiel #20
0
func formatSex(x float64, caller int, mock *string, f fmt.State, c rune) error {
	// valiate verb
	switch c {
	case 's', 'd', 'c', 'v', 'x':
	default:
		fmt.Fprintf(f, "Invalid verb: %%%c", c)
		return nil // not an overflow error
	}
	// declare some variables ahead of goto
	var (
		r          string // formatted result, ultimately
		err        error
		x60        int64
		degHr, min int64
		s1         string
		sexRune    UnitSymbols
		wid1       int
		wid1Spec   bool
	)
	neg := x < 0
	if neg {
		x = -x
	}
	// determine unit symbols
	switch {
	case c == 'x':
		sexRune = UnitSymbols{' ', ' ', ' '}
	case caller == fsAngle:
		sexRune = DMSRunes
	default:
		sexRune = HMSRunes
	}
	// get meaningful precision
	prec, ok := f.Precision()
	if !ok {
		prec = 0
	}
	if prec == 64 {
		degHr = int64(.5 + x/3600)
	} else {
		if prec == 62 {
			x60 = int64(.5 + x/60)
		} else {
			// format seconds into r
			_, x60, r, err = Split60(x, prec, f.Flag('0'))
			if err != nil {
				goto Overflow
			}
			// add seconds unit symbol
			switch c {
			case 's', 'v':
				r += string(sexRune.S)
			case 'd':
				r = DecSymAdd(r, sexRune.S)
			case 'c':
				r = DecSymCombine(r, sexRune.S)
			}
		}
		degHr = x60 / 60
		min = x60 % 60
		// format minutes into r
		if f.Flag('#') || x60 > 0 {
			if f.Flag('0') {
				r = fmt.Sprintf("%02d%c%s", min, sexRune.M, r)
			} else {
				r = fmt.Sprintf("%d%c%s", min, sexRune.M, r)
			}
		}
	}
	s1 = strconv.FormatInt(degHr, 10)
	wid1, wid1Spec = f.Width()
	if wid1Spec {
		// simple rule applies in all cases where width is specified:
		if len(s1) > wid1 {
			if caller == fsAngle {
				err = WidthErrorDegreeOverflow
			} else {
				err = WidthErrorHourOverflow
			}
			goto Overflow
		}
	}
	// format degrees or hours into r
	if f.Flag('#') || degHr > 0 {
		if f.Flag('0') {
			r = fmt.Sprintf("%0*s%c%s", wid1, s1, sexRune.First, r)
		} else {
			r = fmt.Sprintf("%s%c%s", s1, sexRune.First, r)
		}
	}
	// add leading sign
	if caller != fsRA {
		switch {
		case neg:
			r = "-" + r
		case f.Flag('+'):
			r = "+" + r
		case f.Flag(' '):
			r = " " + r
		}
	}
	if mock == nil {
		f.Write([]byte(r))
	} else {
		*mock = r
	}
	return nil
Overflow:
	err1 := err
	var width int
	if mock != nil { // detect recursive loop
		width = 10
	} else {
		var valid string
		formatSex(0, caller, &valid, f, c)
		width = utf8.RuneCountInString(valid)
	}
	f.Write(bytes.Repeat([]byte{'*'}, width)) // emit overflow indicator
	return err1
}
Beispiel #21
0
Datei: int.go Projekt: ssrl/go
// Format is a support routine for fmt.Formatter. It accepts
// the formats 'b' (binary), 'o' (octal), 'd' (decimal), 'x'
// (lowercase hexadecimal), and 'X' (uppercase hexadecimal).
//
func (x *Int) Format(s fmt.State, ch int) {
	cs := charset(ch)

	// special cases
	switch {
	case cs == "":
		// unknown format
		fmt.Fprintf(s, "%%!%c(big.Int=%s)", ch, x.String())
		return
	case x == nil:
		fmt.Fprint(s, "<nil>")
		return
	}

	// determine format
	format := "%s"
	if s.Flag('#') {
		switch ch {
		case 'o':
			format = "0%s"
		case 'x':
			format = "0x%s"
		case 'X':
			format = "0X%s"
		}
	}
	t := fmt.Sprintf(format, x.abs.string(cs))

	// insert spaces in hexadecimal formats if needed
	if len(t) > 0 && s.Flag(' ') && (ch == 'x' || ch == 'X') {
		spaces := (len(t)+1)/2 - 1
		spaced := make([]byte, len(t)+spaces)
		var i, j int
		spaced[i] = t[j]
		i++
		j++
		if len(t)&1 == 0 {
			spaced[i] = t[j]
			i++
			j++
		}
		for j < len(t) {
			spaced[i] = ' '
			i++
			spaced[i] = t[j]
			i++
			j++
			spaced[i] = t[j]
			i++
			j++
		}
		t = string(spaced)
	}

	// determine sign prefix
	prefix := ""
	switch {
	case x.neg:
		prefix = "-"
	case s.Flag('+'):
		prefix = "+"
	case s.Flag(' ') && ch != 'x' && ch != 'X':
		prefix = " "
	}

	// fill to minimum width and prepend sign prefix
	if width, ok := s.Width(); ok && len(t)+len(prefix) < width {
		if s.Flag('0') {
			t = fmt.Sprintf("%s%0*d%s", prefix, width-len(t)-len(prefix), 0, t)
		} else {
			if s.Flag('-') {
				width = -width
			}
			t = fmt.Sprintf("%*s", width, prefix+t)
		}
	} else if prefix != "" {
		t = prefix + t
	}

	fmt.Fprint(s, t)
}
Beispiel #22
0
// format prints a pretty representation of m to the fs io.Writer. The format character c
// specifies the numerical representation of of elements; valid values are those for float64
// specified in the fmt package, with their associated flags. In addition to this, a space
// preceding a verb indicates that zero values should be represented by the dot character.
// The printed range of the matrix can be limited by specifying a positive value for margin;
// If margin is greater than zero, only the first and last margin rows/columns of the matrix
// are output. If squeeze is true, column widths are determined on a per-column basis.
//
// format will not provide Go syntax output.
func format(m Matrix, prefix string, margin int, dot byte, squeeze bool, fs fmt.State, c rune) {
	rows, cols := m.Dims()

	var printed int
	if margin <= 0 {
		printed = rows
		if cols > printed {
			printed = cols
		}
	} else {
		printed = margin
	}

	prec, pOk := fs.Precision()
	if !pOk {
		prec = -1
	}

	var (
		maxWidth int
		widths   widther
		buf, pad []byte
	)
	if squeeze {
		widths = make(columnWidth, cols)
	} else {
		widths = new(uniformWidth)
	}
	switch c {
	case 'v', 'e', 'E', 'f', 'F', 'g', 'G':
		if c == 'v' {
			buf, maxWidth = maxCellWidth(m, 'g', printed, prec, widths)
		} else {
			buf, maxWidth = maxCellWidth(m, c, printed, prec, widths)
		}
	default:
		fmt.Fprintf(fs, "%%!%c(%T=Dims(%d, %d))", c, m, rows, cols)
		return
	}
	width, _ := fs.Width()
	width = max(width, maxWidth)
	pad = make([]byte, max(width, 2))
	for i := range pad {
		pad[i] = ' '
	}

	first := true
	if rows > 2*printed || cols > 2*printed {
		first = false
		fmt.Fprintf(fs, "Dims(%d, %d)\n", rows, cols)
	}

	skipZero := fs.Flag(' ')
	for i := 0; i < rows; i++ {
		if !first {
			fmt.Fprint(fs, prefix)
		}
		first = false
		var el string
		switch {
		case rows == 1:
			fmt.Fprint(fs, "[")
			el = "]"
		case i == 0:
			fmt.Fprint(fs, "⎡")
			el = "⎤\n"
		case i < rows-1:
			fmt.Fprint(fs, "⎢")
			el = "⎥\n"
		default:
			fmt.Fprint(fs, "⎣")
			el = "⎦"
		}

		for j := 0; j < cols; j++ {
			if j >= printed && j < cols-printed {
				j = cols - printed - 1
				if i == 0 || i == rows-1 {
					fmt.Fprint(fs, "...  ...  ")
				} else {
					fmt.Fprint(fs, "          ")
				}
				continue
			}

			v := m.At(i, j)
			if v == 0 && skipZero {
				buf = buf[:1]
				buf[0] = dot
			} else {
				if c == 'v' {
					buf = strconv.AppendFloat(buf[:0], v, 'g', prec, 64)
				} else {
					buf = strconv.AppendFloat(buf[:0], v, byte(c), prec, 64)
				}
			}
			if fs.Flag('-') {
				fs.Write(buf)
				fs.Write(pad[:widths.width(j)-len(buf)])
			} else {
				fs.Write(pad[:widths.width(j)-len(buf)])
				fs.Write(buf)
			}

			if j < cols-1 {
				fs.Write(pad[:2])
			}
		}

		fmt.Fprint(fs, el)

		if i >= printed-1 && i < rows-printed && 2*printed < rows {
			i = rows - printed - 1
			fmt.Fprint(fs, " .\n .\n .\n")
			continue
		}
	}
}
Beispiel #23
0
// Format prints a pretty representation of m to the fs io.Writer. The format character c
// specifies the numerical representation of of elements; valid values are those for float64
// specified in the fmt package, with their associated flags. In addition to this, a '#' for
// all valid verbs except 'v' indicates that zero values be represented by the dot character.
// The '#' associated with the 'v' verb formats the matrix with Go syntax representation.
// The printed range of the matrix can be limited by specifying a positive value for margin;
// If margin is greater than zero, only the first and last margin rows/columns of the matrix
// are output.
func Format(m Matrix, margin int, dot byte, fs fmt.State, c rune) {
	rows, cols := m.Dims()

	var printed int
	if margin <= 0 {
		printed = rows
		if cols > printed {
			printed = cols
		}
	} else {
		printed = margin
	}

	prec, pOk := fs.Precision()
	if !pOk {
		prec = -1
	}

	var (
		maxWidth int
		buf, pad []byte
	)
	switch c {
	case 'v', 'e', 'E', 'f', 'F', 'g', 'G':
		// Note that the '#' flag should have been dealt with by the type.
		// So %v is treated exactly as %g here.
		if c == 'v' {
			buf, maxWidth = maxCellWidth(m, 'g', printed, prec)
		} else {
			buf, maxWidth = maxCellWidth(m, c, printed, prec)
		}
	default:
		fmt.Fprintf(fs, "%%!%c(%T=Dims(%d, %d))", c, m, rows, cols)
		return
	}
	width, _ := fs.Width()
	width = max(width, maxWidth)
	pad = make([]byte, max(width, 2))
	for i := range pad {
		pad[i] = ' '
	}

	if rows > 2*printed || cols > 2*printed {
		fmt.Fprintf(fs, "Dims(%d, %d)\n", rows, cols)
	}

	skipZero := fs.Flag('#')
	for i := 0; i < rows; i++ {
		var el string
		switch {
		case rows == 1:
			fmt.Fprint(fs, "[")
			el = "]"
		case i == 0:
			fmt.Fprint(fs, "⎡")
			el = "⎤\n"
		case i < rows-1:
			fmt.Fprint(fs, "⎢")
			el = "⎥\n"
		default:
			fmt.Fprint(fs, "⎣")
			el = "⎦"
		}

		for j := 0; j < cols; j++ {
			if j >= printed && j < cols-printed {
				j = cols - printed - 1
				if i == 0 || i == rows-1 {
					fmt.Fprint(fs, "...  ...  ")
				} else {
					fmt.Fprint(fs, "          ")
				}
				continue
			}

			v := m.At(i, j)
			if v == 0 && skipZero {
				buf = buf[:1]
				buf[0] = dot
			} else {
				if c == 'v' {
					buf = strconv.AppendFloat(buf[:0], v, 'g', prec, 64)
				} else {
					buf = strconv.AppendFloat(buf[:0], v, byte(c), prec, 64)
				}
			}
			if fs.Flag('-') {
				fs.Write(buf)
				fs.Write(pad[:width-len(buf)])
			} else {
				fs.Write(pad[:width-len(buf)])
				fs.Write(buf)
			}

			if j < cols-1 {
				fs.Write(pad[:2])
			}
		}

		fmt.Fprint(fs, el)

		if i >= printed-1 && i < rows-printed && 2*printed < rows {
			i = rows - printed - 1
			fmt.Fprint(fs, " .\n .\n .\n")
			continue
		}
	}
}
Beispiel #24
0
// Format is a support routine for fmt.Formatter. It accepts the formats 'v' and 's'
// (string), 'a' (fasta) and 'q' (fastq). String, fasta and fastq formats support
// truncated output via the verb's precision. Fasta format supports sequence line
// specification via the verb's width field. Fastq format supports optional inclusion
// of the '+' line descriptor line with the '+' flag. The 'v' verb supports the '#'
// flag for Go syntax output. The 's' and 'v' formats support the '-' flag for
// omission of the sequence name.
func (r Row) Format(fs fmt.State, c rune) {
	var (
		s      = r.Align
		w, wOk = fs.Width()
		p, pOk = fs.Precision()
		buf    alphabet.Columns
	)
	if s != nil {
		if pOk {
			buf = s.Seq[:min(p, len(s.Seq))]
		} else {
			buf = s.Seq
		}
	}

	switch c {
	case 'v':
		if fs.Flag('#') {
			type shadowRow Row
			sr := fmt.Sprintf("%#v", shadowRow(r))
			fmt.Fprintf(fs, "%T%s", r, sr[strings.Index(sr, "{"):])
			return
		}
		fallthrough
	case 's':
		if s == nil {
			fmt.Fprint(fs, "<nil>")
			return
		}
		if !fs.Flag('-') {
			fmt.Fprintf(fs, "%q ", r.Name())
		}
		for _, lc := range buf {
			fmt.Fprintf(fs, "%c", lc[r.Row])
		}
		if pOk && s != nil && p < s.Len() {
			fmt.Fprint(fs, "...")
		}
	case 'a':
		if s == nil {
			return
		}
		r.formatDescLineTo(fs, '>')
		for i, lc := range buf {
			fmt.Fprintf(fs, "%c", lc[r.Row])
			if wOk && i < s.Len()-1 && i%w == w-1 {
				fmt.Fprintln(fs)
			}
		}
		if pOk && p < s.Len() {
			fmt.Fprint(fs, "...")
		}
	case 'q':
		if s == nil {
			return
		}
		r.formatDescLineTo(fs, '@')
		for _, lc := range buf {
			fmt.Fprintf(fs, "%c", lc[r.Row])
		}
		if pOk && p < s.Len() {
			fmt.Fprintln(fs, "...")
		} else {
			fmt.Fprintln(fs)
		}
		if fs.Flag('+') {
			r.formatDescLineTo(fs, '+')
		} else {
			fmt.Fprintln(fs, "+")
		}
		e := seq.DefaultQphred.Encode(seq.DefaultEncoding)
		if e >= unicode.MaxASCII {
			e = unicode.MaxASCII - 1
		}
		for _ = range buf {
			fmt.Fprintf(fs, "%c", e)
		}
		if pOk && p < s.Len() {
			fmt.Fprint(fs, "...")
		}
	default:
		fmt.Fprintf(fs, "%%!%c(alignment.Row=%.10s)", c, s)
	}
}
Beispiel #25
0
// Format implements fmt.Formatter. It accepts the formats
// 'b' (binary), 'o' (octal), 'd' (decimal), 'x' (lowercase
// hexadecimal), and 'X' (uppercase hexadecimal).
// Also supported are the full suite of package fmt's format
// flags for integral types, including '+' and ' ' for sign
// control, '#' for leading zero in octal and for hexadecimal,
// a leading "0x" or "0X" for "%#x" and "%#X" respectively,
// specification of minimum digits precision, output field
// width, space or zero padding, and '-' for left or right
// justification.
//
func (x *Int) Format(s fmt.State, ch rune) {
	// determine base
	var base int
	switch ch {
	case 'b':
		base = 2
	case 'o':
		base = 8
	case 'd', 's', 'v':
		base = 10
	case 'x', 'X':
		base = 16
	default:
		// unknown format
		fmt.Fprintf(s, "%%!%c(big.Int=%s)", ch, x.String())
		return
	}

	if x == nil {
		fmt.Fprint(s, "<nil>")
		return
	}

	// determine sign character
	sign := ""
	switch {
	case x.neg:
		sign = "-"
	case s.Flag('+'): // supersedes ' ' when both specified
		sign = "+"
	case s.Flag(' '):
		sign = " "
	}

	// determine prefix characters for indicating output base
	prefix := ""
	if s.Flag('#') {
		switch ch {
		case 'o': // octal
			prefix = "0"
		case 'x': // hexadecimal
			prefix = "0x"
		case 'X':
			prefix = "0X"
		}
	}

	digits := x.abs.utoa(base)
	if ch == 'X' {
		// faster than bytes.ToUpper
		for i, d := range digits {
			if 'a' <= d && d <= 'z' {
				digits[i] = 'A' + (d - 'a')
			}
		}
	}

	// number of characters for the three classes of number padding
	var left int  // space characters to left of digits for right justification ("%8d")
	var zeros int // zero characters (actually cs[0]) as left-most digits ("%.8d")
	var right int // space characters to right of digits for left justification ("%-8d")

	// determine number padding from precision: the least number of digits to output
	precision, precisionSet := s.Precision()
	if precisionSet {
		switch {
		case len(digits) < precision:
			zeros = precision - len(digits) // count of zero padding
		case len(digits) == 1 && digits[0] == '0' && precision == 0:
			return // print nothing if zero value (x == 0) and zero precision ("." or ".0")
		}
	}

	// determine field pad from width: the least number of characters to output
	length := len(sign) + len(prefix) + zeros + len(digits)
	if width, widthSet := s.Width(); widthSet && length < width { // pad as specified
		switch d := width - length; {
		case s.Flag('-'):
			// pad on the right with spaces; supersedes '0' when both specified
			right = d
		case s.Flag('0') && !precisionSet:
			// pad with zeros unless precision also specified
			zeros = d
		default:
			// pad on the left with spaces
			left = d
		}
	}

	// print number as [left pad][sign][prefix][zero pad][digits][right pad]
	writeMultiple(s, " ", left)
	writeMultiple(s, sign, 1)
	writeMultiple(s, prefix, 1)
	writeMultiple(s, "0", zeros)
	s.Write(digits)
	writeMultiple(s, " ", right)
}
Beispiel #26
0
// Format is a support routine for fmt.Formatter. It accepts the formats 'v' and 's'
// (string), 'a' (fasta) and 'q' (fastq). String, fasta and fastq formats support
// truncated output via the verb's precision. Fasta format supports sequence line
// specification via the verb's width field. Fastq format supports optional inclusion
// of the '+' line descriptor line with the '+' flag. The 'v' verb supports the '#'
// flag for Go syntax output. The 's' and 'v' formats support the '-' flag for
// omission of the sequence name.
func (s *QSeq) Format(fs fmt.State, c rune) {
	if s == nil {
		fmt.Fprint(fs, "<nil>")
		return
	}
	var (
		w, wOk = fs.Width()
		p, pOk = fs.Precision()
		buf    []alphabet.QLetter
	)
	if pOk {
		buf = s.Seq[:min(p, len(s.Seq))]
	} else {
		buf = s.Seq
	}

	switch c {
	case 'v':
		if fs.Flag('#') {
			fmt.Fprintf(fs, "&%#v", *s)
			return
		}
		fallthrough
	case 's':
		if !fs.Flag('-') {
			fmt.Fprintf(fs, "%q ", s.ID)
		}
		for _, ql := range buf {
			fmt.Fprintf(fs, "%c", s.QFilter(s.Alpha, s.Threshold, ql))
		}
		if pOk && p < s.Len() {
			fmt.Fprint(fs, "...")
		}
	case 'a':
		s.formatDescLineTo(fs, '>')
		for i, ql := range buf {
			fmt.Fprintf(fs, "%c", s.QFilter(s.Alpha, s.Threshold, ql))
			if wOk && i < s.Len()-1 && i%w == w-1 {
				fmt.Fprintln(fs)
			}
		}
		if pOk && p < s.Len() {
			fmt.Fprint(fs, "...")
		}
	case 'q':
		s.formatDescLineTo(fs, '@')
		for _, ql := range buf {
			fmt.Fprintf(fs, "%c", s.QFilter(s.Alpha, s.Threshold, ql))
		}
		if pOk && p < s.Len() {
			fmt.Fprintln(fs, "...")
		} else {
			fmt.Fprintln(fs)
		}
		if fs.Flag('+') {
			s.formatDescLineTo(fs, '+')
		} else {
			fmt.Fprintln(fs, "+")
		}
		for _, ql := range buf {
			e := ql.Q.Encode(s.Encode)
			if e >= unicode.MaxASCII {
				e = unicode.MaxASCII - 1
			}
			fmt.Fprintf(fs, "%c", e)
		}
		if pOk && p < s.Len() {
			fmt.Fprint(fs, "...")
		}
	default:
		fmt.Fprintf(fs, "%%!%c(linear.QSeq=%.10s)", c, s)
	}
}