Path: blob/main/vendor/golang.org/x/text/encoding/unicode/unicode.go
2893 views
// Copyright 2013 The Go Authors. All rights reserved.1// Use of this source code is governed by a BSD-style2// license that can be found in the LICENSE file.34// Package unicode provides Unicode encodings such as UTF-16.5package unicode // import "golang.org/x/text/encoding/unicode"67import (8"bytes"9"errors"10"unicode/utf16"11"unicode/utf8"1213"golang.org/x/text/encoding"14"golang.org/x/text/encoding/internal"15"golang.org/x/text/encoding/internal/identifier"16"golang.org/x/text/internal/utf8internal"17"golang.org/x/text/runes"18"golang.org/x/text/transform"19)2021// TODO: I think the Transformers really should return errors on unmatched22// surrogate pairs and odd numbers of bytes. This is not required by RFC 2781,23// which leaves it open, but is suggested by WhatWG. It will allow for all error24// modes as defined by WhatWG: fatal, HTML and Replacement. This would require25// the introduction of some kind of error type for conveying the erroneous code26// point.2728// UTF8 is the UTF-8 encoding. It neither removes nor adds byte order marks.29var UTF8 encoding.Encoding = utf8enc3031// UTF8BOM is an UTF-8 encoding where the decoder strips a leading byte order32// mark while the encoder adds one.33//34// Some editors add a byte order mark as a signature to UTF-8 files. Although35// the byte order mark is not useful for detecting byte order in UTF-8, it is36// sometimes used as a convention to mark UTF-8-encoded files. This relies on37// the observation that the UTF-8 byte order mark is either an illegal or at38// least very unlikely sequence in any other character encoding.39var UTF8BOM encoding.Encoding = utf8bomEncoding{}4041type utf8bomEncoding struct{}4243func (utf8bomEncoding) String() string {44return "UTF-8-BOM"45}4647func (utf8bomEncoding) ID() (identifier.MIB, string) {48return identifier.Unofficial, "x-utf8bom"49}5051func (utf8bomEncoding) NewEncoder() *encoding.Encoder {52return &encoding.Encoder{53Transformer: &utf8bomEncoder{t: runes.ReplaceIllFormed()},54}55}5657func (utf8bomEncoding) NewDecoder() *encoding.Decoder {58return &encoding.Decoder{Transformer: &utf8bomDecoder{}}59}6061var utf8enc = &internal.Encoding{62&internal.SimpleEncoding{utf8Decoder{}, runes.ReplaceIllFormed()},63"UTF-8",64identifier.UTF8,65}6667type utf8bomDecoder struct {68checked bool69}7071func (t *utf8bomDecoder) Reset() {72t.checked = false73}7475func (t *utf8bomDecoder) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {76if !t.checked {77if !atEOF && len(src) < len(utf8BOM) {78if len(src) == 0 {79return 0, 0, nil80}81return 0, 0, transform.ErrShortSrc82}83if bytes.HasPrefix(src, []byte(utf8BOM)) {84nSrc += len(utf8BOM)85src = src[len(utf8BOM):]86}87t.checked = true88}89nDst, n, err := utf8Decoder.Transform(utf8Decoder{}, dst[nDst:], src, atEOF)90nSrc += n91return nDst, nSrc, err92}9394type utf8bomEncoder struct {95written bool96t transform.Transformer97}9899func (t *utf8bomEncoder) Reset() {100t.written = false101t.t.Reset()102}103104func (t *utf8bomEncoder) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {105if !t.written {106if len(dst) < len(utf8BOM) {107return nDst, 0, transform.ErrShortDst108}109nDst = copy(dst, utf8BOM)110t.written = true111}112n, nSrc, err := utf8Decoder.Transform(utf8Decoder{}, dst[nDst:], src, atEOF)113nDst += n114return nDst, nSrc, err115}116117type utf8Decoder struct{ transform.NopResetter }118119func (utf8Decoder) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {120var pSrc int // point from which to start copy in src121var accept utf8internal.AcceptRange122123// The decoder can only make the input larger, not smaller.124n := len(src)125if len(dst) < n {126err = transform.ErrShortDst127n = len(dst)128atEOF = false129}130for nSrc < n {131c := src[nSrc]132if c < utf8.RuneSelf {133nSrc++134continue135}136first := utf8internal.First[c]137size := int(first & utf8internal.SizeMask)138if first == utf8internal.FirstInvalid {139goto handleInvalid // invalid starter byte140}141accept = utf8internal.AcceptRanges[first>>utf8internal.AcceptShift]142if nSrc+size > n {143if !atEOF {144// We may stop earlier than necessary here if the short sequence145// has invalid bytes. Not checking for this simplifies the code146// and may avoid duplicate computations in certain conditions.147if err == nil {148err = transform.ErrShortSrc149}150break151}152// Determine the maximal subpart of an ill-formed subsequence.153switch {154case nSrc+1 >= n || src[nSrc+1] < accept.Lo || accept.Hi < src[nSrc+1]:155size = 1156case nSrc+2 >= n || src[nSrc+2] < utf8internal.LoCB || utf8internal.HiCB < src[nSrc+2]:157size = 2158default:159size = 3 // As we are short, the maximum is 3.160}161goto handleInvalid162}163if c = src[nSrc+1]; c < accept.Lo || accept.Hi < c {164size = 1165goto handleInvalid // invalid continuation byte166} else if size == 2 {167} else if c = src[nSrc+2]; c < utf8internal.LoCB || utf8internal.HiCB < c {168size = 2169goto handleInvalid // invalid continuation byte170} else if size == 3 {171} else if c = src[nSrc+3]; c < utf8internal.LoCB || utf8internal.HiCB < c {172size = 3173goto handleInvalid // invalid continuation byte174}175nSrc += size176continue177178handleInvalid:179// Copy the scanned input so far.180nDst += copy(dst[nDst:], src[pSrc:nSrc])181182// Append RuneError to the destination.183const runeError = "\ufffd"184if nDst+len(runeError) > len(dst) {185return nDst, nSrc, transform.ErrShortDst186}187nDst += copy(dst[nDst:], runeError)188189// Skip the maximal subpart of an ill-formed subsequence according to190// the W3C standard way instead of the Go way. This Transform is191// probably the only place in the text repo where it is warranted.192nSrc += size193pSrc = nSrc194195// Recompute the maximum source length.196if sz := len(dst) - nDst; sz < len(src)-nSrc {197err = transform.ErrShortDst198n = nSrc + sz199atEOF = false200}201}202return nDst + copy(dst[nDst:], src[pSrc:nSrc]), nSrc, err203}204205// UTF16 returns a UTF-16 Encoding for the given default endianness and byte206// order mark (BOM) policy.207//208// When decoding from UTF-16 to UTF-8, if the BOMPolicy is IgnoreBOM then209// neither BOMs U+FEFF nor noncharacters U+FFFE in the input stream will affect210// the endianness used for decoding, and will instead be output as their211// standard UTF-8 encodings: "\xef\xbb\xbf" and "\xef\xbf\xbe". If the BOMPolicy212// is UseBOM or ExpectBOM a staring BOM is not written to the UTF-8 output.213// Instead, it overrides the default endianness e for the remainder of the214// transformation. Any subsequent BOMs U+FEFF or noncharacters U+FFFE will not215// affect the endianness used, and will instead be output as their standard216// UTF-8 encodings. For UseBOM, if there is no starting BOM, it will proceed217// with the default Endianness. For ExpectBOM, in that case, the transformation218// will return early with an ErrMissingBOM error.219//220// When encoding from UTF-8 to UTF-16, a BOM will be inserted at the start of221// the output if the BOMPolicy is UseBOM or ExpectBOM. Otherwise, a BOM will not222// be inserted. The UTF-8 input does not need to contain a BOM.223//224// There is no concept of a 'native' endianness. If the UTF-16 data is produced225// and consumed in a greater context that implies a certain endianness, use226// IgnoreBOM. Otherwise, use ExpectBOM and always produce and consume a BOM.227//228// In the language of https://www.unicode.org/faq/utf_bom.html#bom10, IgnoreBOM229// corresponds to "Where the precise type of the data stream is known... the230// BOM should not be used" and ExpectBOM corresponds to "A particular231// protocol... may require use of the BOM".232func UTF16(e Endianness, b BOMPolicy) encoding.Encoding {233return utf16Encoding{config{e, b}, mibValue[e][b&bomMask]}234}235236// mibValue maps Endianness and BOMPolicy settings to MIB constants. Note that237// some configurations map to the same MIB identifier. RFC 2781 has requirements238// and recommendations. Some of the "configurations" are merely recommendations,239// so multiple configurations could match.240var mibValue = map[Endianness][numBOMValues]identifier.MIB{241BigEndian: [numBOMValues]identifier.MIB{242IgnoreBOM: identifier.UTF16BE,243UseBOM: identifier.UTF16, // BigEnding default is preferred by RFC 2781.244// TODO: acceptBOM | strictBOM would map to UTF16BE as well.245},246LittleEndian: [numBOMValues]identifier.MIB{247IgnoreBOM: identifier.UTF16LE,248UseBOM: identifier.UTF16, // LittleEndian default is allowed and preferred on Windows.249// TODO: acceptBOM | strictBOM would map to UTF16LE as well.250},251// ExpectBOM is not widely used and has no valid MIB identifier.252}253254// All lists a configuration for each IANA-defined UTF-16 variant.255var All = []encoding.Encoding{256UTF8,257UTF16(BigEndian, UseBOM),258UTF16(BigEndian, IgnoreBOM),259UTF16(LittleEndian, IgnoreBOM),260}261262// BOMPolicy is a UTF-16 encoding's byte order mark policy.263type BOMPolicy uint8264265const (266writeBOM BOMPolicy = 0x01267acceptBOM BOMPolicy = 0x02268requireBOM BOMPolicy = 0x04269bomMask BOMPolicy = 0x07270271// HACK: numBOMValues == 8 triggers a bug in the 1.4 compiler (cannot have a272// map of an array of length 8 of a type that is also used as a key or value273// in another map). See golang.org/issue/11354.274// TODO: consider changing this value back to 8 if the use of 1.4.* has275// been minimized.276numBOMValues = 8 + 1277278// IgnoreBOM means to ignore any byte order marks.279IgnoreBOM BOMPolicy = 0280// Common and RFC 2781-compliant interpretation for UTF-16BE/LE.281282// UseBOM means that the UTF-16 form may start with a byte order mark, which283// will be used to override the default encoding.284UseBOM BOMPolicy = writeBOM | acceptBOM285// Common and RFC 2781-compliant interpretation for UTF-16.286287// ExpectBOM means that the UTF-16 form must start with a byte order mark,288// which will be used to override the default encoding.289ExpectBOM BOMPolicy = writeBOM | acceptBOM | requireBOM290// Used in Java as Unicode (not to be confused with Java's UTF-16) and291// ICU's UTF-16,version=1. Not compliant with RFC 2781.292293// TODO (maybe): strictBOM: BOM must match Endianness. This would allow:294// - UTF-16(B|L)E,version=1: writeBOM | acceptBOM | requireBOM | strictBOM295// (UnicodeBig and UnicodeLittle in Java)296// - RFC 2781-compliant, but less common interpretation for UTF-16(B|L)E:297// acceptBOM | strictBOM (e.g. assigned to CheckBOM).298// This addition would be consistent with supporting ExpectBOM.299)300301// Endianness is a UTF-16 encoding's default endianness.302type Endianness bool303304const (305// BigEndian is UTF-16BE.306BigEndian Endianness = false307// LittleEndian is UTF-16LE.308LittleEndian Endianness = true309)310311// ErrMissingBOM means that decoding UTF-16 input with ExpectBOM did not find a312// starting byte order mark.313var ErrMissingBOM = errors.New("encoding: missing byte order mark")314315type utf16Encoding struct {316config317mib identifier.MIB318}319320type config struct {321endianness Endianness322bomPolicy BOMPolicy323}324325func (u utf16Encoding) NewDecoder() *encoding.Decoder {326return &encoding.Decoder{Transformer: &utf16Decoder{327initial: u.config,328current: u.config,329}}330}331332func (u utf16Encoding) NewEncoder() *encoding.Encoder {333return &encoding.Encoder{Transformer: &utf16Encoder{334endianness: u.endianness,335initialBOMPolicy: u.bomPolicy,336currentBOMPolicy: u.bomPolicy,337}}338}339340func (u utf16Encoding) ID() (mib identifier.MIB, other string) {341return u.mib, ""342}343344func (u utf16Encoding) String() string {345e, b := "B", ""346if u.endianness == LittleEndian {347e = "L"348}349switch u.bomPolicy {350case ExpectBOM:351b = "Expect"352case UseBOM:353b = "Use"354case IgnoreBOM:355b = "Ignore"356}357return "UTF-16" + e + "E (" + b + " BOM)"358}359360type utf16Decoder struct {361initial config362current config363}364365func (u *utf16Decoder) Reset() {366u.current = u.initial367}368369func (u *utf16Decoder) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {370if len(src) < 2 && atEOF && u.current.bomPolicy&requireBOM != 0 {371return 0, 0, ErrMissingBOM372}373if len(src) == 0 {374return 0, 0, nil375}376if len(src) >= 2 && u.current.bomPolicy&acceptBOM != 0 {377switch {378case src[0] == 0xfe && src[1] == 0xff:379u.current.endianness = BigEndian380nSrc = 2381case src[0] == 0xff && src[1] == 0xfe:382u.current.endianness = LittleEndian383nSrc = 2384default:385if u.current.bomPolicy&requireBOM != 0 {386return 0, 0, ErrMissingBOM387}388}389u.current.bomPolicy = IgnoreBOM390}391392var r rune393var dSize, sSize int394for nSrc < len(src) {395if nSrc+1 < len(src) {396x := uint16(src[nSrc+0])<<8 | uint16(src[nSrc+1])397if u.current.endianness == LittleEndian {398x = x>>8 | x<<8399}400r, sSize = rune(x), 2401if utf16.IsSurrogate(r) {402if nSrc+3 < len(src) {403x = uint16(src[nSrc+2])<<8 | uint16(src[nSrc+3])404if u.current.endianness == LittleEndian {405x = x>>8 | x<<8406}407// Save for next iteration if it is not a high surrogate.408if isHighSurrogate(rune(x)) {409r, sSize = utf16.DecodeRune(r, rune(x)), 4410}411} else if !atEOF {412err = transform.ErrShortSrc413break414}415}416if dSize = utf8.RuneLen(r); dSize < 0 {417r, dSize = utf8.RuneError, 3418}419} else if atEOF {420// Single trailing byte.421r, dSize, sSize = utf8.RuneError, 3, 1422} else {423err = transform.ErrShortSrc424break425}426if nDst+dSize > len(dst) {427err = transform.ErrShortDst428break429}430nDst += utf8.EncodeRune(dst[nDst:], r)431nSrc += sSize432}433return nDst, nSrc, err434}435436func isHighSurrogate(r rune) bool {437return 0xDC00 <= r && r <= 0xDFFF438}439440type utf16Encoder struct {441endianness Endianness442initialBOMPolicy BOMPolicy443currentBOMPolicy BOMPolicy444}445446func (u *utf16Encoder) Reset() {447u.currentBOMPolicy = u.initialBOMPolicy448}449450func (u *utf16Encoder) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {451if u.currentBOMPolicy&writeBOM != 0 {452if len(dst) < 2 {453return 0, 0, transform.ErrShortDst454}455dst[0], dst[1] = 0xfe, 0xff456u.currentBOMPolicy = IgnoreBOM457nDst = 2458}459460r, size := rune(0), 0461for nSrc < len(src) {462r = rune(src[nSrc])463464// Decode a 1-byte rune.465if r < utf8.RuneSelf {466size = 1467468} else {469// Decode a multi-byte rune.470r, size = utf8.DecodeRune(src[nSrc:])471if size == 1 {472// All valid runes of size 1 (those below utf8.RuneSelf) were473// handled above. We have invalid UTF-8 or we haven't seen the474// full character yet.475if !atEOF && !utf8.FullRune(src[nSrc:]) {476err = transform.ErrShortSrc477break478}479}480}481482if r <= 0xffff {483if nDst+2 > len(dst) {484err = transform.ErrShortDst485break486}487dst[nDst+0] = uint8(r >> 8)488dst[nDst+1] = uint8(r)489nDst += 2490} else {491if nDst+4 > len(dst) {492err = transform.ErrShortDst493break494}495r1, r2 := utf16.EncodeRune(r)496dst[nDst+0] = uint8(r1 >> 8)497dst[nDst+1] = uint8(r1)498dst[nDst+2] = uint8(r2 >> 8)499dst[nDst+3] = uint8(r2)500nDst += 4501}502nSrc += size503}504505if u.endianness == LittleEndian {506for i := 0; i < nDst; i += 2 {507dst[i], dst[i+1] = dst[i+1], dst[i]508}509}510return nDst, nSrc, err511}512513514