Documentation
¶
Overview ¶
Package xmlscan is a streaming pull tokenizer for XML.
- It does not allocate per token. Names, attribute values and text are slices of the scanner's window, valid until the next call to Next.
- It reads through a window that is refilled as it goes, so input of any size is read in bounded memory. Text, CDATA and comments are delivered in chunks when they do not fit; a tag, a processing instruction and the document type declaration must fit, up to Options.MaxTokenBytes. Windows are pooled: Release hands one back.
- It reads UTF-8, UTF-16 and what an XML declaration names, decoded by go-fast-core/charset (encoding.go).
- It resolves namespace prefixes, to the URI and to small numbers the caller chooses.
- It never reads anything but its input. General entity references other than the five predefined ones are given to Options.Resolve, and a replacement read as markup is read from memory, within a bound on nesting and on the bytes all expansions produce together.
- By default it reads well-formed XML and stops with ErrSyntax at the first error. With Options.Recover it reads on through damaged markup the way a lenient reader does and counts each repair: an end tag that matches an element further out closes what is inside it, one that matches nothing is dropped, elements left open at the end are closed, a "<" or "&" that starts no markup is text, an attribute without a value or quotes is read as far as it goes, and elements nested deeper than Options.MaxDepth are read as part of their ancestor (their tags passed over, their text kept).
- Comments, processing instructions and the document type declaration are tokens with Options.Markup; otherwise they are passed over, and a document type declaration is accepted only if it declares nothing (no internal subset, before the root, only one).
Index ¶
- Constants
- Variables
- func UTF8(r io.Reader) (utf8 io.Reader, converted bool, err error)
- type Binding
- type Kind
- type Options
- type Resolution
- type Resolver
- type Scanner
- func (s *Scanner) Abort(err error)
- func (s *Scanner) AppendText(dst []byte) []byte
- func (s *Scanner) Attr(space Space, local string) ([]byte, bool)
- func (s *Scanner) AttrAny(local string) ([]byte, bool)
- func (s *Scanner) AttrAt(i int) (space Space, local, value []byte)
- func (s *Scanner) AttrNameAt(i int) []byte
- func (s *Scanner) AttrURI(uri, local string) ([]byte, bool)
- func (s *Scanner) AttrURIAt(i int) (uri, local, value []byte)
- func (s *Scanner) Depth() int
- func (s *Scanner) Err() error
- func (s *Scanner) Final() bool
- func (s *Scanner) InEntity() bool
- func (s *Scanner) Is(space Space, local string) bool
- func (s *Scanner) Kind() Kind
- func (s *Scanner) Local() []byte
- func (s *Scanner) Name() []byte
- func (s *Scanner) Next() Kind
- func (s *Scanner) NumAttr() int
- func (s *Scanner) Offset() int64
- func (s *Scanner) Release()
- func (s *Scanner) Reset(r io.Reader, opts *Options)
- func (s *Scanner) ResetBytes(data []byte, opts *Options)
- func (s *Scanner) SetResolver(r Resolver)
- func (s *Scanner) Skip() bool
- func (s *Scanner) Space() Space
- func (s *Scanner) Span() (start, end int64)
- func (s *Scanner) Target() []byte
- func (s *Scanner) Text() []byte
- func (s *Scanner) URI() []byte
- type Space
- type Stats
Constants ¶
const ( XMLNamespace = "http://www.w3.org/XML/1998/namespace" XMLNSNamespace = "http://www.w3.org/2000/xmlns/" )
The namespaces bound to the reserved prefixes.
const ( DefaultMaxDepth = 512 DefaultMaxTokenBytes = 16 << 20 DefaultBufferSize = 64 << 10 DefaultMaxAttrs = 1024 DefaultMaxEntityDepth = 16 // MaxEntityName is the longest entity name looked up. A longer one is // not read as a reference. MaxEntityName = 64 // DefaultMaxValueBytes is a bound on one decoded attribute value for // XML from anywhere (Options.MaxValueBytes). DefaultMaxValueBytes = 1 << 20 // MaxNameKept bounds the bytes of an open element's name that are // kept, for its End token and for matching its end tag (two names // longer than this match when their kept starts and lengths do). // The Start token has the whole name; the End token of a longer one // has its first MaxNameKept bytes or fewer, cut where a character // starts. MaxNameKept = 1024 // MaxBindingBytes bounds the prefixes and URIs of the namespace // declarations in scope. MaxBindingBytes = 16 << 20 )
Defaults for Options.
const MaxChunk = 64 << 10
MaxChunk bounds the text of one Text or Comment token read from the input: longer character data, CDATA sections and comments come in pieces, cut at white space where there is some. A consumer that puts block boundaries only between tokens then has a source offset for each.
const Poisoned = poison
Poisoned reports whether the xmlscanpoison tag is set.
Variables ¶
var ( ErrSyntax = errors.New("xmlscan: malformed XML") // ErrDTD: without Options.Markup, a document type declaration with an // internal subset, after the root element has begun, or a second one. ErrDTD = errors.New("xmlscan: a document type declaration with an internal subset, or out of place, is not accepted") // ErrDepth: without Options.Recover, elements nested deeper than // Options.MaxDepth. ErrDepth = errors.New("xmlscan: elements nested too deeply") // ErrTokenTooLarge: a tag, a processing instruction or the document // type declaration is larger than Options.MaxTokenBytes. ErrTokenTooLarge = errors.New("xmlscan: a tag is larger than the token limit") // ErrEncoding: an XML declaration names an encoding that is not // decoded. ErrEncoding = errors.New("xmlscan: unsupported character encoding") )
Errors reported by Err. Syntax errors wrap ErrSyntax and carry the byte offset.
var ErrReferenceTooLarge = fmt.Errorf("%w: a character reference", ErrTokenTooLarge)
ErrReferenceTooLarge is the ErrTokenTooLarge of a character reference longer than the token limit (leading zeros); errors.Is matches both.
Functions ¶
Types ¶
type Binding ¶
type Binding struct{ Prefix, URI string }
Binding declares a namespace: Prefix is "" for the default namespace.
type Kind ¶
type Kind uint8
Kind is the type of a token.
const ( // EOF means the input ended or an error occurred. Err tells which. EOF Kind = iota // Start is a start tag. An empty-element tag (<a/>) gives Start and // then End. Start // End is an end tag. End // Text is character data or a CDATA section. One run of text in the // source may arrive as several Text tokens. Text // Comment is the content of a comment. A long comment arrives as // several Comment tokens; Final reports the last one. Comment // PI is a processing instruction: Target and Text. PI // Doctype is a document type declaration. Text is what lies between // "<!DOCTYPE" and the final ">". Doctype )
type Options ¶
type Options struct {
// Spaces maps namespace URIs to the caller's numbers. It is only read.
Spaces map[string]Space
// MaxDepth bounds element nesting. Deeper is ErrDepth, or, with
// Recover, an element read as part of its ancestor and counted in
// Stats.Flattened. Zero means DefaultMaxDepth.
MaxDepth int
// MaxTokenBytes bounds the size of one tag, processing instruction or
// document type declaration. Zero means DefaultMaxTokenBytes.
MaxTokenBytes int
// MaxAttrs bounds the attributes kept from one tag; the rest are
// counted in Stats.AttrsCut. Zero means DefaultMaxAttrs.
MaxAttrs int
// BufferSize is the initial window size when reading from an
// io.Reader. Zero means DefaultBufferSize.
BufferSize int
// Resolve decides general entity references other than the
// predefined ones. Nil keeps them as written, counted as repairs.
Resolve Resolver
// MaxEntityDepth bounds how deeply replacements read as markup nest.
// Zero means DefaultMaxEntityDepth.
MaxEntityDepth int
// ExpansionLimit bounds the bytes of replacement text read in place
// of references, all expansions together. Zero means no expansion at
// all; negative means no limit.
ExpansionLimit int64
// BaseOffset is the offset of the first byte read, added to every
// offset the scanner reports.
BaseOffset int64
// MaxValueBytes bounds one decoded attribute value; a longer one is
// cut and counted in Stats.ValuesCut. Zero means no bound but
// MaxTokenBytes (DefaultMaxValueBytes is a bound for XML from
// anywhere).
MaxValueBytes int
// Interrupt, if set, is called every 1,024 constructs Next passes
// over without making a token; an error it returns ends the scan.
Interrupt func() error
// Recover makes the scanner read on through damaged markup (see the
// package documentation), counting each repair in Stats.Repairs.
// Without it the first error ends the scan with ErrSyntax.
Recover bool
// Markup makes comments, processing instructions and the document
// type declaration tokens (Comment, PI, Doctype). Without it they are
// passed over, and a document type declaration is accepted only if it
// declares nothing.
Markup bool
// Decoded says the input is UTF-8 already, whatever its XML
// declaration says: it was decoded on the way in.
Decoded bool
// Spans makes Span report where each token is in the input. Without
// it, Span reports it only for Comment, PI and Doctype tokens and
// markup kept as text.
Spans bool
// Bindings are namespace declarations in scope before the input's
// first element, as if an element around it had made them. They are
// for XML read out of a larger document, such as a part of a Flat OPC
// package, which may use a prefix that an ancestor in that document
// declares.
Bindings []Binding
}
Options configures a Scanner. The zero value is usable.
type Resolution ¶
type Resolution uint8
Resolution says how a general entity reference is read.
const ( // Keep keeps the reference in the text as written. Keep Resolution = iota // Insert puts the replacement in the text as it is, as characters. Insert // Expand reads the replacement in place of the reference, as markup. Expand )
type Resolver ¶
type Resolver func(name []byte) (repl []byte, how Resolution)
Resolver decides how a general entity reference other than the five predefined ones is read, and gives its replacement.
type Scanner ¶
type Scanner struct {
// Stats counts repairs, cuts and expansion.
Stats Stats
// contains filtered or unexported fields
}
Scanner reads XML tokens. Create one with New or NewBytes, or reuse one with Reset or ResetBytes, which keeps its buffers.
func (*Scanner) Abort ¶
Abort ends the scan: from now on Next returns EOF and Err returns err, unless the scan had failed already.
func (*Scanner) AppendText ¶
AppendText reads to the end of the element whose Start token is current and appends all character data inside it, at any depth, to dst.
func (*Scanner) Attr ¶
Attr returns the value of the attribute with the given namespace and local name on the current Start token. An attribute written without a prefix has namespace NoSpace. The value has references decoded, is valid UTF-8 as Text is, and is good until the next call to Next.
func (*Scanner) AttrAny ¶
AttrAny returns the value of the first attribute with the given local name, whatever its namespace. It is for attributes that producers write both with and without a prefix.
func (*Scanner) AttrAt ¶
AttrAt returns the i-th attribute of the current Start token: its namespace, local name and decoded value. A namespace declaration's namespace is that of the prefix "xmlns" (SpaceUnknown), or NoSpace for the default namespace's.
func (*Scanner) AttrNameAt ¶
AttrNameAt returns the qualified name of the i-th attribute of the current Start token as written in the source, prefix included. It is valid UTF-8 as Name is.
func (*Scanner) AttrURI ¶
AttrURI returns the value of the attribute with the given namespace URI (empty for none) and local name on the current Start token.
func (*Scanner) AttrURIAt ¶
AttrURIAt returns the i-th attribute of the current Start token: its namespace URI (empty for none), local name and decoded value. A namespace declaration has the xmlns namespace.
func (*Scanner) Depth ¶
Depth returns the number of open elements. After a Start token it includes that element; after an End token it does not.
func (*Scanner) Final ¶
Final reports whether the current Comment token is the last piece of its comment.
func (*Scanner) InEntity ¶
InEntity reports whether the current token comes from the replacement of an entity reference.
func (*Scanner) Is ¶
Is reports whether the current Start or End token is the element with the given namespace and local name.
func (*Scanner) Local ¶
Local returns the local name of the current Start or End token. At an End token it is cut as Name is.
func (*Scanner) Name ¶
Name returns the qualified name of the current Start or End token as it is written in the source, prefix included. It is valid UTF-8: a byte that is not part of a character is U+FFFD, counted in Stats.InvalidUTF8 at the Start token. An end tag is matched to its start tag by the name so mended, so two names that differ only in such bytes match; a prefix is bound by its bytes as written. A Start token has the whole name. An End token has what was kept of its start tag's name: all of it, or the first MaxNameKept bytes or fewer of a longer one (Stats.NamesCut).
func (*Scanner) NumAttr ¶
NumAttr returns the number of attributes kept on the current Start token, namespace declarations included.
func (*Scanner) Offset ¶
Offset returns the byte offset in the input of the next unread byte. While the replacement of an entity reference is read, it is the offset of the reference.
func (*Scanner) Release ¶
func (s *Scanner) Release()
Release hands the scanner's window back to be reused, and leaves the scanner at the end of its stream until it is Reset. What it read is a view of the window, so nothing of it may be held after: that holds already, since the window slides over the stream as it is read.
func (*Scanner) ResetBytes ¶
ResetBytes makes the scanner read from data, keeping its buffers.
func (*Scanner) SetResolver ¶
SetResolver replaces Options.Resolve, as a reader does once it has read the document type declaration.
func (*Scanner) Skip ¶
Skip reads past the end of the element whose Start token is current. It reports false if the input ended first.
func (*Scanner) Span ¶
Span returns the byte offsets in the input where the current token starts and ends, with Options.Spans. A token read from the replacement of an entity reference has the offsets of the outermost reference.
func (*Scanner) Text ¶
Text returns the content of the current Text, Comment, PI or Doctype token. Text has references decoded; all have line ends normalized to "\n", except Doctype, which is as written. It is valid UTF-8: a byte of the input that is not part of a character is U+FFFD, counted in Stats.InvalidUTF8.
type Space ¶
type Space uint16
Space identifies an XML namespace. Callers number the namespaces they care about from FirstSpace and pass the numbering in Options.Spaces.
const ( // NoSpace is the absence of a namespace: an attribute without a // prefix, or an element where no default namespace is in force. NoSpace Space = iota // SpaceXML is the namespace of the reserved "xml" prefix (xml:space). SpaceXML // SpaceUnknown is any namespace not listed in Options.Spaces, and any // prefix that was never declared. SpaceUnknown // FirstSpace is the first number available to callers. FirstSpace )
type Stats ¶
type Stats struct {
// Repairs counts the places where damaged markup was read leniently,
// and references kept as written (an unknown entity, a character
// reference without its semicolon).
Repairs int
// Flattened counts elements nested deeper than Options.MaxDepth.
Flattened int
// AttrsCut counts attributes past Options.MaxAttrs.
AttrsCut int
// EntitiesCut counts references kept as written because expanding
// them would pass Options.MaxEntityDepth or Options.ExpansionLimit.
EntitiesCut int
// EntitiesRecursive counts references to an entity inside its own
// replacement, kept as written.
EntitiesRecursive int
// Expanded is the bytes of replacement text read in place of
// references.
Expanded int64
// ValuesCut counts attribute values cut to Options.MaxValueBytes, or
// to what is left of MaxTokenBytes for all the values of one tag, as
// they are read.
ValuesCut int
// NamesCut counts element names longer than MaxNameKept, of which
// only the start is kept for the End token.
NamesCut int
// BindingsCut counts namespace declarations not read because those
// in scope already hold MaxBindingBytes.
BindingsCut int
// CharRefsReplaced counts character references to no character XML
// allows anywhere (�, a surrogate, a number past U+10FFFF), each
// read as U+FFFD. Each is counted in Repairs too.
CharRefsReplaced int
// InvalidUTF8 counts the bytes of text, attribute values and names
// read that are not part of a UTF-8 character, each read as U+FFFD
// (input that is UTF-8 is handed on as it is, and need not be valid).
// A name is counted once: an element's at its Start token, not again
// at its End.
InvalidUTF8 int
}
Stats counts what the scanner did besides reading well-formed input.