prefer io.WriteString
Vladimir Bauer
8 years ago
| 1 | 1 | |
| 2 | 2 | import ( |
| 3 | 3 | "fmt" |
| 4 | "io" | |
| 4 | 5 | "strconv" |
| 5 | 6 | "strings" |
| 6 | 7 | ) |
| 32 | 33 | |
| 33 | 34 | type CounterKiB int64 |
| 34 | 35 | |
| 35 | func (c CounterKiB) Format(f fmt.State, r rune) { | |
| 36 | prec, ok := f.Precision() | |
| 36 | func (c CounterKiB) Format(st fmt.State, r rune) { | |
| 37 | prec, ok := st.Precision() | |
| 37 | 38 | |
| 38 | 39 | if r == 'd' || !ok { |
| 39 | 40 | prec = 0 |
| 65 | 66 | res = strconv.FormatInt(int64(c), 10) |
| 66 | 67 | } |
| 67 | 68 | |
| 68 | if f.Flag(int(' ')) { | |
| 69 | if st.Flag(' ') { | |
| 69 | 70 | res += " " |
| 70 | 71 | } |
| 71 | 72 | res += unit |
| 72 | 73 | |
| 73 | if w, ok := f.Width(); ok { | |
| 74 | if w, ok := st.Width(); ok { | |
| 74 | 75 | if len(res) < w { |
| 75 | 76 | pad := strings.Repeat(" ", w-len(res)) |
| 76 | if f.Flag(int('-')) { | |
| 77 | if st.Flag(int('-')) { | |
| 77 | 78 | res += pad |
| 78 | 79 | } else { |
| 79 | 80 | res = pad + res |
| 81 | 82 | } |
| 82 | 83 | } |
| 83 | 84 | |
| 84 | f.Write([]byte(res)) | |
| 85 | io.WriteString(st, res) | |
| 85 | 86 | } |
| 86 | 87 | |
| 87 | 88 | type CounterKB int64 |
| 88 | 89 | |
| 89 | func (c CounterKB) Format(f fmt.State, r rune) { | |
| 90 | prec, ok := f.Precision() | |
| 90 | func (c CounterKB) Format(st fmt.State, verb rune) { | |
| 91 | prec, ok := st.Precision() | |
| 91 | 92 | |
| 92 | if r == 'd' || !ok { | |
| 93 | if verb == 'd' || !ok { | |
| 93 | 94 | prec = 0 |
| 94 | 95 | } |
| 95 | if r == 'f' && !ok { | |
| 96 | if verb == 'f' && !ok { | |
| 96 | 97 | prec = 6 |
| 97 | 98 | } |
| 98 | 99 | // retain old beahavior if s verb used |
| 99 | if r == 's' { | |
| 100 | if verb == 's' { | |
| 100 | 101 | prec = 1 |
| 101 | 102 | } |
| 102 | 103 | |
| 119 | 120 | res = strconv.FormatInt(int64(c), 10) |
| 120 | 121 | } |
| 121 | 122 | |
| 122 | if f.Flag(int(' ')) { | |
| 123 | if st.Flag(' ') { | |
| 123 | 124 | res += " " |
| 124 | 125 | } |
| 125 | 126 | res += unit |
| 126 | 127 | |
| 127 | if w, ok := f.Width(); ok { | |
| 128 | if w, ok := st.Width(); ok { | |
| 128 | 129 | if len(res) < w { |
| 129 | 130 | pad := strings.Repeat(" ", w-len(res)) |
| 130 | if f.Flag(int('-')) { | |
| 131 | if st.Flag(int('-')) { | |
| 131 | 132 | res += pad |
| 132 | 133 | } else { |
| 133 | 134 | res = pad + res |
| 135 | 136 | } |
| 136 | 137 | } |
| 137 | 138 | |
| 138 | f.Write([]byte(res)) | |
| 139 | io.WriteString(st, res) | |
| 139 | 140 | } |