encodeJSONString writes a string literal to buf as a JSON string. Cribbed from https://github.com/golang/go/blob/7badae85f20f1bce4cc344f9202447618d45d414/src/encoding/json/encode.go.
(buf *bytes.Buffer, s string)
| 544 | // encodeJSONString writes a string literal to buf as a JSON string. |
| 545 | // Cribbed from https://github.com/golang/go/blob/7badae85f20f1bce4cc344f9202447618d45d414/src/encoding/json/encode.go. |
| 546 | func encodeJSONString(buf *bytes.Buffer, s string) { |
| 547 | buf.WriteByte('"') |
| 548 | start := 0 |
| 549 | for i := 0; i < len(s); { |
| 550 | if b := s[i]; b < utf8.RuneSelf { |
| 551 | if safeSet[b] { |
| 552 | i++ |
| 553 | continue |
| 554 | } |
| 555 | if start < i { |
| 556 | buf.WriteString(s[start:i]) |
| 557 | } |
| 558 | switch b { |
| 559 | case '\\', '"': |
| 560 | buf.WriteByte('\\') |
| 561 | buf.WriteByte(b) |
| 562 | case '\n': |
| 563 | buf.WriteByte('\\') |
| 564 | buf.WriteByte('n') |
| 565 | case '\r': |
| 566 | buf.WriteByte('\\') |
| 567 | buf.WriteByte('r') |
| 568 | case '\t': |
| 569 | buf.WriteByte('\\') |
| 570 | buf.WriteByte('t') |
| 571 | default: |
| 572 | // This encodes bytes < 0x20 except for \t, \n and \r. |
| 573 | // If escapeHTML is set, it also escapes <, >, and & |
| 574 | // because they can lead to security holes when |
| 575 | // user-controlled strings are rendered into JSON |
| 576 | // and served to some browsers. |
| 577 | buf.WriteString(`\u00`) |
| 578 | buf.WriteByte(hexAlphabet[b>>4]) |
| 579 | buf.WriteByte(hexAlphabet[b&0xF]) |
| 580 | } |
| 581 | i++ |
| 582 | start = i |
| 583 | continue |
| 584 | } |
| 585 | c, size := utf8.DecodeRuneInString(s[i:]) |
| 586 | if c == utf8.RuneError && size == 1 { |
| 587 | if start < i { |
| 588 | buf.WriteString(s[start:i]) |
| 589 | } |
| 590 | buf.WriteString(`\ufffd`) |
| 591 | i += size |
| 592 | start = i |
| 593 | continue |
| 594 | } |
| 595 | i += size |
| 596 | } |
| 597 | if start < len(s) { |
| 598 | buf.WriteString(s[start:]) |
| 599 | } |
| 600 | buf.WriteByte('"') |
| 601 | } |
| 602 | |
| 603 | func (j jsonArray) Format(buf *bytes.Buffer) { |