refactor cap line splitting

This commit is contained in:
Shivaram Lingamneni
2019-11-09 20:31:39 -05:00
parent b7076f4c9e
commit a75d26a46b
5 changed files with 126 additions and 83 deletions

View File

@@ -83,3 +83,44 @@ func MakeSplitMessage(original string, origIs512 bool) (result SplitMessage) {
return
}
// TokenLineBuilder is a helper for building IRC lines composed of delimited tokens,
// with a maximum line length.
type TokenLineBuilder struct {
lineLen int
delim string
buf bytes.Buffer
result []string
}
func (t *TokenLineBuilder) Initialize(lineLen int, delim string) {
t.lineLen = lineLen
t.delim = delim
}
// Add adds a token to the line, creating a new line if necessary.
func (t *TokenLineBuilder) Add(token string) {
tokenLen := len(token)
if t.buf.Len() != 0 {
tokenLen += len(t.delim)
}
if t.lineLen < t.buf.Len()+tokenLen {
t.result = append(t.result, t.buf.String())
t.buf.Reset()
}
if t.buf.Len() != 0 {
t.buf.WriteString(t.delim)
}
t.buf.WriteString(token)
}
// Lines terminates the line-building and returns all the lines.
func (t *TokenLineBuilder) Lines() (result []string) {
result = t.result
t.result = nil
if t.buf.Len() != 0 {
result = append(result, t.buf.String())
t.buf.Reset()
}
return
}

View File

@@ -58,3 +58,27 @@ func BenchmarkWordWrap(b *testing.B) {
WordWrap(monteCristo, 60)
}
}
func TestTokenLineBuilder(t *testing.T) {
lineLen := 400
var tl TokenLineBuilder
tl.Initialize(lineLen, " ")
for _, token := range strings.Fields(monteCristo) {
tl.Add(token)
}
lines := tl.Lines()
if len(lines) != 4 {
t.Errorf("expected 4 lines, got %d", len(lines))
}
for _, line := range lines {
if len(line) > lineLen {
t.Errorf("line length %d exceeds maximum of %d", len(line), lineLen)
}
}
joined := strings.Join(lines, " ")
if joined != monteCristo {
t.Errorf("text incorrectly split into lines: %s instead of %s", joined, monteCristo)
}
}