| 1 | // Copyright 2014 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. |
| 4 | |
| 5 | package seq |
| 6 | |
| 7 | import "unicode/utf16" |
| 8 | |
| 9 | // Based heavily on package unicode/utf16 from the Go standard library. |
| 10 | |
| 11 | const ( |
| 12 | replacementChar = '\uFFFD' // Unicode replacement character |
| 13 | maxRune = '\U0010FFFF' // Maximum valid Unicode code point. |
| 14 | ) |
| 15 | |
| 16 | const ( |
| 17 | // 0xd800-0xdc00 encodes the high 10 bits of a pair. |
| 18 | // 0xdc00-0xe000 encodes the low 10 bits of a pair. |
| 19 | // the value is those 20 bits plus 0x10000. |
| 20 | surr1 = 0xd800 |
| 21 | surr2 = 0xdc00 |
| 22 | surr3 = 0xe000 |
| 23 | |
| 24 | surrSelf = 0x10000 |
| 25 | ) |
| 26 | |
| 27 | // UTF16Encode utf16 encodes s into chars. It returns the resulting |
| 28 | // length in units of uint16. It is assumed that the chars slice |
| 29 | // has enough room for the encoded string. |
| 30 | func UTF16Encode(s string, chars []uint16) int { |
| 31 | n := 0 |
| 32 | for _, v := range s { |
| 33 | switch { |
| 34 | case v < 0, surr1 <= v && v < surr3, v > maxRune: |
| 35 | v = replacementChar |
| 36 | fallthrough |
| 37 | case v < surrSelf: |
| 38 | chars[n] = uint16(v) |
| 39 | n += 1 |
| 40 | default: |
| 41 | // surrogate pair, two uint16 values |
| 42 | r1, r2 := utf16.EncodeRune(v) |
| 43 | chars[n] = uint16(r1) |
| 44 | chars[n+1] = uint16(r2) |
| 45 | n += 2 |
| 46 | } |
| 47 | } |
| 48 | return n |
| 49 | } |