handleProcInstEncoding replaces the encoding declaration in the processing instruction data with "UTF-8" and returns the updated data. It also recreates the reader with defined encoding.
(data []byte)
| 454 | // with "UTF-8" and returns the updated data. |
| 455 | // It also recreates the reader with defined encoding. |
| 456 | func (d *Decoder) handleProcInstEncoding(data []byte) []byte { |
| 457 | matches := encodingRE.FindSubmatch(data) |
| 458 | if matches == nil { |
| 459 | // No encoding declaration found, return original data without changes |
| 460 | return data |
| 461 | } |
| 462 | |
| 463 | // Get the encoding from the processing instruction data |
| 464 | encoding := bytes.Trim(matches[2], `"'`) |
| 465 | |
| 466 | if bytes.EqualFold(encoding, []byte("utf-8")) || bytes.EqualFold(encoding, []byte("utf8")) { |
| 467 | // No need for special handling if encoding is already UTF-8 |
| 468 | return data |
| 469 | } |
| 470 | |
| 471 | // Recreate the reader with defined encoding. |
| 472 | // If the encoding is UTF-16/32, we have already handled it in the BOM check. |
| 473 | if len(encoding) < 3 || !bytes.EqualFold(encoding[:3], []byte("utf")) { |
| 474 | if !d.setEncoding(string(encoding)) { |
| 475 | return data |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | // Build the updated data with "UTF-8" encoding. |
| 480 | // We write it to the buffer that already contains the processing instruction data, |
| 481 | // so we mark the position of the updated data start. |
| 482 | start := d.buf.Len() |
| 483 | d.buf.Write(matches[1]) // Up to encoding= |
| 484 | d.buf.Write([]byte(`"UTF-8"`)) // New encoding |
| 485 | d.buf.Write(matches[3]) // After encoding declaration |
| 486 | updated := d.buf.Bytes()[start:] |
| 487 | |
| 488 | return updated |
| 489 | } |
| 490 | |
| 491 | // readComment reads a comment (until `-->`). |
| 492 | func (d *Decoder) readComment() ([]byte, bool) { |
no test coverage detected