1 // Copyright 2010 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package utf16 implements encoding and decoding of UTF-16 sequences.
11 // 0xd800-0xdc00 encodes the high 10 bits of a pair.
12 // 0xdc00-0xe000 encodes the low 10 bits of a pair.
13 // the value is those 20 bits plus 0x10000.
21 // IsSurrogate returns true if the specified Unicode code point
22 // can appear in a surrogate pair.
23 func IsSurrogate(r rune) bool {
24 return surr1 <= r && r < surr3
27 // DecodeRune returns the UTF-16 decoding of a surrogate pair.
28 // If the pair is not a valid UTF-16 surrogate pair, DecodeRune returns
29 // the Unicode replacement code point U+FFFD.
30 func DecodeRune(r1, r2 rune) rune {
31 if surr1 <= r1 && r1 < surr2 && surr2 <= r2 && r2 < surr3 {
32 return (rune(r1)-surr1)<<10 | (rune(r2) - surr2) + 0x10000
34 return unicode.ReplacementChar
37 // EncodeRune returns the UTF-16 surrogate pair r1, r2 for the given rune.
38 // If the rune is not a valid Unicode code point or does not need encoding,
39 // EncodeRune returns U+FFFD, U+FFFD.
40 func EncodeRune(r rune) (r1, r2 rune) {
41 if r < surrSelf || r > unicode.MaxRune || IsSurrogate(r) {
42 return unicode.ReplacementChar, unicode.ReplacementChar
45 return surr1 + (r>>10)&0x3ff, surr2 + r&0x3ff
48 // Encode returns the UTF-16 encoding of the Unicode code point sequence s.
49 func Encode(s []rune) []uint16 {
57 a := make([]uint16, n)
61 case v < 0, surr1 <= v && v < surr3, v > unicode.MaxRune:
62 v = unicode.ReplacementChar
68 r1, r2 := EncodeRune(v)
77 // Decode returns the Unicode code point sequence represented
78 // by the UTF-16 encoding s.
79 func Decode(s []uint16) []rune {
80 a := make([]rune, len(s))
82 for i := 0; i < len(s); i++ {
84 case surr1 <= r && r < surr2 && i+1 < len(s) &&
85 surr2 <= s[i+1] && s[i+1] < surr3:
86 // valid surrogate sequence
87 a[n] = DecodeRune(rune(r), rune(s[i+1]))
90 case surr1 <= r && r < surr3:
91 // invalid surrogate sequence
92 a[n] = unicode.ReplacementChar