Browse Source

[common] Add ASCIITrim

pull/1780/head
Jae Kwon 7 years ago
parent
commit
9b2a8f07a3
2 changed files with 23 additions and 0 deletions
  1. +15
    -0
      common/string.go
  2. +8
    -0
      common/string_test.go

+ 15
- 0
common/string.go View File

@ -72,3 +72,18 @@ func IsASCIIText(s string) bool {
} }
return true return true
} }
// NOTE: Assumes that s is ASCII as per IsASCIIText(), otherwise panics.
func ASCIITrim(s string) string {
r := make([]byte, 0, len(s))
for _, b := range []byte(s) {
if b == 32 {
continue // skip space
} else if 32 < b && b <= 126 {
r = append(r, b)
} else {
panic(fmt.Sprintf("non-ASCII (non-tab) char 0x%X", b))
}
}
return string(r)
}

+ 8
- 0
common/string_test.go View File

@ -64,3 +64,11 @@ func TestIsASCIIText(t *testing.T) {
assert.True(t, IsASCIIText(v), "%q is ascii-text", v) assert.True(t, IsASCIIText(v), "%q is ascii-text", v)
} }
} }
func TestASCIITrim(t *testing.T) {
assert.Equal(t, ASCIITrim(" "), "")
assert.Equal(t, ASCIITrim(" a"), "a")
assert.Equal(t, ASCIITrim("a "), "a")
assert.Equal(t, ASCIITrim(" a "), "a")
assert.Panics(t, func() { ASCIITrim("\xC2\xA2") })
}

Loading…
Cancel
Save