Example #1
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
	}
}
Example #2
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)
}
Example #3
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)
}
Example #4
0
// Format implements fmt.Formatter. It accepts format.State for
// language-specific rendering.
func (v Value) Format(s fmt.State, verb rune) {
	var lang int
	if state, ok := s.(format.State); ok {
		lang, _ = language.CompactIndex(state.Language())
	}

	// Get the options. Use DefaultFormat if not present.
	opt := v.format
	if opt == nil {
		opt = defaultFormat
	}
	cur := v.currency
	if cur.index == 0 {
		cur = opt.currency
	}

	// TODO: use pattern.
	io.WriteString(s, opt.symbol(lang, cur))
	if v.amount != nil {
		s.Write(space)

		// TODO: apply currency-specific rounding
		scale, _ := opt.kind.Rounding(cur)
		if _, ok := s.Precision(); !ok {
			fmt.Fprintf(s, "%.*f", scale, v.amount)
		} else {
			fmt.Fprint(s, v.amount)
		}
	}
}
Example #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")
}
Example #6
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)
}
Example #7
0
File: fmt.go Project: achanda/go
// fmtFlag computes the (internal) FmtFlag
// value given the fmt.State and format verb.
func fmtFlag(s fmt.State, verb rune) FmtFlag {
	var flag FmtFlag
	if s.Flag('-') {
		flag |= FmtLeft
	}
	if s.Flag('#') {
		flag |= FmtSharp
	}
	if s.Flag('+') {
		flag |= FmtSign
	}
	if s.Flag(' ') {
		flag |= FmtUnsigned
	}
	if _, ok := s.Precision(); ok {
		flag |= FmtComma
	}
	if s.Flag('0') {
		flag |= FmtByte
	}
	switch verb {
	case 'S':
		flag |= FmtShort
	case 'L':
		flag |= FmtLong
	}
	return flag
}
Example #8
0
File: goof.go Project: akutz/goof
// 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)
}
Example #9
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))
}
Example #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)
}
Example #11
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))
}
Example #12
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)
}
Example #13
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()
}
Example #14
0
File: m_test.go Project: kr/doozer
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))
}
Example #15
0
File: ct.go Project: 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)
	}
}
Example #16
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)
}
Example #17
0
func (pf *printFormatter) Format(f fmt.State, c rune) {
	var qual Qualification
	if prec, ok := f.Precision(); ok {
		if prec < 0 || prec >= len(QualLevels) {
			fmt.Fprintf(f, "%%!%c(invalid qual %d)", c, prec)
			return
		}
		qual = QualLevels[prec]
	}

	switch c {
	case 'n':
		fmt.Fprint(f, pf.Name(qual))
	case 'w':
		fmt.Fprint(f, pf.DefKeyword())
	case 'k':
		fmt.Fprint(f, pf.Kind())
	case 't':
		if f.Flag(' ') {
			fmt.Fprint(f, pf.NameAndTypeSeparator())
		}
		fmt.Fprint(f, pf.Type(qual))
	}
}
Example #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)
	}
}
Example #19
0
File: int.go Project: Sunmonds/gcc
// 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)
}
Example #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
}
Example #21
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
		}
	}
}
Example #22
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)
	}
}
Example #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 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
		}
	}
}
Example #24
0
File: qseq.go Project: gordon/biogo
// 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)
	}
}
Example #25
0
/*
Format implements the fmt.Formatter interface, based on Apache HTTP's
CustomLog directive. This allows a Context object to have Sprintf verbs for
its values. See: https://httpd.apache.org/docs/2.4/mod/mod_log_config.html#formats

	Verb	Description
	----	---------------------------------------------------

	%%  	Percent sign
	%a  	Client remote address
	%b  	Size of reponse in bytes, excluding headers. Or '-' if zero.
	%#a 	Proxy client address, or unknown.
	%h  	Remote hostname. Will perform lookup.
	%l  	Remote ident, will write '-' (only for Apache log support).
	%m  	Request method
	%q  	Request query string.
	%r  	Request line.
	%#r 	Request line without protocol.
	%s  	Response status code.
	%#s 	Response status code and text.
	%t  	Request time, as string.
	%u  	Remote user, if any.
	%v  	Request host name.
	%A  	User agent.
	%B  	Size of reponse in bytes, excluding headers.
	%C  	Colorized status code. For console, using ANSI escape codes.
	%D  	Time lapsed to serve request, in seconds.
	%H  	Request protocol.
	%I  	Bytes received.
	%L  	Request ID.
	%P  	Server port used.
	%R  	Referer.
	%U  	Request path.

Example:

	// Print request line and remote address.
	// Index [1] needed to reuse ctx argument.
	fmt.Printf("\"%r\" %[1]a", ctx)
	// Output:
	// "GET /v1/" 192.168.1.10

*/
func (ctx *Context) Format(f fmt.State, c rune) {
	var str string

	p, pok := f.Precision()
	if !pok {
		p = -1
	}

	switch c {
	case 'a':
		if f.Flag('#') {
			str = ctx.ProxyClient()
			break
		}
		str = ctx.Request.RemoteAddr
	case 'b':
		if ctx.Bytes() == 0 {
			f.Write([]byte{45})
			return
		}
		fallthrough
	case 'B':
		str = strconv.Itoa(ctx.Bytes())
	case 'h':
		t := strings.Split(ctx.Request.RemoteAddr, ":")
		str = t[0]
	case 'l':
		f.Write([]byte{45})
		return
	case 'm':
		str = ctx.Request.Method
	case 'q':
		str = ctx.Request.URL.RawQuery
	case 'r':
		str = ctx.Request.Method + " " + ctx.Request.URL.RequestURI()
		if f.Flag('#') {
			break
		}
		str += " " + ctx.Request.Proto
	case 's':
		str = strconv.Itoa(ctx.Status())
		if f.Flag('#') {
			str += " " + http.StatusText(ctx.Status())
		}
	case 't':
		t := ctx.Info.GetTime("context.start_time")
		str = t.Format("[02/Jan/2006:15:04:05 -0700]")
	case 'u':
		// XXX: i dont think net/http sets User
		if ctx.Request.URL.User == nil {
			f.Write([]byte{45})
			return
		}
		str = ctx.Request.URL.User.Username()
	case 'v':
		str = ctx.Request.Host
	case 'A':
		str = ctx.Request.UserAgent()
	case 'C':
		str = statusColor(ctx.Status())
	case 'D':
		when := ctx.Info.GetTime("context.start_time")
		if when.IsZero() {
			f.Write([]byte("%!(BADTIME)"))
			return
		}
		pok = false
		str = strconv.FormatFloat(time.Since(when).Seconds(), 'f', p, 32)
	case 'H':
		str = ctx.Request.Proto
	case 'I':
		str = fmt.Sprintf("%d", ctx.Request.ContentLength)
	case 'L':
		str = ctx.Info.Get("context.request_id")
	case 'P':
		s := strings.Split(ctx.Request.Host, ":")
		if len(s) > 1 {
			str = s[1]
			break
		}
		str = "80"
	case 'R':
		str = ctx.Request.Referer()
	case 'U':
		str = ctx.Request.URL.Path
	}
	if pok {
		str = str[:p]
	}
	f.Write([]byte(str))
}
Example #26
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)
}