utf16 Encode Decode Surrogate Rules

Round-trip runes through unicode/utf16 and see IsSurrogate, Encode, and DecodeRune classify lone surrogates versus legal pairs.

GoData Integrity

Code

gosnippet
34 lines
package main

import (
	"fmt"
	"unicode/utf16"
)

func main() {
	// Encode:BMP 内字符 1 个码元,emoji 需要 2 个(代理对)
	text := []rune{'A', '中', '\U0001F600'}
	units := utf16.Encode(text)
	fmt.Println("runes:", len(text), "units:", len(units))
	fmt.Println("units:", units)

	// Decode:合法序列原样还原
	back := utf16.Decode(units)
	fmt.Println("decode roundtrip:", string(back) == string(text))

	// IsSurrogate 标记代理区间的码元:0xD800-0xDFFF
	fmt.Println("0xD800 is surrogate:", utf16.IsSurrogate(0xD800))
	fmt.Println("0x4E2D is surrogate:", utf16.IsSurrogate(0x4E2D))

	// 孤立代理 Decode 时还原成替换符,而不是 panic
	lone := []uint16{0xD800, 'B'}
	fmt.Printf("lone surrogate decode: %q\n", utf16.Decode(lone))

	// DecodeRune 单独解码一对码元:合法对返回码点与 true
	r1, ok1 := utf16.DecodeRune(0xD83D, 0xDE00)
	fmt.Printf("pair: %U valid: %t\n", r1, ok1)

	// 两个高代理不是合法对:返回替换符与 false
	r2, ok2 := utf16.DecodeRune(0xD800, 0xD800)
	fmt.Printf("bad pair: %U valid: %t\n", r2, ok2)
}

Surrogate pairs versus lone units

All decoding and classification happens in main; there is no other entry path.

Watch out for

  • The sole import is unicode/utf16, part of the standard library distribution.

Applying it

Execution begins at func main() and covers every utf16 helper in one pass

The run prints runes:, units:, decode roundtrip: — each prefix names the step that produced it.

The calls that classify

r1, ok1 := utf16.DecodeRune(0xD83D, 0xDE00)

Interactive Tools for This Topic

FAQ

What does utf16 Encode Decode Surrogate Rules print when run?
Invoke the file as-is — the `runes:`, `units:`, `decode roundtrip:` prefixes identify which step printed each line.