github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/x/text/encoding/unicode/unicode.go (about) 1 // Copyright 2013 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 unicode provides Unicode encodings such as UTF-16. 6 package unicode // import "github.com/insionng/yougam/libraries/x/text/encoding/unicode" 7 8 import ( 9 "errors" 10 "unicode/utf16" 11 "unicode/utf8" 12 13 "github.com/insionng/yougam/libraries/x/text/encoding" 14 "github.com/insionng/yougam/libraries/x/text/encoding/internal" 15 "github.com/insionng/yougam/libraries/x/text/encoding/internal/identifier" 16 "github.com/insionng/yougam/libraries/x/text/internal/utf8internal" 17 "github.com/insionng/yougam/libraries/x/text/runes" 18 "github.com/insionng/yougam/libraries/x/text/transform" 19 ) 20 21 // TODO: I think the Transformers really should return errors on unmatched 22 // 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 error 24 // modes as defined by WhatWG: fatal, HTML and Replacement. This would require 25 // the introduction of some kind of error type for conveying the erroneous code 26 // point. 27 28 // TODO: 29 // - Define UTF-32? 30 31 // UTF8 is the UTF-8 encoding. 32 var UTF8 encoding.Encoding = utf8enc 33 34 var utf8enc = &internal.Encoding{ 35 &internal.SimpleEncoding{utf8Decoder{}, runes.ReplaceIllFormed()}, 36 "UTF-8", 37 identifier.UTF8, 38 } 39 40 type utf8Decoder struct{ transform.NopResetter } 41 42 func (utf8Decoder) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { 43 var pSrc int // point from which to start copy in src 44 var accept utf8internal.AcceptRange 45 46 // The decoder can only make the input larger, not smaller. 47 n := len(src) 48 if len(dst) < n { 49 err = transform.ErrShortDst 50 n = len(dst) 51 atEOF = false 52 } 53 for nSrc < n { 54 c := src[nSrc] 55 if c < utf8.RuneSelf { 56 nSrc++ 57 continue 58 } 59 first := utf8internal.First[c] 60 size := int(first & utf8internal.SizeMask) 61 if first == utf8internal.FirstInvalid { 62 goto handleInvalid // invalid starter byte 63 } 64 accept = utf8internal.AcceptRanges[first>>utf8internal.AcceptShift] 65 if nSrc+size > n { 66 if !atEOF { 67 // We may stop earlier than necessary here if the short sequence 68 // has invalid bytes. Not checking for this simplifies the code 69 // and may avoid duplicate computations in certain conditions. 70 if err == nil { 71 err = transform.ErrShortSrc 72 } 73 break 74 } 75 // Determine the maximal subpart of an ill-formed subsequence. 76 switch { 77 case nSrc+1 >= n || src[nSrc+1] < accept.Lo || accept.Hi < src[nSrc+1]: 78 size = 1 79 case nSrc+2 >= n || src[nSrc+2] < utf8internal.LoCB || utf8internal.HiCB < src[nSrc+2]: 80 size = 2 81 default: 82 size = 3 // As we are short, the maximum is 3. 83 } 84 goto handleInvalid 85 } 86 if c = src[nSrc+1]; c < accept.Lo || accept.Hi < c { 87 size = 1 88 goto handleInvalid // invalid continuation byte 89 } else if size == 2 { 90 } else if c = src[nSrc+2]; c < utf8internal.LoCB || utf8internal.HiCB < c { 91 size = 2 92 goto handleInvalid // invalid continuation byte 93 } else if size == 3 { 94 } else if c = src[nSrc+3]; c < utf8internal.LoCB || utf8internal.HiCB < c { 95 size = 3 96 goto handleInvalid // invalid continuation byte 97 } 98 nSrc += size 99 continue 100 101 handleInvalid: 102 // Copy the scanned input so far. 103 nDst += copy(dst[nDst:], src[pSrc:nSrc]) 104 105 // Append RuneError to the destination. 106 const runeError = "\ufffd" 107 if nDst+len(runeError) > len(dst) { 108 return nDst, nSrc, transform.ErrShortDst 109 } 110 nDst += copy(dst[nDst:], runeError) 111 112 // Skip the maximal subpart of an ill-formed subsequence according to 113 // the W3C standard way instead of the Go way. This Transform is 114 // probably the only place in the text repo where it is warranted. 115 nSrc += size 116 pSrc = nSrc 117 118 // Recompute the maximum source length. 119 if sz := len(dst) - nDst; sz < len(src)-nSrc { 120 err = transform.ErrShortDst 121 n = nSrc + sz 122 atEOF = false 123 } 124 } 125 return nDst + copy(dst[nDst:], src[pSrc:nSrc]), nSrc, err 126 } 127 128 // UTF16 returns a UTF-16 Encoding for the given default endianness and byte 129 // order mark (BOM) policy. 130 // 131 // When decoding from UTF-16 to UTF-8, if the BOMPolicy is IgnoreBOM then 132 // neither BOMs U+FEFF nor noncharacters U+FFFE in the input stream will affect 133 // the endianness used for decoding, and will instead be output as their 134 // standard UTF-8 encodings: "\xef\xbb\xbf" and "\xef\xbf\xbe". If the BOMPolicy 135 // is UseBOM or ExpectBOM a staring BOM is not written to the UTF-8 output. 136 // Instead, it overrides the default endianness e for the remainder of the 137 // transformation. Any subsequent BOMs U+FEFF or noncharacters U+FFFE will not 138 // affect the endianness used, and will instead be output as their standard 139 // UTF-8 encodings. For UseBOM, if there is no starting BOM, it will proceed 140 // with the default Endianness. For ExpectBOM, in that case, the transformation 141 // will return early with an ErrMissingBOM error. 142 // 143 // When encoding from UTF-8 to UTF-16, a BOM will be inserted at the start of 144 // the output if the BOMPolicy is UseBOM or ExpectBOM. Otherwise, a BOM will not 145 // be inserted. The UTF-8 input does not need to contain a BOM. 146 // 147 // There is no concept of a 'native' endianness. If the UTF-16 data is produced 148 // and consumed in a greater context that implies a certain endianness, use 149 // IgnoreBOM. Otherwise, use ExpectBOM and always produce and consume a BOM. 150 // 151 // In the language of http://www.unicode.org/faq/utf_bom.html#bom10, IgnoreBOM 152 // corresponds to "Where the precise type of the data stream is known... the 153 // BOM should not be used" and ExpectBOM corresponds to "A particular 154 // protocol... may require use of the BOM". 155 func UTF16(e Endianness, b BOMPolicy) encoding.Encoding { 156 return utf16Encoding{config{e, b}, mibValue[e][b&bomMask]} 157 } 158 159 // mibValue maps Endianness and BOMPolicy settings to MIB constants. Note that 160 // some configurations map to the same MIB identifier. RFC 2781 has requirements 161 // and recommendations. Some of the "configurations" are merely recommendations, 162 // so multiple configurations could match. 163 var mibValue = map[Endianness][numBOMValues]identifier.MIB{ 164 BigEndian: [numBOMValues]identifier.MIB{ 165 IgnoreBOM: identifier.UTF16BE, 166 UseBOM: identifier.UTF16, // BigEnding default is preferred by RFC 2781. 167 // TODO: acceptBOM | strictBOM would map to UTF16BE as well. 168 }, 169 LittleEndian: [numBOMValues]identifier.MIB{ 170 IgnoreBOM: identifier.UTF16LE, 171 UseBOM: identifier.UTF16, // LittleEndian default is allowed and preferred on Windows. 172 // TODO: acceptBOM | strictBOM would map to UTF16LE as well. 173 }, 174 // ExpectBOM is not widely used and has no valid MIB identifier. 175 } 176 177 // All lists a configuration for each IANA-defined UTF-16 variant. 178 var All = []encoding.Encoding{ 179 UTF8, 180 UTF16(BigEndian, UseBOM), 181 UTF16(BigEndian, IgnoreBOM), 182 UTF16(LittleEndian, IgnoreBOM), 183 } 184 185 // BOMPolicy is a UTF-16 encoding's byte order mark policy. 186 type BOMPolicy uint8 187 188 const ( 189 writeBOM BOMPolicy = 0x01 190 acceptBOM BOMPolicy = 0x02 191 requireBOM BOMPolicy = 0x04 192 bomMask BOMPolicy = 0x07 193 194 // HACK: numBOMValues == 8 triggers a bug in the 1.4 compiler (cannot have a 195 // map of an array of length 8 of a type that is also used as a key or value 196 // in another map). See yougam/libraries/issue/11354. 197 // TODO: consider changing this value back to 8 if the use of 1.4.* has 198 // been minimized. 199 numBOMValues = 8 + 1 200 201 // IgnoreBOM means to ignore any byte order marks. 202 IgnoreBOM BOMPolicy = 0 203 // Common and RFC 2781-compliant interpretation for UTF-16BE/LE. 204 205 // UseBOM means that the UTF-16 form may start with a byte order mark, which 206 // will be used to override the default encoding. 207 UseBOM BOMPolicy = writeBOM | acceptBOM 208 // Common and RFC 2781-compliant interpretation for UTF-16. 209 210 // ExpectBOM means that the UTF-16 form must start with a byte order mark, 211 // which will be used to override the default encoding. 212 ExpectBOM BOMPolicy = writeBOM | acceptBOM | requireBOM 213 // Used in Java as Unicode (not to be confused with Java's UTF-16) and 214 // ICU's UTF-16,version=1. Not compliant with RFC 2781. 215 216 // TODO (maybe): strictBOM: BOM must match Endianness. This would allow: 217 // - UTF-16(B|L)E,version=1: writeBOM | acceptBOM | requireBOM | strictBOM 218 // (UnicodeBig and UnicodeLittle in Java) 219 // - RFC 2781-compliant, but less common interpretation for UTF-16(B|L)E: 220 // acceptBOM | strictBOM (e.g. assigned to CheckBOM). 221 // This addition would be consistent with supporting ExpectBOM. 222 ) 223 224 // Endianness is a UTF-16 encoding's default endianness. 225 type Endianness bool 226 227 const ( 228 // BigEndian is UTF-16BE. 229 BigEndian Endianness = false 230 // LittleEndian is UTF-16LE. 231 LittleEndian Endianness = true 232 ) 233 234 // ErrMissingBOM means that decoding UTF-16 input with ExpectBOM did not find a 235 // starting byte order mark. 236 var ErrMissingBOM = errors.New("encoding: missing byte order mark") 237 238 type utf16Encoding struct { 239 config 240 mib identifier.MIB 241 } 242 243 type config struct { 244 endianness Endianness 245 bomPolicy BOMPolicy 246 } 247 248 func (u utf16Encoding) NewDecoder() *encoding.Decoder { 249 return &encoding.Decoder{Transformer: &utf16Decoder{ 250 initial: u.config, 251 current: u.config, 252 }} 253 } 254 255 func (u utf16Encoding) NewEncoder() *encoding.Encoder { 256 return &encoding.Encoder{Transformer: &utf16Encoder{ 257 endianness: u.endianness, 258 initialBOMPolicy: u.bomPolicy, 259 currentBOMPolicy: u.bomPolicy, 260 }} 261 } 262 263 func (u utf16Encoding) ID() (mib identifier.MIB, other string) { 264 return u.mib, "" 265 } 266 267 func (u utf16Encoding) String() string { 268 e, b := "B", "" 269 if u.endianness == LittleEndian { 270 e = "L" 271 } 272 switch u.bomPolicy { 273 case ExpectBOM: 274 b = "Expect" 275 case UseBOM: 276 b = "Use" 277 case IgnoreBOM: 278 b = "Ignore" 279 } 280 return "UTF-16" + e + "E (" + b + " BOM)" 281 } 282 283 type utf16Decoder struct { 284 initial config 285 current config 286 } 287 288 func (u *utf16Decoder) Reset() { 289 u.current = u.initial 290 } 291 292 func (u *utf16Decoder) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { 293 if u.current.bomPolicy&acceptBOM != 0 { 294 if len(src) < 2 { 295 return 0, 0, transform.ErrShortSrc 296 } 297 switch { 298 case src[0] == 0xfe && src[1] == 0xff: 299 u.current.endianness = BigEndian 300 nSrc = 2 301 case src[0] == 0xff && src[1] == 0xfe: 302 u.current.endianness = LittleEndian 303 nSrc = 2 304 default: 305 if u.current.bomPolicy&requireBOM != 0 { 306 return 0, 0, ErrMissingBOM 307 } 308 } 309 u.current.bomPolicy = IgnoreBOM 310 } 311 312 var r rune 313 var dSize, sSize int 314 for nSrc < len(src) { 315 if nSrc+1 < len(src) { 316 x := uint16(src[nSrc+0])<<8 | uint16(src[nSrc+1]) 317 if u.current.endianness == LittleEndian { 318 x = x>>8 | x<<8 319 } 320 r, sSize = rune(x), 2 321 if utf16.IsSurrogate(r) { 322 if nSrc+3 < len(src) { 323 x = uint16(src[nSrc+2])<<8 | uint16(src[nSrc+3]) 324 if u.current.endianness == LittleEndian { 325 x = x>>8 | x<<8 326 } 327 // Save for next iteration if it is not a high surrogate. 328 if isHighSurrogate(rune(x)) { 329 r, sSize = utf16.DecodeRune(r, rune(x)), 4 330 } 331 } else if !atEOF { 332 err = transform.ErrShortSrc 333 break 334 } 335 } 336 if dSize = utf8.RuneLen(r); dSize < 0 { 337 r, dSize = utf8.RuneError, 3 338 } 339 } else if atEOF { 340 // Single trailing byte. 341 r, dSize, sSize = utf8.RuneError, 3, 1 342 } else { 343 err = transform.ErrShortSrc 344 break 345 } 346 if nDst+dSize > len(dst) { 347 err = transform.ErrShortDst 348 break 349 } 350 nDst += utf8.EncodeRune(dst[nDst:], r) 351 nSrc += sSize 352 } 353 return nDst, nSrc, err 354 } 355 356 func isHighSurrogate(r rune) bool { 357 return 0xDC00 <= r && r <= 0xDFFF 358 } 359 360 type utf16Encoder struct { 361 endianness Endianness 362 initialBOMPolicy BOMPolicy 363 currentBOMPolicy BOMPolicy 364 } 365 366 func (u *utf16Encoder) Reset() { 367 u.currentBOMPolicy = u.initialBOMPolicy 368 } 369 370 func (u *utf16Encoder) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { 371 if u.currentBOMPolicy&writeBOM != 0 { 372 if len(dst) < 2 { 373 return 0, 0, transform.ErrShortDst 374 } 375 dst[0], dst[1] = 0xfe, 0xff 376 u.currentBOMPolicy = IgnoreBOM 377 nDst = 2 378 } 379 380 r, size := rune(0), 0 381 for nSrc < len(src) { 382 r = rune(src[nSrc]) 383 384 // Decode a 1-byte rune. 385 if r < utf8.RuneSelf { 386 size = 1 387 388 } else { 389 // Decode a multi-byte rune. 390 r, size = utf8.DecodeRune(src[nSrc:]) 391 if size == 1 { 392 // All valid runes of size 1 (those below utf8.RuneSelf) were 393 // handled above. We have invalid UTF-8 or we haven't seen the 394 // full character yet. 395 if !atEOF && !utf8.FullRune(src[nSrc:]) { 396 err = transform.ErrShortSrc 397 break 398 } 399 } 400 } 401 402 if r <= 0xffff { 403 if nDst+2 > len(dst) { 404 err = transform.ErrShortDst 405 break 406 } 407 dst[nDst+0] = uint8(r >> 8) 408 dst[nDst+1] = uint8(r) 409 nDst += 2 410 } else { 411 if nDst+4 > len(dst) { 412 err = transform.ErrShortDst 413 break 414 } 415 r1, r2 := utf16.EncodeRune(r) 416 dst[nDst+0] = uint8(r1 >> 8) 417 dst[nDst+1] = uint8(r1) 418 dst[nDst+2] = uint8(r2 >> 8) 419 dst[nDst+3] = uint8(r2) 420 nDst += 4 421 } 422 nSrc += size 423 } 424 425 if u.endianness == LittleEndian { 426 for i := 0; i < nDst; i += 2 { 427 dst[i], dst[i+1] = dst[i+1], dst[i] 428 } 429 } 430 return nDst, nSrc, err 431 }