Skip to content

Commit a386802

Browse files
ainar-grasky
authored andcommitted
unicode/utf8: document the handling of runes out of range in EncodeRune
Document the way EncodeRune currently handles runes which are out of range. Also add an example showing that behaviour. Change-Id: I0f8e7645ae053474ec319085a2bb6d7f73bc137c Reviewed-on: https://go-review.googlesource.com/c/go/+/255998 Reviewed-by: Rob Pike <[email protected]> Reviewed-by: Giovanni Bajo <[email protected]> Trust: Giovanni Bajo <[email protected]> Run-TryBot: Giovanni Bajo <[email protected]> TryBot-Result: Go Bot <[email protected]>
1 parent 73eb24c commit a386802

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

src/unicode/utf8/example_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,26 @@ func ExampleEncodeRune() {
107107
// 3
108108
}
109109

110+
func ExampleEncodeRune_outOfRange() {
111+
runes := []rune{
112+
// Less than 0, out of range.
113+
-1,
114+
// Greater than 0x10FFFF, out of range.
115+
0x110000,
116+
// The Unicode replacement character.
117+
utf8.RuneError,
118+
}
119+
for i, c := range runes {
120+
buf := make([]byte, 3)
121+
size := utf8.EncodeRune(buf, c)
122+
fmt.Printf("%d: %d %[2]s %d\n", i, buf, size)
123+
}
124+
// Output:
125+
// 0: [239 191 189] � 3
126+
// 1: [239 191 189] � 3
127+
// 2: [239 191 189] � 3
128+
}
129+
110130
func ExampleFullRune() {
111131
buf := []byte{228, 184, 150} // 世
112132
fmt.Println(utf8.FullRune(buf))

src/unicode/utf8/utf8.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,7 @@ func RuneLen(r rune) int {
337337
}
338338

339339
// EncodeRune writes into p (which must be large enough) the UTF-8 encoding of the rune.
340+
// If the rune is out of range, it writes the encoding of RuneError.
340341
// It returns the number of bytes written.
341342
func EncodeRune(p []byte, r rune) int {
342343
// Negative values are erroneous. Making it unsigned addresses the problem.

0 commit comments

Comments
 (0)