// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package unicode provides Unicode encodings such as UTF-16.
package unicode // import "golang.org/x/text/encoding/unicode" import ( ) // TODO: I think the Transformers really should return errors on unmatched // surrogate pairs and odd numbers of bytes. This is not required by RFC 2781, // which leaves it open, but is suggested by WhatWG. It will allow for all error // modes as defined by WhatWG: fatal, HTML and Replacement. This would require // the introduction of some kind of error type for conveying the erroneous code // point. // UTF8 is the UTF-8 encoding. It neither removes nor adds byte order marks. var UTF8 encoding.Encoding = utf8enc // UTF8BOM is an UTF-8 encoding where the decoder strips a leading byte order // mark while the encoder adds one. // // Some editors add a byte order mark as a signature to UTF-8 files. Although // the byte order mark is not useful for detecting byte order in UTF-8, it is // sometimes used as a convention to mark UTF-8-encoded files. This relies on // the observation that the UTF-8 byte order mark is either an illegal or at // least very unlikely sequence in any other character encoding. var UTF8BOM encoding.Encoding = utf8bomEncoding{} type utf8bomEncoding struct{} func (utf8bomEncoding) () string { return "UTF-8-BOM" } func (utf8bomEncoding) () (identifier.MIB, string) { return identifier.Unofficial, "x-utf8bom" } func (utf8bomEncoding) () *encoding.Encoder { return &encoding.Encoder{ Transformer: &utf8bomEncoder{t: runes.ReplaceIllFormed()}, } } func (utf8bomEncoding) () *encoding.Decoder { return &encoding.Decoder{Transformer: &utf8bomDecoder{}} } var utf8enc = &internal.Encoding{ &internal.SimpleEncoding{utf8Decoder{}, runes.ReplaceIllFormed()}, "UTF-8", identifier.UTF8, } type utf8bomDecoder struct { checked bool } func ( *utf8bomDecoder) () { .checked = false } func ( *utf8bomDecoder) (, []byte, bool) (, int, error) { if !.checked { if ! && len() < len(utf8BOM) { if len() == 0 { return 0, 0, nil } return 0, 0, transform.ErrShortSrc } if bytes.HasPrefix(, []byte(utf8BOM)) { += len(utf8BOM) = [len(utf8BOM):] } .checked = true } , , := utf8Decoder.Transform(utf8Decoder{}, [:], , ) += return , , } type utf8bomEncoder struct { written bool t transform.Transformer } func ( *utf8bomEncoder) () { .written = false .t.Reset() } func ( *utf8bomEncoder) (, []byte, bool) (, int, error) { if !.written { if len() < len(utf8BOM) { return , 0, transform.ErrShortDst } = copy(, utf8BOM) .written = true } , , := utf8Decoder.Transform(utf8Decoder{}, [:], , ) += return , , } type utf8Decoder struct{ transform.NopResetter } func (utf8Decoder) (, []byte, bool) (, int, error) { var int // point from which to start copy in src var utf8internal.AcceptRange // The decoder can only make the input larger, not smaller. := len() if len() < { = transform.ErrShortDst = len() = false } for < { := [] if < utf8.RuneSelf { ++ continue } := utf8internal.First[] := int( & utf8internal.SizeMask) if == utf8internal.FirstInvalid { goto // invalid starter byte } = utf8internal.AcceptRanges[>>utf8internal.AcceptShift] if + > { if ! { // We may stop earlier than necessary here if the short sequence // has invalid bytes. Not checking for this simplifies the code // and may avoid duplicate computations in certain conditions. if == nil { = transform.ErrShortSrc } break } // Determine the maximal subpart of an ill-formed subsequence. switch { case +1 >= || [+1] < .Lo || .Hi < [+1]: = 1 case +2 >= || [+2] < utf8internal.LoCB || utf8internal.HiCB < [+2]: = 2 default: = 3 // As we are short, the maximum is 3. } goto } if = [+1]; < .Lo || .Hi < { = 1 goto // invalid continuation byte } else if == 2 { } else if = [+2]; < utf8internal.LoCB || utf8internal.HiCB < { = 2 goto // invalid continuation byte } else if == 3 { } else if = [+3]; < utf8internal.LoCB || utf8internal.HiCB < { = 3 goto // invalid continuation byte } += continue : // Copy the scanned input so far. += copy([:], [:]) // Append RuneError to the destination. const = "\ufffd" if +len() > len() { return , , transform.ErrShortDst } += copy([:], ) // Skip the maximal subpart of an ill-formed subsequence according to // the W3C standard way instead of the Go way. This Transform is // probably the only place in the text repo where it is warranted. += = // Recompute the maximum source length. if := len() - ; < len()- { = transform.ErrShortDst = + = false } } return + copy([:], [:]), , } // UTF16 returns a UTF-16 Encoding for the given default endianness and byte // order mark (BOM) policy. // // When decoding from UTF-16 to UTF-8, if the BOMPolicy is IgnoreBOM then // neither BOMs U+FEFF nor noncharacters U+FFFE in the input stream will affect // the endianness used for decoding, and will instead be output as their // standard UTF-8 encodings: "\xef\xbb\xbf" and "\xef\xbf\xbe". If the BOMPolicy // is UseBOM or ExpectBOM a staring BOM is not written to the UTF-8 output. // Instead, it overrides the default endianness e for the remainder of the // transformation. Any subsequent BOMs U+FEFF or noncharacters U+FFFE will not // affect the endianness used, and will instead be output as their standard // UTF-8 encodings. For UseBOM, if there is no starting BOM, it will proceed // with the default Endianness. For ExpectBOM, in that case, the transformation // will return early with an ErrMissingBOM error. // // When encoding from UTF-8 to UTF-16, a BOM will be inserted at the start of // the output if the BOMPolicy is UseBOM or ExpectBOM. Otherwise, a BOM will not // be inserted. The UTF-8 input does not need to contain a BOM. // // There is no concept of a 'native' endianness. If the UTF-16 data is produced // and consumed in a greater context that implies a certain endianness, use // IgnoreBOM. Otherwise, use ExpectBOM and always produce and consume a BOM. // // In the language of https://www.unicode.org/faq/utf_bom.html#bom10, IgnoreBOM // corresponds to "Where the precise type of the data stream is known... the // BOM should not be used" and ExpectBOM corresponds to "A particular // protocol... may require use of the BOM". func ( Endianness, BOMPolicy) encoding.Encoding { return utf16Encoding{config{, }, mibValue[][&bomMask]} } // mibValue maps Endianness and BOMPolicy settings to MIB constants. Note that // some configurations map to the same MIB identifier. RFC 2781 has requirements // and recommendations. Some of the "configurations" are merely recommendations, // so multiple configurations could match. var mibValue = map[Endianness][numBOMValues]identifier.MIB{ BigEndian: [numBOMValues]identifier.MIB{ IgnoreBOM: identifier.UTF16BE, UseBOM: identifier.UTF16, // BigEnding default is preferred by RFC 2781. // TODO: acceptBOM | strictBOM would map to UTF16BE as well. }, LittleEndian: [numBOMValues]identifier.MIB{ IgnoreBOM: identifier.UTF16LE, UseBOM: identifier.UTF16, // LittleEndian default is allowed and preferred on Windows. // TODO: acceptBOM | strictBOM would map to UTF16LE as well. }, // ExpectBOM is not widely used and has no valid MIB identifier. } // All lists a configuration for each IANA-defined UTF-16 variant. var All = []encoding.Encoding{ UTF8, UTF16(BigEndian, UseBOM), UTF16(BigEndian, IgnoreBOM), UTF16(LittleEndian, IgnoreBOM), } // BOMPolicy is a UTF-16 encoding's byte order mark policy. type BOMPolicy uint8 const ( writeBOM BOMPolicy = 0x01 acceptBOM BOMPolicy = 0x02 requireBOM BOMPolicy = 0x04 bomMask BOMPolicy = 0x07 // HACK: numBOMValues == 8 triggers a bug in the 1.4 compiler (cannot have a // map of an array of length 8 of a type that is also used as a key or value // in another map). See golang.org/issue/11354. // TODO: consider changing this value back to 8 if the use of 1.4.* has // been minimized. numBOMValues = 8 + 1 // IgnoreBOM means to ignore any byte order marks. IgnoreBOM BOMPolicy = 0 // Common and RFC 2781-compliant interpretation for UTF-16BE/LE. // UseBOM means that the UTF-16 form may start with a byte order mark, which // will be used to override the default encoding. UseBOM BOMPolicy = writeBOM | acceptBOM // Common and RFC 2781-compliant interpretation for UTF-16. // ExpectBOM means that the UTF-16 form must start with a byte order mark, // which will be used to override the default encoding. ExpectBOM BOMPolicy = writeBOM | acceptBOM | requireBOM // Used in Java as Unicode (not to be confused with Java's UTF-16) and // ICU's UTF-16,version=1. Not compliant with RFC 2781. // TODO (maybe): strictBOM: BOM must match Endianness. This would allow: // - UTF-16(B|L)E,version=1: writeBOM | acceptBOM | requireBOM | strictBOM // (UnicodeBig and UnicodeLittle in Java) // - RFC 2781-compliant, but less common interpretation for UTF-16(B|L)E: // acceptBOM | strictBOM (e.g. assigned to CheckBOM). // This addition would be consistent with supporting ExpectBOM. ) // Endianness is a UTF-16 encoding's default endianness. type Endianness bool const ( // BigEndian is UTF-16BE. BigEndian Endianness = false // LittleEndian is UTF-16LE. LittleEndian Endianness = true ) // ErrMissingBOM means that decoding UTF-16 input with ExpectBOM did not find a // starting byte order mark. var ErrMissingBOM = errors.New("encoding: missing byte order mark") type utf16Encoding struct { config mib identifier.MIB } type config struct { endianness Endianness bomPolicy BOMPolicy } func ( utf16Encoding) () *encoding.Decoder { return &encoding.Decoder{Transformer: &utf16Decoder{ initial: .config, current: .config, }} } func ( utf16Encoding) () *encoding.Encoder { return &encoding.Encoder{Transformer: &utf16Encoder{ endianness: .endianness, initialBOMPolicy: .bomPolicy, currentBOMPolicy: .bomPolicy, }} } func ( utf16Encoding) () ( identifier.MIB, string) { return .mib, "" } func ( utf16Encoding) () string { , := "B", "" if .endianness == LittleEndian { = "L" } switch .bomPolicy { case ExpectBOM: = "Expect" case UseBOM: = "Use" case IgnoreBOM: = "Ignore" } return "UTF-16" + + "E (" + + " BOM)" } type utf16Decoder struct { initial config current config } func ( *utf16Decoder) () { .current = .initial } func ( *utf16Decoder) (, []byte, bool) (, int, error) { if len() < 2 && && .current.bomPolicy&requireBOM != 0 { return 0, 0, ErrMissingBOM } if len() == 0 { return 0, 0, nil } if len() >= 2 && .current.bomPolicy&acceptBOM != 0 { switch { case [0] == 0xfe && [1] == 0xff: .current.endianness = BigEndian = 2 case [0] == 0xff && [1] == 0xfe: .current.endianness = LittleEndian = 2 default: if .current.bomPolicy&requireBOM != 0 { return 0, 0, ErrMissingBOM } } .current.bomPolicy = IgnoreBOM } var rune var , int for < len() { if +1 < len() { := uint16([+0])<<8 | uint16([+1]) if .current.endianness == LittleEndian { = >>8 | <<8 } , = rune(), 2 if utf16.IsSurrogate() { if +3 < len() { = uint16([+2])<<8 | uint16([+3]) if .current.endianness == LittleEndian { = >>8 | <<8 } // Save for next iteration if it is not a high surrogate. if isHighSurrogate(rune()) { , = utf16.DecodeRune(, rune()), 4 } } else if ! { = transform.ErrShortSrc break } } if = utf8.RuneLen(); < 0 { , = utf8.RuneError, 3 } } else if { // Single trailing byte. , , = utf8.RuneError, 3, 1 } else { = transform.ErrShortSrc break } if + > len() { = transform.ErrShortDst break } += utf8.EncodeRune([:], ) += } return , , } func isHighSurrogate( rune) bool { return 0xDC00 <= && <= 0xDFFF } type utf16Encoder struct { endianness Endianness initialBOMPolicy BOMPolicy currentBOMPolicy BOMPolicy } func ( *utf16Encoder) () { .currentBOMPolicy = .initialBOMPolicy } func ( *utf16Encoder) (, []byte, bool) (, int, error) { if .currentBOMPolicy&writeBOM != 0 { if len() < 2 { return 0, 0, transform.ErrShortDst } [0], [1] = 0xfe, 0xff .currentBOMPolicy = IgnoreBOM = 2 } , := rune(0), 0 for < len() { = rune([]) // Decode a 1-byte rune. if < utf8.RuneSelf { = 1 } else { // Decode a multi-byte rune. , = utf8.DecodeRune([:]) if == 1 { // All valid runes of size 1 (those below utf8.RuneSelf) were // handled above. We have invalid UTF-8 or we haven't seen the // full character yet. if ! && !utf8.FullRune([:]) { = transform.ErrShortSrc break } } } if <= 0xffff { if +2 > len() { = transform.ErrShortDst break } [+0] = uint8( >> 8) [+1] = uint8() += 2 } else { if +4 > len() { = transform.ErrShortDst break } , := utf16.EncodeRune() [+0] = uint8( >> 8) [+1] = uint8() [+2] = uint8( >> 8) [+3] = uint8() += 4 } += } if .endianness == LittleEndian { for := 0; < ; += 2 { [], [+1] = [+1], [] } } return , , }