| 1 | // Copyright 2026 The TCell Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package tty |
| 16 | |
| 17 | import ( |
| 18 | "unicode/utf16" |
| 19 | "unicode/utf8" |
| 20 | ) |
| 21 | |
| 22 | // decodeUTF16Rune decodes one UTF-16 code unit at a time while preserving |
| 23 | // malformed input as replacement characters instead of silently discarding it. |
| 24 | func decodeUTF16Rune(surrogate *rune, wc rune) []rune { |
| 25 | switch { |
| 26 | case wc >= 0xD800 && wc <= 0xDBFF: |
| 27 | if *surrogate != 0 { |
| 28 | *surrogate = wc |
| 29 | return []rune{utf8.RuneError} |
| 30 | } |
| 31 | *surrogate = wc |
| 32 | return nil |
| 33 | case wc >= 0xDC00 && wc <= 0xDFFF: |
| 34 | if *surrogate == 0 { |
| 35 | return []rune{utf8.RuneError} |
| 36 | } |
| 37 | decoded := utf16.DecodeRune(*surrogate, wc) |
| 38 | *surrogate = 0 |
| 39 | return []rune{decoded} |
| 40 | default: |
| 41 | if *surrogate != 0 { |
| 42 | *surrogate = 0 |
| 43 | return []rune{utf8.RuneError, wc} |
| 44 | } |
| 45 | return []rune{wc} |
| 46 | } |
| 47 | } |