utf8s.Len()

master
Charles Iliya Krempeaux 2018-07-02 11:03:47 -07:00
parent 444816a8c7
commit 751302c4d8
2 changed files with 78 additions and 0 deletions

22
len.go 100644
View File

@ -0,0 +1,22 @@
package utf8s
// Len returns the number of bytes in a UTF-8 encoding of this Unicode code point.
func Len(r rune) int {
switch {
case 127 > r:
return 1
case 0x7FF >= r:
return 2
case 0xFFFF >= r:
return 3
case 0x10FFFF >= r:
return 4
default:
return 0
}
}

56
len_test.go 100644
View File

@ -0,0 +1,56 @@
package utf8s
import (
"testing"
)
func TestLen(t *testing.T) {
tests := []struct{
Datum rune
Expected int
}{
{
Datum: 'A',
Expected: 1,
},
{
Datum: 'r',
Expected: 1,
},
{
Datum: '¡',
Expected: 2,
},
{
Datum: '۵',
Expected: 2,
},
{
Datum: '‱',
Expected: 3,
},
{
Datum: '≡',
Expected: 3,
},
{
Datum: '𐏕',
Expected: 4,
},
{
Datum: '🙂',
Expected: 4,
},
}
for testNumber, test := range tests {
actual := Len(test.Datum)
if expected := test.Expected; expected != actual {
t.Errorf("For test #%d, expected %d, but actually got %d.", testNumber, expected, actual)
continue
}
}
}