Added TrimStrIfAppropriate & docs for TrimStr2Runes.

This commit is contained in:
Matteo Kloiber 2015-04-01 22:25:00 +02:00
parent 6a92b4408c
commit d01854a399
2 changed files with 45 additions and 6 deletions

View File

@ -45,15 +45,39 @@ func str2runes(s string) []rune {
return []rune(s)
}
// Here for backwards-compatibility.
func trimStr2Runes(s string, w int) []rune {
return TrimStr2Runes(s, w)
}
// TrimStr2Runes trims string to w[-1 rune], appends …, and returns the runes
// of that string if string is grather then n. If string is small then w,
// return the runes.
func TrimStr2Runes(s string, w int) []rune {
if w <= 0 {
return []rune{}
}
sw := rw.StringWidth(s)
if sw > w {
return []rune(rw.Truncate(s, w, dot))
}
return str2runes(s) //[]rune(rw.Truncate(s, w, ""))
return str2runes(s)
}
// TrimStrIfAppropriate trim string to "s[:-1] + …"
// if string > width otherwise return string
func TrimStrIfAppropriate(s string, w int) string {
if w <= 0 {
return ""
}
sw := rw.StringWidth(s)
if sw > w {
return rw.Truncate(s, w, dot)
}
return s
}
func strWidth(s string) int {

View File

@ -5,24 +5,21 @@
package termui
import (
"fmt"
"testing"
"github.com/davecgh/go-spew/spew"
)
func TestStr2Rune(t *testing.T) {
s := "你好,世界."
rs := str2runes(s)
if len(rs) != 6 {
t.Error()
t.Error(t)
}
}
func TestWidth(t *testing.T) {
s0 := "つのだ☆HIRO"
s1 := "11111111111"
spew.Dump(s0)
spew.Dump(s1)
// above not align for setting East Asian Ambiguous to wide!!
if strWidth(s0) != strWidth(s1) {
@ -56,3 +53,21 @@ func TestTrim(t *testing.T) {
t.Error("avoid trim failed")
}
}
func assertEqual(t *testing.T, expected, got interface{}, msg ...interface{}) {
baseMsg := fmt.Sprintf("Got %v expected %v", got, expected)
msg = append([]interface{}{baseMsg}, msg...)
if expected != got {
t.Error(fmt.Sprint(msg...))
}
}
func TestTrimStrIfAppropriate_NoTrim(t *testing.T) {
assertEqual(t, "hello", TrimStrIfAppropriate("hello", 5))
}
func TestTrimStrIfAppropriate(t *testing.T) {
assertEqual(t, "hel…", TrimStrIfAppropriate("hello", 4))
assertEqual(t, "h…", TrimStrIfAppropriate("hello", 2))
}