Documentation
¶
Overview ¶
Package encoding implements the character encodings of the WHATWG Encoding Standard: finding an encoding by label, decoding bytes to text and encoding text to bytes, one-shot or streaming.
The shape follows what Go programmers know from text-encoding packages: an Encoding value hands out a Decoder and an Encoder, which convert whole slices and strings or wrap an io.Reader or io.Writer. Streaming is safe on any chunk boundary: splitting the input anywhere gives the same output as converting it whole.
Decoding never fails. Following the standard, a byte sequence the encoding cannot represent becomes U+FFFD and is counted in Result.Errors. Encoding uses the standard's "html" error mode: a character the encoding cannot hold is written as a decimal character reference such as "€", which is what HTML needs.
To find the encoding of an HTML document (byte order mark, transport label, <meta> prescan) use onehtml.SniffEncoding and look the answer up with Lookup; FromContentType reads a charset out of a Content-Type or <meta> content value on its own.
The package is pure Go and reads nothing but its arguments.
Index ¶
Examples ¶
Constants ¶
const DefaultMaxOffsetRuns = 16 << 20
DefaultMaxOffsetRuns is the number of offset-map runs Encoding.Decode allows unless WithMaxOffsetRuns says otherwise. A run is a stretch of text whose bytes map one-to-one onto source bytes, so only input that keeps changing between widths makes many.
const (
// LimitOffsetRuns is the size of the offset map ([WithMaxOffsetRuns]).
LimitOffsetRuns = "offset map runs"
)
The names a LimitError.Limit can hold.
Variables ¶
var ( // UTF8 is "UTF-8". UTF8 = Encoding{std.Utf8} // UTF16LE is "UTF-16LE". UTF16LE = Encoding{std.Utf16le} // UTF16BE is "UTF-16BE". UTF16BE = Encoding{std.Utf16be} // Windows1252 is "windows-1252", the label HTML falls back to and the // one the labels "latin1" and "ascii" name. Windows1252 = Encoding{std.Windows1252} )
The encodings most programs name directly. Every other encoding is reached through Lookup with any of its labels, or All.
var ErrLimit = limit.Err
ErrLimit is matched by errors.Is for every LimitError. It is the same value as onehtml.ErrLimit and css.ErrLimit.
Functions ¶
func All ¶
All yields every encoding of the standard, in the standard's own order (UTF-8, the legacy single-byte encodings, the multi-byte ones, then replacement, UTF-16BE, UTF-16LE and x-user-defined).
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml/encoding"
)
func main() {
n := 0
for e := range encoding.All() {
if e.Name() == "Big5" {
fmt.Println("has Big5")
}
n++
}
fmt.Println(n)
}
Output: has Big5 40
Types ¶
type DecodeOption ¶
type DecodeOption func(*decodeConfig)
DecodeOption configures Encoding.Decode and Encoding.NewDecoder.
func WithBOMSniffing ¶
func WithBOMSniffing(on bool) DecodeOption
WithBOMSniffing says whether a byte order mark is looked for. It is by default: the standard's "decode" runs, and a UTF-8, UTF-16BE or UTF-16LE byte order mark overrides the encoding and is removed. With false the decoder takes the encoding as given and decodes a byte order mark like any other bytes (U+FEFF in the Unicode encodings).
func WithMaxOffsetRuns ¶
func WithMaxOffsetRuns(n int) DecodeOption
WithMaxOffsetRuns bounds the offset map Encoding.Decode builds. Zero means DefaultMaxOffsetRuns and a negative n means no bound. When the bound is hit Decode returns a *LimitError. Streaming decoders keep no offset map and ignore it.
type Decoder ¶
type Decoder struct {
// contains filtered or unexported fields
}
A Decoder converts bytes in one encoding to UTF-8 text. It holds only configuration, so one Decoder may be used by many goroutines; the state of a stream lives in the io.Reader or io.WriteCloser it makes.
Decoding never fails: undecodable bytes become U+FFFD. Use Encoding.Decode when the count of such bytes or the offset map matters. ISO-2022-JP, whose meaning depends on escape sequences that can sit anywhere, is decoded when the stream ends rather than as it goes.
func (*Decoder) Reader ¶
Reader returns a reader of the text r's bytes decode to. Bytes may arrive in any pieces; a character split between two reads is joined, and the output is the same as for one read of everything. The underlying error, if any, is returned after all the text before it.
Example ¶
package main
import (
"fmt"
"io"
"recursiveai.org/go/onehtml/encoding"
)
func main() {
e, _ := encoding.Lookup("euc-jp")
src := e.Encode("日本語のテキスト")
// Read one byte at a time: characters split between reads are joined.
one := io.LimitReader(&slowReader{src}, int64(len(src)))
text, _ := io.ReadAll(e.NewDecoder().Reader(one))
fmt.Println(string(text))
}
type slowReader struct{ b []byte }
func (s *slowReader) Read(p []byte) (int, error) {
if len(s.b) == 0 {
return 0, io.EOF
}
p[0], s.b = s.b[0], s.b[1:]
return 1, nil
}
Output: 日本語のテキスト
func (*Decoder) Writer ¶
func (d *Decoder) Writer(w io.Writer) io.WriteCloser
Writer returns a writer that decodes the bytes written to it and writes the text to w. Close finishes the stream, writing whatever an incomplete ending decodes to; it does not close w. A Writer is not safe for concurrent use.
Example ¶
package main
import (
"fmt"
"os"
"recursiveai.org/go/onehtml/encoding"
)
func main() {
w := encoding.UTF16LE.NewDecoder().Writer(os.Stdout)
// "hé" in UTF-16LE, written in two pieces with a unit cut in half.
w.Write([]byte{'h', 0, 0xE9})
w.Write([]byte{0})
w.Close()
fmt.Println()
}
Output: hé
type Encoder ¶
type Encoder struct {
// contains filtered or unexported fields
}
An Encoder converts UTF-8 text to bytes in one encoding, in the standard's "html" error mode (see Encoding.Encode). It holds no state, so one Encoder may be used by many goroutines; stream state lives in the reader or writer it makes.
Text may arrive in any pieces, even with a character cut in two. ISO-2022-JP output, whose escape sequences depend on what came before, is produced when the stream ends rather than as it goes.
func (*Encoder) Reader ¶
Reader returns a reader of the bytes the text read from r encodes to. The underlying error, if any, is returned after everything before it.
func (*Encoder) Writer ¶
func (en *Encoder) Writer(w io.Writer) io.WriteCloser
Writer returns a writer that encodes the text written to it and writes the bytes to w. Close finishes the stream (an incomplete UTF-8 ending is written as U+FFFD, and ISO-2022-JP output returns to ASCII); it does not close w. A Writer is not safe for concurrent use.
Example ¶
package main
import (
"fmt"
"strings"
"recursiveai.org/go/onehtml/encoding"
)
func main() {
e, _ := encoding.Lookup("iso-2022-jp")
var sb strings.Builder
w := e.NewEncoder().Writer(&sb)
fmt.Fprint(w, "a日")
fmt.Fprint(w, "本b")
w.Close()
fmt.Printf("%q\n", sb.String())
}
Output: "a\x1b$BF|K\\\x1b(Bb"
type Encoding ¶
type Encoding struct {
// contains filtered or unexported fields
}
Encoding is one of the encodings of the Encoding Standard. Values are comparable and cheap to copy; the zero value is UTF-8.
func FromContentType ¶
FromContentType returns the encoding named by the charset parameter of a Content-Type value, or by a <meta http-equiv="content-type"> content attribute, as the HTML standard's "extracting a character encoding from a meta element" reads it. For example "text/html; charset=Shift_JIS" gives Shift_JIS. ok is false when there is no charset or its label is unknown.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml/encoding"
)
func main() {
e, ok := encoding.FromContentType("text/html; charset=Shift_JIS")
fmt.Println(e, ok)
}
Output: Shift_JIS true
func Lookup ¶
Lookup returns the encoding a label names, as the standard's "get an encoding" does: leading and trailing ASCII whitespace is ignored and ASCII case is folded. ok is false for a label no encoding has, including the empty label.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml/encoding"
)
func main() {
e, ok := encoding.Lookup(" Latin1 ")
fmt.Println(e, ok)
_, ok = encoding.Lookup("not-an-encoding")
fmt.Println(ok)
}
Output: windows-1252 true false
func (Encoding) Decode ¶
func (e Encoding) Decode(b []byte, opts ...DecodeOption) (Result, error)
Decode converts b to text with the standard's "decode": a byte order mark overrides e and is removed (see WithBOMSniffing), and bytes that are not valid in the encoding become U+FFFD. It returns the offset map with the text, so a position found in the text can be pointed at in the original bytes. Decode returns an error only for a *LimitError; the result is then the zero Result.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml/encoding"
)
func main() {
// A UTF-8 byte order mark overrides the label and is removed; the
// stray 0xFF is not valid UTF-8 and becomes U+FFFD, counted once.
res, err := encoding.Windows1252.Decode([]byte("\xef\xbb\xbfcaf\xc3\xa9 \xff"))
if err != nil {
panic(err)
}
fmt.Println(res.Encoding, res.BOMLength, res.Errors, res.Text)
// The "é" is at text offset 3; its bytes start at offset 6 of the input.
fmt.Println(res.Offsets.ByteOffset(3))
}
Output: UTF-8 3 1 café � 6
Example (Offsets) ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml/encoding"
)
func main() {
e, _ := encoding.Lookup("shift_jis")
// "ア" is one byte, 0xB1, in Shift_JIS and three bytes of UTF-8 text.
res, _ := e.Decode([]byte("a\xb1b"))
fmt.Println(res.Text, res.Offsets.ByteOffset(4), res.Offsets.TextOffset(2))
}
Output: aアb 2 4
func (Encoding) Encode ¶
Encode converts UTF-8 text to bytes in e, in the standard's "html" error mode: a character e cannot hold is written as a decimal character reference, "&#NNN;". Invalid UTF-8 in text is taken as U+FFFD. As the standard says, replacement and the UTF-16 encodings have no encoder of their own and write UTF-8. ISO-2022-JP output starts in ASCII and returns to it at the end.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/onehtml/encoding"
)
func main() {
e, _ := encoding.Lookup("windows-1252")
// The euro sign is byte 0x80; U+0100 has no place in windows-1252 and
// becomes a character reference, as HTML form submission does.
fmt.Printf("%q\n", e.Encode("€ Ā"))
}
Output: "\x80 Ā"
func (Encoding) Name ¶
Name returns the standard name of the encoding, for example "windows-1252" or "Shift_JIS". It is also what Lookup accepts back.
func (Encoding) NewDecoder ¶
func (e Encoding) NewDecoder(opts ...DecodeOption) *Decoder
NewDecoder returns a decoder for e. It runs the standard's "decode" unless WithBOMSniffing is false.
func (Encoding) NewEncoder ¶
NewEncoder returns an encoder for e.
type LimitError ¶
type LimitError struct {
// Limit names the bound: [LimitOffsetRuns].
Limit string
// Max is the bound that was exceeded.
Max int
}
LimitError reports that decoding would have needed more than a configured bound allowed. It matches ErrLimit.
type OffsetMap ¶
type OffsetMap struct {
// contains filtered or unexported fields
}
OffsetMap relates offsets in decoded text to offsets in the bytes it was decoded from. A nil *OffsetMap is the identity map.
func (*OffsetMap) ByteOffset ¶
ByteOffset returns the offset in the original bytes of the character at offset t of the decoded text. Inside a character whose bytes changed length it is where the character begins; an offset at or past the end of the text keeps its distance from the end of the bytes.
func (*OffsetMap) TextOffset ¶
TextOffset is the inverse of OffsetMap.ByteOffset: the offset in the decoded text of the character that byte offset b lies in. Bytes that produced no text, such as a byte order mark or an ISO-2022-JP escape sequence, map to the start of the character after them.
type Result ¶
type Result struct {
// Encoding is the encoding the bytes were decoded with, which a byte
// order mark can change from the one asked for.
Encoding Encoding
// Text is the decoded text, always valid UTF-8.
Text string
// Errors counts the U+FFFD characters the decoder wrote for bytes it
// could not decode. A U+FFFD that was in the input is not counted.
Errors int
// BOMLength is the number of bytes of byte order mark removed from the
// start of the input, 0 for none.
BOMLength int
// Offsets maps offsets in Text to offsets in the input and back.
Offsets *OffsetMap
}
Result is the outcome of Encoding.Decode.