go-utf8/runelength.go

47 lines
583 B
Go
Raw Normal View History

2022-07-18 23:36:02 +00:00
package utf8
2018-07-02 18:03:47 +00:00
2022-07-19 01:46:19 +00:00
// RuneLength returns the number of bytes in a UTF-8 encoding of this Unicode code point.
2018-07-02 18:28:12 +00:00
//
// Example
//
2022-07-19 01:46:19 +00:00
// length := utf8.RuneLength('A')
2018-07-02 18:28:12 +00:00
//
// // length == 1
//
// Example
//
2022-07-19 01:46:19 +00:00
// length := utf8.RuneLength('r')
2018-07-02 18:28:12 +00:00
//
// // length == 1
//
// Example
//
2022-07-19 01:46:19 +00:00
// length := utf8.RuneLength('¡')
2018-07-02 18:28:12 +00:00
//
// // length == 2
//
// Example
//
2022-07-19 01:46:19 +00:00
// length := utf8.RuneLength('۵')
2018-07-02 18:28:12 +00:00
//
// // length == 2
2022-07-19 01:46:19 +00:00
func RuneLength(r rune) int {
2018-07-02 18:03:47 +00:00
switch {
2018-07-02 18:11:03 +00:00
case 127 >= r:
2018-07-02 18:03:47 +00:00
return 1
case 0x7FF >= r:
return 2
case 0xFFFF >= r:
return 3
case 0x10FFFF >= r:
return 4
default:
return 0
}
}