go-utf8/writerune.go

78 lines
1.4 KiB
Go
Raw Normal View History

2022-07-18 23:36:02 +00:00
package utf8
2018-07-02 09:37:29 +00:00
import (
"io"
)
// WriteRune writes a single UTF-8 encoded Unicode character and returns the number of bytes written.
2022-07-19 05:02:10 +00:00
//
2022-07-19 05:12:14 +00:00
// If writer is nil then WriteRune will return an error that matches utf8.NilWriterComplainer.
2022-07-19 05:02:10 +00:00
//
// Example
//
// Here is an example usage of WriteRune:
//
// n, err := utf8.WriteRune(writer, r)
// if nil != err {
//
// switch err.(type) {
// case utf8.NilWriterComplainer:
// //@TODO
// default:
// //TODO
// }
//
// }
2018-07-02 18:26:04 +00:00
func WriteRune(writer io.Writer, r rune) (int, error) {
if nil == writer {
return 0, errNilWriter
}
2018-07-02 09:37:29 +00:00
switch {
case 127 >= r:
var buffer [1]byte
buffer[0] = byte(r)
p := buffer[:]
2018-07-02 18:26:04 +00:00
return writer.Write(p)
2018-07-02 09:37:29 +00:00
case 0x7FF >= r:
var buffer [2]byte
buffer[0] = 0xC0 | byte((0x000007C0 & r) >> 6)
buffer[1] = 0x80 | byte( 0x0000003F & r)
p := buffer[:]
2018-07-02 18:26:04 +00:00
return writer.Write(p)
2018-07-02 09:37:29 +00:00
case 0xFFFF >= r:
var buffer [3]byte
buffer[0] = 0xE0 | byte((0x0000F000 & r) >> 12)
buffer[1] = 0x80 | byte((0x00000FC0 & r) >> 6)
buffer[2] = 0x80 | byte( 0x0000003F & r)
p := buffer[:]
2018-07-02 18:26:04 +00:00
return writer.Write(p)
2018-07-02 09:37:29 +00:00
case 0x10FFFF >= r:
var buffer [4]byte
buffer[0] = 0xF0 | byte((0x001C0000 & r) >> 18)
buffer[1] = 0x80 | byte((0x0003F000 & r) >> 12)
buffer[2] = 0x80 | byte((0x00000FC0 & r) >> 6)
buffer[3] = 0x80 | byte( 0x0000003F & r)
p := buffer[:]
2018-07-02 18:26:04 +00:00
return writer.Write(p)
2018-07-02 09:37:29 +00:00
default:
return 0, errInternalError
}
}