forked from diamondburned/gotk4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
piece.go
83 lines (70 loc) · 1.39 KB
/
piece.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package pen
import (
"fmt"
"strings"
)
// Piece is a simple string builder with easy chaining.
type Piece struct {
str strings.Builder
}
// NewPiece returns a new piece.
func NewPiece() *Piece {
return &Piece{}
}
func (p *Piece) ensureCap() {
if p.str.Cap() < 4096 {
p.str.Grow(4096)
}
}
// Writef writes using Printf.
func (p *Piece) Writef(f string, v ...interface{}) *Piece {
p.ensureCap()
if len(v) == 0 {
p.str.WriteString(f)
} else {
fmt.Fprintf(&p.str, f, v...)
}
return p
}
// Write writes using Print.
func (p *Piece) Write(v ...interface{}) *Piece {
p.ensureCap()
if len(v) == 1 {
if str, ok := v[0].(string); ok {
p.str.WriteString(str)
return p
}
}
fmt.Fprint(&p.str, v...)
return p
}
// Char writes a single ASCII character.
func (p *Piece) Char(b byte) *Piece {
p.ensureCap()
p.str.WriteByte(b)
return p
}
// EmptyLine writes a new line.
func (p *Piece) EmptyLine() *Piece {
p.ensureCap()
p.str.WriteByte('\n')
return p
}
// Line writes a line.
func (p *Piece) Line(line string) *Piece {
p.ensureCap()
p.str.WriteString(line)
p.str.WriteByte('\n')
return p
}
// Linef writes a line using Sprintf.
func (p *Piece) Linef(f string, v ...interface{}) *Piece {
p.ensureCap()
p.Writef(f, v...)
p.str.WriteByte('\n')
return p
}
// String returns the inner string block.
func (p *Piece) String() string {
return strings.TrimSuffix(p.str.String(), "\n")
}