Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid truncation for inputs close to limit #57

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion truncate/truncate.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,10 @@ func (w *Writer) Write(b []byte) (int, error) {
return w.buf.WriteString(w.tail)
}

w.width -= uint(tw)
safeWidth := w.width - uint(tw)
var curWidth uint

var tailcs []rune
for _, c := range string(b) {
if c == ansi.Marker {
// ANSI escape sequence
Expand All @@ -98,8 +99,18 @@ func (w *Writer) Write(b []byte) (int, error) {
w.ansiWriter.ResetAnsi()
}
return n, err
} else if curWidth > safeWidth {
tailcs = append(tailcs, c) // buffer rune until it's safe to write
} else {
_, err := w.ansiWriter.Write([]byte(string(c)))
if err != nil {
return 0, err
}
}
}

// never exceeded width, so safe to write buffered tail runes
for _, c := range tailcs {
_, err := w.ansiWriter.Write([]byte(string(c)))
if err != nil {
return 0, err
Expand Down
23 changes: 22 additions & 1 deletion truncate/truncate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,27 @@ func TestTruncate(t *testing.T) {
"foobar",
"foo.",
},
// Same width:
// Same width with no tail:
{
3,
"",
"foo",
"foo",
},
// Same width with tail:
{
3,
".",
"foo",
"foo",
},
// Pass through when in + tail longer than width, but in shorter:
{
4,
"...",
"foo",
"foo",
},
// Tail is longer than width:
{
2,
Expand All @@ -66,6 +80,13 @@ func TestTruncate(t *testing.T) {
"你好",
"你",
},
// Double-width runes with tail:
{
4,
".",
"你好",
"你好",
},
// Double-width rune is dropped if it is too wide:
{
1,
Expand Down