Black Lives Matter. Support the Equal Justice Initiative.

Source file src/encoding/xml/xml.go

Documentation: encoding/xml

     1  // Copyright 2009 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 xml implements a simple XML 1.0 parser that
     6  // understands XML name spaces.
     7  package xml
     8  
     9  // References:
    10  //    Annotated XML spec: https://www.xml.com/axml/testaxml.htm
    11  //    XML name spaces: https://www.w3.org/TR/REC-xml-names/
    12  
    13  // TODO(rsc):
    14  //	Test error handling.
    15  
    16  import (
    17  	"bufio"
    18  	"bytes"
    19  	"errors"
    20  	"fmt"
    21  	"io"
    22  	"strconv"
    23  	"strings"
    24  	"unicode"
    25  	"unicode/utf8"
    26  )
    27  
    28  // A SyntaxError represents a syntax error in the XML input stream.
    29  type SyntaxError struct {
    30  	Msg  string
    31  	Line int
    32  }
    33  
    34  func (e *SyntaxError) Error() string {
    35  	return "XML syntax error on line " + strconv.Itoa(e.Line) + ": " + e.Msg
    36  }
    37  
    38  // A Name represents an XML name (Local) annotated
    39  // with a name space identifier (Space).
    40  // In tokens returned by Decoder.Token, the Space identifier
    41  // is given as a canonical URL, not the short prefix used
    42  // in the document being parsed.
    43  type Name struct {
    44  	Space, Local string
    45  }
    46  
    47  // An Attr represents an attribute in an XML element (Name=Value).
    48  type Attr struct {
    49  	Name  Name
    50  	Value string
    51  }
    52  
    53  // A Token is an interface holding one of the token types:
    54  // StartElement, EndElement, CharData, Comment, ProcInst, or Directive.
    55  type Token interface{}
    56  
    57  // A StartElement represents an XML start element.
    58  type StartElement struct {
    59  	Name Name
    60  	Attr []Attr
    61  }
    62  
    63  // Copy creates a new copy of StartElement.
    64  func (e StartElement) Copy() StartElement {
    65  	attrs := make([]Attr, len(e.Attr))
    66  	copy(attrs, e.Attr)
    67  	e.Attr = attrs
    68  	return e
    69  }
    70  
    71  // End returns the corresponding XML end element.
    72  func (e StartElement) End() EndElement {
    73  	return EndElement{e.Name}
    74  }
    75  
    76  // An EndElement represents an XML end element.
    77  type EndElement struct {
    78  	Name Name
    79  }
    80  
    81  // A CharData represents XML character data (raw text),
    82  // in which XML escape sequences have been replaced by
    83  // the characters they represent.
    84  type CharData []byte
    85  
    86  func makeCopy(b []byte) []byte {
    87  	b1 := make([]byte, len(b))
    88  	copy(b1, b)
    89  	return b1
    90  }
    91  
    92  // Copy creates a new copy of CharData.
    93  func (c CharData) Copy() CharData { return CharData(makeCopy(c)) }
    94  
    95  // A Comment represents an XML comment of the form <!--comment-->.
    96  // The bytes do not include the <!-- and --> comment markers.
    97  type Comment []byte
    98  
    99  // Copy creates a new copy of Comment.
   100  func (c Comment) Copy() Comment { return Comment(makeCopy(c)) }
   101  
   102  // A ProcInst represents an XML processing instruction of the form <?target inst?>
   103  type ProcInst struct {
   104  	Target string
   105  	Inst   []byte
   106  }
   107  
   108  // Copy creates a new copy of ProcInst.
   109  func (p ProcInst) Copy() ProcInst {
   110  	p.Inst = makeCopy(p.Inst)
   111  	return p
   112  }
   113  
   114  // A Directive represents an XML directive of the form <!text>.
   115  // The bytes do not include the <! and > markers.
   116  type Directive []byte
   117  
   118  // Copy creates a new copy of Directive.
   119  func (d Directive) Copy() Directive { return Directive(makeCopy(d)) }
   120  
   121  // CopyToken returns a copy of a Token.
   122  func CopyToken(t Token) Token {
   123  	switch v := t.(type) {
   124  	case CharData:
   125  		return v.Copy()
   126  	case Comment:
   127  		return v.Copy()
   128  	case Directive:
   129  		return v.Copy()
   130  	case ProcInst:
   131  		return v.Copy()
   132  	case StartElement:
   133  		return v.Copy()
   134  	}
   135  	return t
   136  }
   137  
   138  // A TokenReader is anything that can decode a stream of XML tokens, including a
   139  // Decoder.
   140  //
   141  // When Token encounters an error or end-of-file condition after successfully
   142  // reading a token, it returns the token. It may return the (non-nil) error from
   143  // the same call or return the error (and a nil token) from a subsequent call.
   144  // An instance of this general case is that a TokenReader returning a non-nil
   145  // token at the end of the token stream may return either io.EOF or a nil error.
   146  // The next Read should return nil, io.EOF.
   147  //
   148  // Implementations of Token are discouraged from returning a nil token with a
   149  // nil error. Callers should treat a return of nil, nil as indicating that
   150  // nothing happened; in particular it does not indicate EOF.
   151  type TokenReader interface {
   152  	Token() (Token, error)
   153  }
   154  
   155  // A Decoder represents an XML parser reading a particular input stream.
   156  // The parser assumes that its input is encoded in UTF-8.
   157  type Decoder struct {
   158  	// Strict defaults to true, enforcing the requirements
   159  	// of the XML specification.
   160  	// If set to false, the parser allows input containing common
   161  	// mistakes:
   162  	//	* If an element is missing an end tag, the parser invents
   163  	//	  end tags as necessary to keep the return values from Token
   164  	//	  properly balanced.
   165  	//	* In attribute values and character data, unknown or malformed
   166  	//	  character entities (sequences beginning with &) are left alone.
   167  	//
   168  	// Setting:
   169  	//
   170  	//	d.Strict = false
   171  	//	d.AutoClose = xml.HTMLAutoClose
   172  	//	d.Entity = xml.HTMLEntity
   173  	//
   174  	// creates a parser that can handle typical HTML.
   175  	//
   176  	// Strict mode does not enforce the requirements of the XML name spaces TR.
   177  	// In particular it does not reject name space tags using undefined prefixes.
   178  	// Such tags are recorded with the unknown prefix as the name space URL.
   179  	Strict bool
   180  
   181  	// When Strict == false, AutoClose indicates a set of elements to
   182  	// consider closed immediately after they are opened, regardless
   183  	// of whether an end element is present.
   184  	AutoClose []string
   185  
   186  	// Entity can be used to map non-standard entity names to string replacements.
   187  	// The parser behaves as if these standard mappings are present in the map,
   188  	// regardless of the actual map content:
   189  	//
   190  	//	"lt": "<",
   191  	//	"gt": ">",
   192  	//	"amp": "&",
   193  	//	"apos": "'",
   194  	//	"quot": `"`,
   195  	Entity map[string]string
   196  
   197  	// CharsetReader, if non-nil, defines a function to generate
   198  	// charset-conversion readers, converting from the provided
   199  	// non-UTF-8 charset into UTF-8. If CharsetReader is nil or
   200  	// returns an error, parsing stops with an error. One of the
   201  	// CharsetReader's result values must be non-nil.
   202  	CharsetReader func(charset string, input io.Reader) (io.Reader, error)
   203  
   204  	// DefaultSpace sets the default name space used for unadorned tags,
   205  	// as if the entire XML stream were wrapped in an element containing
   206  	// the attribute xmlns="DefaultSpace".
   207  	DefaultSpace string
   208  
   209  	r              io.ByteReader
   210  	t              TokenReader
   211  	buf            bytes.Buffer
   212  	saved          *bytes.Buffer
   213  	stk            *stack
   214  	free           *stack
   215  	needClose      bool
   216  	toClose        Name
   217  	nextToken      Token
   218  	nextByte       int
   219  	ns             map[string]string
   220  	err            error
   221  	line           int
   222  	offset         int64
   223  	unmarshalDepth int
   224  }
   225  
   226  // NewDecoder creates a new XML parser reading from r.
   227  // If r does not implement io.ByteReader, NewDecoder will
   228  // do its own buffering.
   229  func NewDecoder(r io.Reader) *Decoder {
   230  	d := &Decoder{
   231  		ns:       make(map[string]string),
   232  		nextByte: -1,
   233  		line:     1,
   234  		Strict:   true,
   235  	}
   236  	d.switchToReader(r)
   237  	return d
   238  }
   239  
   240  // NewTokenDecoder creates a new XML parser using an underlying token stream.
   241  func NewTokenDecoder(t TokenReader) *Decoder {
   242  	// Is it already a Decoder?
   243  	if d, ok := t.(*Decoder); ok {
   244  		return d
   245  	}
   246  	d := &Decoder{
   247  		ns:       make(map[string]string),
   248  		t:        t,
   249  		nextByte: -1,
   250  		line:     1,
   251  		Strict:   true,
   252  	}
   253  	return d
   254  }
   255  
   256  // Token returns the next XML token in the input stream.
   257  // At the end of the input stream, Token returns nil, io.EOF.
   258  //
   259  // Slices of bytes in the returned token data refer to the
   260  // parser's internal buffer and remain valid only until the next
   261  // call to Token. To acquire a copy of the bytes, call CopyToken
   262  // or the token's Copy method.
   263  //
   264  // Token expands self-closing elements such as <br/>
   265  // into separate start and end elements returned by successive calls.
   266  //
   267  // Token guarantees that the StartElement and EndElement
   268  // tokens it returns are properly nested and matched:
   269  // if Token encounters an unexpected end element
   270  // or EOF before all expected end elements,
   271  // it will return an error.
   272  //
   273  // Token implements XML name spaces as described by
   274  // https://www.w3.org/TR/REC-xml-names/.  Each of the
   275  // Name structures contained in the Token has the Space
   276  // set to the URL identifying its name space when known.
   277  // If Token encounters an unrecognized name space prefix,
   278  // it uses the prefix as the Space rather than report an error.
   279  func (d *Decoder) Token() (Token, error) {
   280  	var t Token
   281  	var err error
   282  	if d.stk != nil && d.stk.kind == stkEOF {
   283  		return nil, io.EOF
   284  	}
   285  	if d.nextToken != nil {
   286  		t = d.nextToken
   287  		d.nextToken = nil
   288  	} else if t, err = d.rawToken(); err != nil {
   289  		switch {
   290  		case err == io.EOF && d.t != nil:
   291  			err = nil
   292  		case err == io.EOF && d.stk != nil && d.stk.kind != stkEOF:
   293  			err = d.syntaxError("unexpected EOF")
   294  		}
   295  		return t, err
   296  	}
   297  
   298  	if !d.Strict {
   299  		if t1, ok := d.autoClose(t); ok {
   300  			d.nextToken = t
   301  			t = t1
   302  		}
   303  	}
   304  	switch t1 := t.(type) {
   305  	case StartElement:
   306  		// In XML name spaces, the translations listed in the
   307  		// attributes apply to the element name and
   308  		// to the other attribute names, so process
   309  		// the translations first.
   310  		for _, a := range t1.Attr {
   311  			if a.Name.Space == xmlnsPrefix {
   312  				v, ok := d.ns[a.Name.Local]
   313  				d.pushNs(a.Name.Local, v, ok)
   314  				d.ns[a.Name.Local] = a.Value
   315  			}
   316  			if a.Name.Space == "" && a.Name.Local == xmlnsPrefix {
   317  				// Default space for untagged names
   318  				v, ok := d.ns[""]
   319  				d.pushNs("", v, ok)
   320  				d.ns[""] = a.Value
   321  			}
   322  		}
   323  
   324  		d.translate(&t1.Name, true)
   325  		for i := range t1.Attr {
   326  			d.translate(&t1.Attr[i].Name, false)
   327  		}
   328  		d.pushElement(t1.Name)
   329  		t = t1
   330  
   331  	case EndElement:
   332  		d.translate(&t1.Name, true)
   333  		if !d.popElement(&t1) {
   334  			return nil, d.err
   335  		}
   336  		t = t1
   337  	}
   338  	return t, err
   339  }
   340  
   341  const (
   342  	xmlURL      = "http://www.w3.org/XML/1998/namespace"
   343  	xmlnsPrefix = "xmlns"
   344  	xmlPrefix   = "xml"
   345  )
   346  
   347  // Apply name space translation to name n.
   348  // The default name space (for Space=="")
   349  // applies only to element names, not to attribute names.
   350  func (d *Decoder) translate(n *Name, isElementName bool) {
   351  	switch {
   352  	case n.Space == xmlnsPrefix:
   353  		return
   354  	case n.Space == "" && !isElementName:
   355  		return
   356  	case n.Space == xmlPrefix:
   357  		n.Space = xmlURL
   358  	case n.Space == "" && n.Local == xmlnsPrefix:
   359  		return
   360  	}
   361  	if v, ok := d.ns[n.Space]; ok {
   362  		n.Space = v
   363  	} else if n.Space == "" {
   364  		n.Space = d.DefaultSpace
   365  	}
   366  }
   367  
   368  func (d *Decoder) switchToReader(r io.Reader) {
   369  	// Get efficient byte at a time reader.
   370  	// Assume that if reader has its own
   371  	// ReadByte, it's efficient enough.
   372  	// Otherwise, use bufio.
   373  	if rb, ok := r.(io.ByteReader); ok {
   374  		d.r = rb
   375  	} else {
   376  		d.r = bufio.NewReader(r)
   377  	}
   378  }
   379  
   380  // Parsing state - stack holds old name space translations
   381  // and the current set of open elements. The translations to pop when
   382  // ending a given tag are *below* it on the stack, which is
   383  // more work but forced on us by XML.
   384  type stack struct {
   385  	next *stack
   386  	kind int
   387  	name Name
   388  	ok   bool
   389  }
   390  
   391  const (
   392  	stkStart = iota
   393  	stkNs
   394  	stkEOF
   395  )
   396  
   397  func (d *Decoder) push(kind int) *stack {
   398  	s := d.free
   399  	if s != nil {
   400  		d.free = s.next
   401  	} else {
   402  		s = new(stack)
   403  	}
   404  	s.next = d.stk
   405  	s.kind = kind
   406  	d.stk = s
   407  	return s
   408  }
   409  
   410  func (d *Decoder) pop() *stack {
   411  	s := d.stk
   412  	if s != nil {
   413  		d.stk = s.next
   414  		s.next = d.free
   415  		d.free = s
   416  	}
   417  	return s
   418  }
   419  
   420  // Record that after the current element is finished
   421  // (that element is already pushed on the stack)
   422  // Token should return EOF until popEOF is called.
   423  func (d *Decoder) pushEOF() {
   424  	// Walk down stack to find Start.
   425  	// It might not be the top, because there might be stkNs
   426  	// entries above it.
   427  	start := d.stk
   428  	for start.kind != stkStart {
   429  		start = start.next
   430  	}
   431  	// The stkNs entries below a start are associated with that
   432  	// element too; skip over them.
   433  	for start.next != nil && start.next.kind == stkNs {
   434  		start = start.next
   435  	}
   436  	s := d.free
   437  	if s != nil {
   438  		d.free = s.next
   439  	} else {
   440  		s = new(stack)
   441  	}
   442  	s.kind = stkEOF
   443  	s.next = start.next
   444  	start.next = s
   445  }
   446  
   447  // Undo a pushEOF.
   448  // The element must have been finished, so the EOF should be at the top of the stack.
   449  func (d *Decoder) popEOF() bool {
   450  	if d.stk == nil || d.stk.kind != stkEOF {
   451  		return false
   452  	}
   453  	d.pop()
   454  	return true
   455  }
   456  
   457  // Record that we are starting an element with the given name.
   458  func (d *Decoder) pushElement(name Name) {
   459  	s := d.push(stkStart)
   460  	s.name = name
   461  }
   462  
   463  // Record that we are changing the value of ns[local].
   464  // The old value is url, ok.
   465  func (d *Decoder) pushNs(local string, url string, ok bool) {
   466  	s := d.push(stkNs)
   467  	s.name.Local = local
   468  	s.name.Space = url
   469  	s.ok = ok
   470  }
   471  
   472  // Creates a SyntaxError with the current line number.
   473  func (d *Decoder) syntaxError(msg string) error {
   474  	return &SyntaxError{Msg: msg, Line: d.line}
   475  }
   476  
   477  // Record that we are ending an element with the given name.
   478  // The name must match the record at the top of the stack,
   479  // which must be a pushElement record.
   480  // After popping the element, apply any undo records from
   481  // the stack to restore the name translations that existed
   482  // before we saw this element.
   483  func (d *Decoder) popElement(t *EndElement) bool {
   484  	s := d.pop()
   485  	name := t.Name
   486  	switch {
   487  	case s == nil || s.kind != stkStart:
   488  		d.err = d.syntaxError("unexpected end element </" + name.Local + ">")
   489  		return false
   490  	case s.name.Local != name.Local:
   491  		if !d.Strict {
   492  			d.needClose = true
   493  			d.toClose = t.Name
   494  			t.Name = s.name
   495  			return true
   496  		}
   497  		d.err = d.syntaxError("element <" + s.name.Local + "> closed by </" + name.Local + ">")
   498  		return false
   499  	case s.name.Space != name.Space:
   500  		d.err = d.syntaxError("element <" + s.name.Local + "> in space " + s.name.Space +
   501  			"closed by </" + name.Local + "> in space " + name.Space)
   502  		return false
   503  	}
   504  
   505  	// Pop stack until a Start or EOF is on the top, undoing the
   506  	// translations that were associated with the element we just closed.
   507  	for d.stk != nil && d.stk.kind != stkStart && d.stk.kind != stkEOF {
   508  		s := d.pop()
   509  		if s.ok {
   510  			d.ns[s.name.Local] = s.name.Space
   511  		} else {
   512  			delete(d.ns, s.name.Local)
   513  		}
   514  	}
   515  
   516  	return true
   517  }
   518  
   519  // If the top element on the stack is autoclosing and
   520  // t is not the end tag, invent the end tag.
   521  func (d *Decoder) autoClose(t Token) (Token, bool) {
   522  	if d.stk == nil || d.stk.kind != stkStart {
   523  		return nil, false
   524  	}
   525  	name := strings.ToLower(d.stk.name.Local)
   526  	for _, s := range d.AutoClose {
   527  		if strings.ToLower(s) == name {
   528  			// This one should be auto closed if t doesn't close it.
   529  			et, ok := t.(EndElement)
   530  			if !ok || et.Name.Local != name {
   531  				return EndElement{d.stk.name}, true
   532  			}
   533  			break
   534  		}
   535  	}
   536  	return nil, false
   537  }
   538  
   539  var errRawToken = errors.New("xml: cannot use RawToken from UnmarshalXML method")
   540  
   541  // RawToken is like Token but does not verify that
   542  // start and end elements match and does not translate
   543  // name space prefixes to their corresponding URLs.
   544  func (d *Decoder) RawToken() (Token, error) {
   545  	if d.unmarshalDepth > 0 {
   546  		return nil, errRawToken
   547  	}
   548  	return d.rawToken()
   549  }
   550  
   551  func (d *Decoder) rawToken() (Token, error) {
   552  	if d.t != nil {
   553  		return d.t.Token()
   554  	}
   555  	if d.err != nil {
   556  		return nil, d.err
   557  	}
   558  	if d.needClose {
   559  		// The last element we read was self-closing and
   560  		// we returned just the StartElement half.
   561  		// Return the EndElement half now.
   562  		d.needClose = false
   563  		return EndElement{d.toClose}, nil
   564  	}
   565  
   566  	b, ok := d.getc()
   567  	if !ok {
   568  		return nil, d.err
   569  	}
   570  
   571  	if b != '<' {
   572  		// Text section.
   573  		d.ungetc(b)
   574  		data := d.text(-1, false)
   575  		if data == nil {
   576  			return nil, d.err
   577  		}
   578  		return CharData(data), nil
   579  	}
   580  
   581  	if b, ok = d.mustgetc(); !ok {
   582  		return nil, d.err
   583  	}
   584  	switch b {
   585  	case '/':
   586  		// </: End element
   587  		var name Name
   588  		if name, ok = d.nsname(); !ok {
   589  			if d.err == nil {
   590  				d.err = d.syntaxError("expected element name after </")
   591  			}
   592  			return nil, d.err
   593  		}
   594  		d.space()
   595  		if b, ok = d.mustgetc(); !ok {
   596  			return nil, d.err
   597  		}
   598  		if b != '>' {
   599  			d.err = d.syntaxError("invalid characters between </" + name.Local + " and >")
   600  			return nil, d.err
   601  		}
   602  		return EndElement{name}, nil
   603  
   604  	case '?':
   605  		// <?: Processing instruction.
   606  		var target string
   607  		if target, ok = d.name(); !ok {
   608  			if d.err == nil {
   609  				d.err = d.syntaxError("expected target name after <?")
   610  			}
   611  			return nil, d.err
   612  		}
   613  		d.space()
   614  		d.buf.Reset()
   615  		var b0 byte
   616  		for {
   617  			if b, ok = d.mustgetc(); !ok {
   618  				return nil, d.err
   619  			}
   620  			d.buf.WriteByte(b)
   621  			if b0 == '?' && b == '>' {
   622  				break
   623  			}
   624  			b0 = b
   625  		}
   626  		data := d.buf.Bytes()
   627  		data = data[0 : len(data)-2] // chop ?>
   628  
   629  		if target == "xml" {
   630  			content := string(data)
   631  			ver := procInst("version", content)
   632  			if ver != "" && ver != "1.0" {
   633  				d.err = fmt.Errorf("xml: unsupported version %q; only version 1.0 is supported", ver)
   634  				return nil, d.err
   635  			}
   636  			enc := procInst("encoding", content)
   637  			if enc != "" && enc != "utf-8" && enc != "UTF-8" && !strings.EqualFold(enc, "utf-8") {
   638  				if d.CharsetReader == nil {
   639  					d.err = fmt.Errorf("xml: encoding %q declared but Decoder.CharsetReader is nil", enc)
   640  					return nil, d.err
   641  				}
   642  				newr, err := d.CharsetReader(enc, d.r.(io.Reader))
   643  				if err != nil {
   644  					d.err = fmt.Errorf("xml: opening charset %q: %v", enc, err)
   645  					return nil, d.err
   646  				}
   647  				if newr == nil {
   648  					panic("CharsetReader returned a nil Reader for charset " + enc)
   649  				}
   650  				d.switchToReader(newr)
   651  			}
   652  		}
   653  		return ProcInst{target, data}, nil
   654  
   655  	case '!':
   656  		// <!: Maybe comment, maybe CDATA.
   657  		if b, ok = d.mustgetc(); !ok {
   658  			return nil, d.err
   659  		}
   660  		switch b {
   661  		case '-': // <!-
   662  			// Probably <!-- for a comment.
   663  			if b, ok = d.mustgetc(); !ok {
   664  				return nil, d.err
   665  			}
   666  			if b != '-' {
   667  				d.err = d.syntaxError("invalid sequence <!- not part of <!--")
   668  				return nil, d.err
   669  			}
   670  			// Look for terminator.
   671  			d.buf.Reset()
   672  			var b0, b1 byte
   673  			for {
   674  				if b, ok = d.mustgetc(); !ok {
   675  					return nil, d.err
   676  				}
   677  				d.buf.WriteByte(b)
   678  				if b0 == '-' && b1 == '-' {
   679  					if b != '>' {
   680  						d.err = d.syntaxError(
   681  							`invalid sequence "--" not allowed in comments`)
   682  						return nil, d.err
   683  					}
   684  					break
   685  				}
   686  				b0, b1 = b1, b
   687  			}
   688  			data := d.buf.Bytes()
   689  			data = data[0 : len(data)-3] // chop -->
   690  			return Comment(data), nil
   691  
   692  		case '[': // <![
   693  			// Probably <![CDATA[.
   694  			for i := 0; i < 6; i++ {
   695  				if b, ok = d.mustgetc(); !ok {
   696  					return nil, d.err
   697  				}
   698  				if b != "CDATA["[i] {
   699  					d.err = d.syntaxError("invalid <![ sequence")
   700  					return nil, d.err
   701  				}
   702  			}
   703  			// Have <![CDATA[.  Read text until ]]>.
   704  			data := d.text(-1, true)
   705  			if data == nil {
   706  				return nil, d.err
   707  			}
   708  			return CharData(data), nil
   709  		}
   710  
   711  		// Probably a directive: <!DOCTYPE ...>, <!ENTITY ...>, etc.
   712  		// We don't care, but accumulate for caller. Quoted angle
   713  		// brackets do not count for nesting.
   714  		d.buf.Reset()
   715  		d.buf.WriteByte(b)
   716  		inquote := uint8(0)
   717  		depth := 0
   718  		for {
   719  			if b, ok = d.mustgetc(); !ok {
   720  				return nil, d.err
   721  			}
   722  			if inquote == 0 && b == '>' && depth == 0 {
   723  				break
   724  			}
   725  		HandleB:
   726  			d.buf.WriteByte(b)
   727  			switch {
   728  			case b == inquote:
   729  				inquote = 0
   730  
   731  			case inquote != 0:
   732  				// in quotes, no special action
   733  
   734  			case b == '\'' || b == '"':
   735  				inquote = b
   736  
   737  			case b == '>' && inquote == 0:
   738  				depth--
   739  
   740  			case b == '<' && inquote == 0:
   741  				// Look for <!-- to begin comment.
   742  				s := "!--"
   743  				for i := 0; i < len(s); i++ {
   744  					if b, ok = d.mustgetc(); !ok {
   745  						return nil, d.err
   746  					}
   747  					if b != s[i] {
   748  						for j := 0; j < i; j++ {
   749  							d.buf.WriteByte(s[j])
   750  						}
   751  						depth++
   752  						goto HandleB
   753  					}
   754  				}
   755  
   756  				// Remove < that was written above.
   757  				d.buf.Truncate(d.buf.Len() - 1)
   758  
   759  				// Look for terminator.
   760  				var b0, b1 byte
   761  				for {
   762  					if b, ok = d.mustgetc(); !ok {
   763  						return nil, d.err
   764  					}
   765  					if b0 == '-' && b1 == '-' && b == '>' {
   766  						break
   767  					}
   768  					b0, b1 = b1, b
   769  				}
   770  			}
   771  		}
   772  		return Directive(d.buf.Bytes()), nil
   773  	}
   774  
   775  	// Must be an open element like <a href="foo">
   776  	d.ungetc(b)
   777  
   778  	var (
   779  		name  Name
   780  		empty bool
   781  		attr  []Attr
   782  	)
   783  	if name, ok = d.nsname(); !ok {
   784  		if d.err == nil {
   785  			d.err = d.syntaxError("expected element name after <")
   786  		}
   787  		return nil, d.err
   788  	}
   789  
   790  	attr = []Attr{}
   791  	for {
   792  		d.space()
   793  		if b, ok = d.mustgetc(); !ok {
   794  			return nil, d.err
   795  		}
   796  		if b == '/' {
   797  			empty = true
   798  			if b, ok = d.mustgetc(); !ok {
   799  				return nil, d.err
   800  			}
   801  			if b != '>' {
   802  				d.err = d.syntaxError("expected /> in element")
   803  				return nil, d.err
   804  			}
   805  			break
   806  		}
   807  		if b == '>' {
   808  			break
   809  		}
   810  		d.ungetc(b)
   811  
   812  		a := Attr{}
   813  		if a.Name, ok = d.nsname(); !ok {
   814  			if d.err == nil {
   815  				d.err = d.syntaxError("expected attribute name in element")
   816  			}
   817  			return nil, d.err
   818  		}
   819  		d.space()
   820  		if b, ok = d.mustgetc(); !ok {
   821  			return nil, d.err
   822  		}
   823  		if b != '=' {
   824  			if d.Strict {
   825  				d.err = d.syntaxError("attribute name without = in element")
   826  				return nil, d.err
   827  			}
   828  			d.ungetc(b)
   829  			a.Value = a.Name.Local
   830  		} else {
   831  			d.space()
   832  			data := d.attrval()
   833  			if data == nil {
   834  				return nil, d.err
   835  			}
   836  			a.Value = string(data)
   837  		}
   838  		attr = append(attr, a)
   839  	}
   840  	if empty {
   841  		d.needClose = true
   842  		d.toClose = name
   843  	}
   844  	return StartElement{name, attr}, nil
   845  }
   846  
   847  func (d *Decoder) attrval() []byte {
   848  	b, ok := d.mustgetc()
   849  	if !ok {
   850  		return nil
   851  	}
   852  	// Handle quoted attribute values
   853  	if b == '"' || b == '\'' {
   854  		return d.text(int(b), false)
   855  	}
   856  	// Handle unquoted attribute values for strict parsers
   857  	if d.Strict {
   858  		d.err = d.syntaxError("unquoted or missing attribute value in element")
   859  		return nil
   860  	}
   861  	// Handle unquoted attribute values for unstrict parsers
   862  	d.ungetc(b)
   863  	d.buf.Reset()
   864  	for {
   865  		b, ok = d.mustgetc()
   866  		if !ok {
   867  			return nil
   868  		}
   869  		// https://www.w3.org/TR/REC-html40/intro/sgmltut.html#h-3.2.2
   870  		if 'a' <= b && b <= 'z' || 'A' <= b && b <= 'Z' ||
   871  			'0' <= b && b <= '9' || b == '_' || b == ':' || b == '-' {
   872  			d.buf.WriteByte(b)
   873  		} else {
   874  			d.ungetc(b)
   875  			break
   876  		}
   877  	}
   878  	return d.buf.Bytes()
   879  }
   880  
   881  // Skip spaces if any
   882  func (d *Decoder) space() {
   883  	for {
   884  		b, ok := d.getc()
   885  		if !ok {
   886  			return
   887  		}
   888  		switch b {
   889  		case ' ', '\r', '\n', '\t':
   890  		default:
   891  			d.ungetc(b)
   892  			return
   893  		}
   894  	}
   895  }
   896  
   897  // Read a single byte.
   898  // If there is no byte to read, return ok==false
   899  // and leave the error in d.err.
   900  // Maintain line number.
   901  func (d *Decoder) getc() (b byte, ok bool) {
   902  	if d.err != nil {
   903  		return 0, false
   904  	}
   905  	if d.nextByte >= 0 {
   906  		b = byte(d.nextByte)
   907  		d.nextByte = -1
   908  	} else {
   909  		b, d.err = d.r.ReadByte()
   910  		if d.err != nil {
   911  			return 0, false
   912  		}
   913  		if d.saved != nil {
   914  			d.saved.WriteByte(b)
   915  		}
   916  	}
   917  	if b == '\n' {
   918  		d.line++
   919  	}
   920  	d.offset++
   921  	return b, true
   922  }
   923  
   924  // InputOffset returns the input stream byte offset of the current decoder position.
   925  // The offset gives the location of the end of the most recently returned token
   926  // and the beginning of the next token.
   927  func (d *Decoder) InputOffset() int64 {
   928  	return d.offset
   929  }
   930  
   931  // Return saved offset.
   932  // If we did ungetc (nextByte >= 0), have to back up one.
   933  func (d *Decoder) savedOffset() int {
   934  	n := d.saved.Len()
   935  	if d.nextByte >= 0 {
   936  		n--
   937  	}
   938  	return n
   939  }
   940  
   941  // Must read a single byte.
   942  // If there is no byte to read,
   943  // set d.err to SyntaxError("unexpected EOF")
   944  // and return ok==false
   945  func (d *Decoder) mustgetc() (b byte, ok bool) {
   946  	if b, ok = d.getc(); !ok {
   947  		if d.err == io.EOF {
   948  			d.err = d.syntaxError("unexpected EOF")
   949  		}
   950  	}
   951  	return
   952  }
   953  
   954  // Unread a single byte.
   955  func (d *Decoder) ungetc(b byte) {
   956  	if b == '\n' {
   957  		d.line--
   958  	}
   959  	d.nextByte = int(b)
   960  	d.offset--
   961  }
   962  
   963  var entity = map[string]rune{
   964  	"lt":   '<',
   965  	"gt":   '>',
   966  	"amp":  '&',
   967  	"apos": '\'',
   968  	"quot": '"',
   969  }
   970  
   971  // Read plain text section (XML calls it character data).
   972  // If quote >= 0, we are in a quoted string and need to find the matching quote.
   973  // If cdata == true, we are in a <![CDATA[ section and need to find ]]>.
   974  // On failure return nil and leave the error in d.err.
   975  func (d *Decoder) text(quote int, cdata bool) []byte {
   976  	var b0, b1 byte
   977  	var trunc int
   978  	d.buf.Reset()
   979  Input:
   980  	for {
   981  		b, ok := d.getc()
   982  		if !ok {
   983  			if cdata {
   984  				if d.err == io.EOF {
   985  					d.err = d.syntaxError("unexpected EOF in CDATA section")
   986  				}
   987  				return nil
   988  			}
   989  			break Input
   990  		}
   991  
   992  		// <![CDATA[ section ends with ]]>.
   993  		// It is an error for ]]> to appear in ordinary text.
   994  		if b0 == ']' && b1 == ']' && b == '>' {
   995  			if cdata {
   996  				trunc = 2
   997  				break Input
   998  			}
   999  			d.err = d.syntaxError("unescaped ]]> not in CDATA section")
  1000  			return nil
  1001  		}
  1002  
  1003  		// Stop reading text if we see a <.
  1004  		if b == '<' && !cdata {
  1005  			if quote >= 0 {
  1006  				d.err = d.syntaxError("unescaped < inside quoted string")
  1007  				return nil
  1008  			}
  1009  			d.ungetc('<')
  1010  			break Input
  1011  		}
  1012  		if quote >= 0 && b == byte(quote) {
  1013  			break Input
  1014  		}
  1015  		if b == '&' && !cdata {
  1016  			// Read escaped character expression up to semicolon.
  1017  			// XML in all its glory allows a document to define and use
  1018  			// its own character names with <!ENTITY ...> directives.
  1019  			// Parsers are required to recognize lt, gt, amp, apos, and quot
  1020  			// even if they have not been declared.
  1021  			before := d.buf.Len()
  1022  			d.buf.WriteByte('&')
  1023  			var ok bool
  1024  			var text string
  1025  			var haveText bool
  1026  			if b, ok = d.mustgetc(); !ok {
  1027  				return nil
  1028  			}
  1029  			if b == '#' {
  1030  				d.buf.WriteByte(b)
  1031  				if b, ok = d.mustgetc(); !ok {
  1032  					return nil
  1033  				}
  1034  				base := 10
  1035  				if b == 'x' {
  1036  					base = 16
  1037  					d.buf.WriteByte(b)
  1038  					if b, ok = d.mustgetc(); !ok {
  1039  						return nil
  1040  					}
  1041  				}
  1042  				start := d.buf.Len()
  1043  				for '0' <= b && b <= '9' ||
  1044  					base == 16 && 'a' <= b && b <= 'f' ||
  1045  					base == 16 && 'A' <= b && b <= 'F' {
  1046  					d.buf.WriteByte(b)
  1047  					if b, ok = d.mustgetc(); !ok {
  1048  						return nil
  1049  					}
  1050  				}
  1051  				if b != ';' {
  1052  					d.ungetc(b)
  1053  				} else {
  1054  					s := string(d.buf.Bytes()[start:])
  1055  					d.buf.WriteByte(';')
  1056  					n, err := strconv.ParseUint(s, base, 64)
  1057  					if err == nil && n <= unicode.MaxRune {
  1058  						text = string(rune(n))
  1059  						haveText = true
  1060  					}
  1061  				}
  1062  			} else {
  1063  				d.ungetc(b)
  1064  				if !d.readName() {
  1065  					if d.err != nil {
  1066  						return nil
  1067  					}
  1068  				}
  1069  				if b, ok = d.mustgetc(); !ok {
  1070  					return nil
  1071  				}
  1072  				if b != ';' {
  1073  					d.ungetc(b)
  1074  				} else {
  1075  					name := d.buf.Bytes()[before+1:]
  1076  					d.buf.WriteByte(';')
  1077  					if isName(name) {
  1078  						s := string(name)
  1079  						if r, ok := entity[s]; ok {
  1080  							text = string(r)
  1081  							haveText = true
  1082  						} else if d.Entity != nil {
  1083  							text, haveText = d.Entity[s]
  1084  						}
  1085  					}
  1086  				}
  1087  			}
  1088  
  1089  			if haveText {
  1090  				d.buf.Truncate(before)
  1091  				d.buf.Write([]byte(text))
  1092  				b0, b1 = 0, 0
  1093  				continue Input
  1094  			}
  1095  			if !d.Strict {
  1096  				b0, b1 = 0, 0
  1097  				continue Input
  1098  			}
  1099  			ent := string(d.buf.Bytes()[before:])
  1100  			if ent[len(ent)-1] != ';' {
  1101  				ent += " (no semicolon)"
  1102  			}
  1103  			d.err = d.syntaxError("invalid character entity " + ent)
  1104  			return nil
  1105  		}
  1106  
  1107  		// We must rewrite unescaped \r and \r\n into \n.
  1108  		if b == '\r' {
  1109  			d.buf.WriteByte('\n')
  1110  		} else if b1 == '\r' && b == '\n' {
  1111  			// Skip \r\n--we already wrote \n.
  1112  		} else {
  1113  			d.buf.WriteByte(b)
  1114  		}
  1115  
  1116  		b0, b1 = b1, b
  1117  	}
  1118  	data := d.buf.Bytes()
  1119  	data = data[0 : len(data)-trunc]
  1120  
  1121  	// Inspect each rune for being a disallowed character.
  1122  	buf := data
  1123  	for len(buf) > 0 {
  1124  		r, size := utf8.DecodeRune(buf)
  1125  		if r == utf8.RuneError && size == 1 {
  1126  			d.err = d.syntaxError("invalid UTF-8")
  1127  			return nil
  1128  		}
  1129  		buf = buf[size:]
  1130  		if !isInCharacterRange(r) {
  1131  			d.err = d.syntaxError(fmt.Sprintf("illegal character code %U", r))
  1132  			return nil
  1133  		}
  1134  	}
  1135  
  1136  	return data
  1137  }
  1138  
  1139  // Decide whether the given rune is in the XML Character Range, per
  1140  // the Char production of https://www.xml.com/axml/testaxml.htm,
  1141  // Section 2.2 Characters.
  1142  func isInCharacterRange(r rune) (inrange bool) {
  1143  	return r == 0x09 ||
  1144  		r == 0x0A ||
  1145  		r == 0x0D ||
  1146  		r >= 0x20 && r <= 0xD7FF ||
  1147  		r >= 0xE000 && r <= 0xFFFD ||
  1148  		r >= 0x10000 && r <= 0x10FFFF
  1149  }
  1150  
  1151  // Get name space name: name with a : stuck in the middle.
  1152  // The part before the : is the name space identifier.
  1153  func (d *Decoder) nsname() (name Name, ok bool) {
  1154  	s, ok := d.name()
  1155  	if !ok {
  1156  		return
  1157  	}
  1158  	i := strings.Index(s, ":")
  1159  	if i < 0 {
  1160  		name.Local = s
  1161  	} else {
  1162  		name.Space = s[0:i]
  1163  		name.Local = s[i+1:]
  1164  	}
  1165  	return name, true
  1166  }
  1167  
  1168  // Get name: /first(first|second)*/
  1169  // Do not set d.err if the name is missing (unless unexpected EOF is received):
  1170  // let the caller provide better context.
  1171  func (d *Decoder) name() (s string, ok bool) {
  1172  	d.buf.Reset()
  1173  	if !d.readName() {
  1174  		return "", false
  1175  	}
  1176  
  1177  	// Now we check the characters.
  1178  	b := d.buf.Bytes()
  1179  	if !isName(b) {
  1180  		d.err = d.syntaxError("invalid XML name: " + string(b))
  1181  		return "", false
  1182  	}
  1183  	return string(b), true
  1184  }
  1185  
  1186  // Read a name and append its bytes to d.buf.
  1187  // The name is delimited by any single-byte character not valid in names.
  1188  // All multi-byte characters are accepted; the caller must check their validity.
  1189  func (d *Decoder) readName() (ok bool) {
  1190  	var b byte
  1191  	if b, ok = d.mustgetc(); !ok {
  1192  		return
  1193  	}
  1194  	if b < utf8.RuneSelf && !isNameByte(b) {
  1195  		d.ungetc(b)
  1196  		return false
  1197  	}
  1198  	d.buf.WriteByte(b)
  1199  
  1200  	for {
  1201  		if b, ok = d.mustgetc(); !ok {
  1202  			return
  1203  		}
  1204  		if b < utf8.RuneSelf && !isNameByte(b) {
  1205  			d.ungetc(b)
  1206  			break
  1207  		}
  1208  		d.buf.WriteByte(b)
  1209  	}
  1210  	return true
  1211  }
  1212  
  1213  func isNameByte(c byte) bool {
  1214  	return 'A' <= c && c <= 'Z' ||
  1215  		'a' <= c && c <= 'z' ||
  1216  		'0' <= c && c <= '9' ||
  1217  		c == '_' || c == ':' || c == '.' || c == '-'
  1218  }
  1219  
  1220  func isName(s []byte) bool {
  1221  	if len(s) == 0 {
  1222  		return false
  1223  	}
  1224  	c, n := utf8.DecodeRune(s)
  1225  	if c == utf8.RuneError && n == 1 {
  1226  		return false
  1227  	}
  1228  	if !unicode.Is(first, c) {
  1229  		return false
  1230  	}
  1231  	for n < len(s) {
  1232  		s = s[n:]
  1233  		c, n = utf8.DecodeRune(s)
  1234  		if c == utf8.RuneError && n == 1 {
  1235  			return false
  1236  		}
  1237  		if !unicode.Is(first, c) && !unicode.Is(second, c) {
  1238  			return false
  1239  		}
  1240  	}
  1241  	return true
  1242  }
  1243  
  1244  func isNameString(s string) bool {
  1245  	if len(s) == 0 {
  1246  		return false
  1247  	}
  1248  	c, n := utf8.DecodeRuneInString(s)
  1249  	if c == utf8.RuneError && n == 1 {
  1250  		return false
  1251  	}
  1252  	if !unicode.Is(first, c) {
  1253  		return false
  1254  	}
  1255  	for n < len(s) {
  1256  		s = s[n:]
  1257  		c, n = utf8.DecodeRuneInString(s)
  1258  		if c == utf8.RuneError && n == 1 {
  1259  			return false
  1260  		}
  1261  		if !unicode.Is(first, c) && !unicode.Is(second, c) {
  1262  			return false
  1263  		}
  1264  	}
  1265  	return true
  1266  }
  1267  
  1268  // These tables were generated by cut and paste from Appendix B of
  1269  // the XML spec at https://www.xml.com/axml/testaxml.htm
  1270  // and then reformatting. First corresponds to (Letter | '_' | ':')
  1271  // and second corresponds to NameChar.
  1272  
  1273  var first = &unicode.RangeTable{
  1274  	R16: []unicode.Range16{
  1275  		{0x003A, 0x003A, 1},
  1276  		{0x0041, 0x005A, 1},
  1277  		{0x005F, 0x005F, 1},
  1278  		{0x0061, 0x007A, 1},
  1279  		{0x00C0, 0x00D6, 1},
  1280  		{0x00D8, 0x00F6, 1},
  1281  		{0x00F8, 0x00FF, 1},
  1282  		{0x0100, 0x0131, 1},
  1283  		{0x0134, 0x013E, 1},
  1284  		{0x0141, 0x0148, 1},
  1285  		{0x014A, 0x017E, 1},
  1286  		{0x0180, 0x01C3, 1},
  1287  		{0x01CD, 0x01F0, 1},
  1288  		{0x01F4, 0x01F5, 1},
  1289  		{0x01FA, 0x0217, 1},
  1290  		{0x0250, 0x02A8, 1},
  1291  		{0x02BB, 0x02C1, 1},
  1292  		{0x0386, 0x0386, 1},
  1293  		{0x0388, 0x038A, 1},
  1294  		{0x038C, 0x038C, 1},
  1295  		{0x038E, 0x03A1, 1},
  1296  		{0x03A3, 0x03CE, 1},
  1297  		{0x03D0, 0x03D6, 1},
  1298  		{0x03DA, 0x03E0, 2},
  1299  		{0x03E2, 0x03F3, 1},
  1300  		{0x0401, 0x040C, 1},
  1301  		{0x040E, 0x044F, 1},
  1302  		{0x0451, 0x045C, 1},
  1303  		{0x045E, 0x0481, 1},
  1304  		{0x0490, 0x04C4, 1},
  1305  		{0x04C7, 0x04C8, 1},
  1306  		{0x04CB, 0x04CC, 1},
  1307  		{0x04D0, 0x04EB, 1},
  1308  		{0x04EE, 0x04F5, 1},
  1309  		{0x04F8, 0x04F9, 1},
  1310  		{0x0531, 0x0556, 1},
  1311  		{0x0559, 0x0559, 1},
  1312  		{0x0561, 0x0586, 1},
  1313  		{0x05D0, 0x05EA, 1},
  1314  		{0x05F0, 0x05F2, 1},
  1315  		{0x0621, 0x063A, 1},
  1316  		{0x0641, 0x064A, 1},
  1317  		{0x0671, 0x06B7, 1},
  1318  		{0x06BA, 0x06BE, 1},
  1319  		{0x06C0, 0x06CE, 1},
  1320  		{0x06D0, 0x06D3, 1},
  1321  		{0x06D5, 0x06D5, 1},
  1322  		{0x06E5, 0x06E6, 1},
  1323  		{0x0905, 0x0939, 1},
  1324  		{0x093D, 0x093D, 1},
  1325  		{0x0958, 0x0961, 1},
  1326  		{0x0985, 0x098C, 1},
  1327  		{0x098F, 0x0990, 1},
  1328  		{0x0993, 0x09A8, 1},
  1329  		{0x09AA, 0x09B0, 1},
  1330  		{0x09B2, 0x09B2, 1},
  1331  		{0x09B6, 0x09B9, 1},
  1332  		{0x09DC, 0x09DD, 1},
  1333  		{0x09DF, 0x09E1, 1},
  1334  		{0x09F0, 0x09F1, 1},
  1335  		{0x0A05, 0x0A0A, 1},
  1336  		{0x0A0F, 0x0A10, 1},
  1337  		{0x0A13, 0x0A28, 1},
  1338  		{0x0A2A, 0x0A30, 1},
  1339  		{0x0A32, 0x0A33, 1},
  1340  		{0x0A35, 0x0A36, 1},
  1341  		{0x0A38, 0x0A39, 1},
  1342  		{0x0A59, 0x0A5C, 1},
  1343  		{0x0A5E, 0x0A5E, 1},
  1344  		{0x0A72, 0x0A74, 1},
  1345  		{0x0A85, 0x0A8B, 1},
  1346  		{0x0A8D, 0x0A8D, 1},
  1347  		{0x0A8F, 0x0A91, 1},
  1348  		{0x0A93, 0x0AA8, 1},
  1349  		{0x0AAA, 0x0AB0, 1},
  1350  		{0x0AB2, 0x0AB3, 1},
  1351  		{0x0AB5, 0x0AB9, 1},
  1352  		{0x0ABD, 0x0AE0, 0x23},
  1353  		{0x0B05, 0x0B0C, 1},
  1354  		{0x0B0F, 0x0B10, 1},
  1355  		{0x0B13, 0x0B28, 1},
  1356  		{0x0B2A, 0x0B30, 1},
  1357  		{0x0B32, 0x0B33, 1},
  1358  		{0x0B36, 0x0B39, 1},
  1359  		{0x0B3D, 0x0B3D, 1},
  1360  		{0x0B5C, 0x0B5D, 1},
  1361  		{0x0B5F, 0x0B61, 1},
  1362  		{0x0B85, 0x0B8A, 1},
  1363  		{0x0B8E, 0x0B90, 1},
  1364  		{0x0B92, 0x0B95, 1},
  1365  		{0x0B99, 0x0B9A, 1},
  1366  		{0x0B9C, 0x0B9C, 1},
  1367  		{0x0B9E, 0x0B9F, 1},
  1368  		{0x0BA3, 0x0BA4, 1},
  1369  		{0x0BA8, 0x0BAA, 1},
  1370  		{0x0BAE, 0x0BB5, 1},
  1371  		{0x0BB7, 0x0BB9, 1},
  1372  		{0x0C05, 0x0C0C, 1},
  1373  		{0x0C0E, 0x0C10, 1},
  1374  		{0x0C12, 0x0C28, 1},
  1375  		{0x0C2A, 0x0C33, 1},
  1376  		{0x0C35, 0x0C39, 1},
  1377  		{0x0C60, 0x0C61, 1},
  1378  		{0x0C85, 0x0C8C, 1},
  1379  		{0x0C8E, 0x0C90, 1},
  1380  		{0x0C92, 0x0CA8, 1},
  1381  		{0x0CAA, 0x0CB3, 1},
  1382  		{0x0CB5, 0x0CB9, 1},
  1383  		{0x0CDE, 0x0CDE, 1},
  1384  		{0x0CE0, 0x0CE1, 1},
  1385  		{0x0D05, 0x0D0C, 1},
  1386  		{0x0D0E, 0x0D10, 1},
  1387  		{0x0D12, 0x0D28, 1},
  1388  		{0x0D2A, 0x0D39, 1},
  1389  		{0x0D60, 0x0D61, 1},
  1390  		{0x0E01, 0x0E2E, 1},
  1391  		{0x0E30, 0x0E30, 1},
  1392  		{0x0E32, 0x0E33, 1},
  1393  		{0x0E40, 0x0E45, 1},
  1394  		{0x0E81, 0x0E82, 1},
  1395  		{0x0E84, 0x0E84, 1},
  1396  		{0x0E87, 0x0E88, 1},
  1397  		{0x0E8A, 0x0E8D, 3},
  1398  		{0x0E94, 0x0E97, 1},
  1399  		{0x0E99, 0x0E9F, 1},
  1400  		{0x0EA1, 0x0EA3, 1},
  1401  		{0x0EA5, 0x0EA7, 2},
  1402  		{0x0EAA, 0x0EAB, 1},
  1403  		{0x0EAD, 0x0EAE, 1},
  1404  		{0x0EB0, 0x0EB0, 1},
  1405  		{0x0EB2, 0x0EB3, 1},
  1406  		{0x0EBD, 0x0EBD, 1},
  1407  		{0x0EC0, 0x0EC4, 1},
  1408  		{0x0F40, 0x0F47, 1},
  1409  		{0x0F49, 0x0F69, 1},
  1410  		{0x10A0, 0x10C5, 1},
  1411  		{0x10D0, 0x10F6, 1},
  1412  		{0x1100, 0x1100, 1},
  1413  		{0x1102, 0x1103, 1},
  1414  		{0x1105, 0x1107, 1},
  1415  		{0x1109, 0x1109, 1},
  1416  		{0x110B, 0x110C, 1},
  1417  		{0x110E, 0x1112, 1},
  1418  		{0x113C, 0x1140, 2},
  1419  		{0x114C, 0x1150, 2},
  1420  		{0x1154, 0x1155, 1},
  1421  		{0x1159, 0x1159, 1},
  1422  		{0x115F, 0x1161, 1},
  1423  		{0x1163, 0x1169, 2},
  1424  		{0x116D, 0x116E, 1},
  1425  		{0x1172, 0x1173, 1},
  1426  		{0x1175, 0x119E, 0x119E - 0x1175},
  1427  		{0x11A8, 0x11AB, 0x11AB - 0x11A8},
  1428  		{0x11AE, 0x11AF, 1},
  1429  		{0x11B7, 0x11B8, 1},
  1430  		{0x11BA, 0x11BA, 1},
  1431  		{0x11BC, 0x11C2, 1},
  1432  		{0x11EB, 0x11F0, 0x11F0 - 0x11EB},
  1433  		{0x11F9, 0x11F9, 1},
  1434  		{0x1E00, 0x1E9B, 1},
  1435  		{0x1EA0, 0x1EF9, 1},
  1436  		{0x1F00, 0x1F15, 1},
  1437  		{0x1F18, 0x1F1D, 1},
  1438  		{0x1F20, 0x1F45, 1},
  1439  		{0x1F48, 0x1F4D, 1},
  1440  		{0x1F50, 0x1F57, 1},
  1441  		{0x1F59, 0x1F5B, 0x1F5B - 0x1F59},
  1442  		{0x1F5D, 0x1F5D, 1},
  1443  		{0x1F5F, 0x1F7D, 1},
  1444  		{0x1F80, 0x1FB4, 1},
  1445  		{0x1FB6, 0x1FBC, 1},
  1446  		{0x1FBE, 0x1FBE, 1},
  1447  		{0x1FC2, 0x1FC4, 1},
  1448  		{0x1FC6, 0x1FCC, 1},
  1449  		{0x1FD0, 0x1FD3, 1},
  1450  		{0x1FD6, 0x1FDB, 1},
  1451  		{0x1FE0, 0x1FEC, 1},
  1452  		{0x1FF2, 0x1FF4, 1},
  1453  		{0x1FF6, 0x1FFC, 1},
  1454  		{0x2126, 0x2126, 1},
  1455  		{0x212A, 0x212B, 1},
  1456  		{0x212E, 0x212E, 1},
  1457  		{0x2180, 0x2182, 1},
  1458  		{0x3007, 0x3007, 1},
  1459  		{0x3021, 0x3029, 1},
  1460  		{0x3041, 0x3094, 1},
  1461  		{0x30A1, 0x30FA, 1},
  1462  		{0x3105, 0x312C, 1},
  1463  		{0x4E00, 0x9FA5, 1},
  1464  		{0xAC00, 0xD7A3, 1},
  1465  	},
  1466  }
  1467  
  1468  var second = &unicode.RangeTable{
  1469  	R16: []unicode.Range16{
  1470  		{0x002D, 0x002E, 1},
  1471  		{0x0030, 0x0039, 1},
  1472  		{0x00B7, 0x00B7, 1},
  1473  		{0x02D0, 0x02D1, 1},
  1474  		{0x0300, 0x0345, 1},
  1475  		{0x0360, 0x0361, 1},
  1476  		{0x0387, 0x0387, 1},
  1477  		{0x0483, 0x0486, 1},
  1478  		{0x0591, 0x05A1, 1},
  1479  		{0x05A3, 0x05B9, 1},
  1480  		{0x05BB, 0x05BD, 1},
  1481  		{0x05BF, 0x05BF, 1},
  1482  		{0x05C1, 0x05C2, 1},
  1483  		{0x05C4, 0x0640, 0x0640 - 0x05C4},
  1484  		{0x064B, 0x0652, 1},
  1485  		{0x0660, 0x0669, 1},
  1486  		{0x0670, 0x0670, 1},
  1487  		{0x06D6, 0x06DC, 1},
  1488  		{0x06DD, 0x06DF, 1},
  1489  		{0x06E0, 0x06E4, 1},
  1490  		{0x06E7, 0x06E8, 1},
  1491  		{0x06EA, 0x06ED, 1},
  1492  		{0x06F0, 0x06F9, 1},
  1493  		{0x0901, 0x0903, 1},
  1494  		{0x093C, 0x093C, 1},
  1495  		{0x093E, 0x094C, 1},
  1496  		{0x094D, 0x094D, 1},
  1497  		{0x0951, 0x0954, 1},
  1498  		{0x0962, 0x0963, 1},
  1499  		{0x0966, 0x096F, 1},
  1500  		{0x0981, 0x0983, 1},
  1501  		{0x09BC, 0x09BC, 1},
  1502  		{0x09BE, 0x09BF, 1},
  1503  		{0x09C0, 0x09C4, 1},
  1504  		{0x09C7, 0x09C8, 1},
  1505  		{0x09CB, 0x09CD, 1},
  1506  		{0x09D7, 0x09D7, 1},
  1507  		{0x09E2, 0x09E3, 1},
  1508  		{0x09E6, 0x09EF, 1},
  1509  		{0x0A02, 0x0A3C, 0x3A},
  1510  		{0x0A3E, 0x0A3F, 1},
  1511  		{0x0A40, 0x0A42, 1},
  1512  		{0x0A47, 0x0A48, 1},
  1513  		{0x0A4B, 0x0A4D, 1},
  1514  		{0x0A66, 0x0A6F, 1},
  1515  		{0x0A70, 0x0A71, 1},
  1516  		{0x0A81, 0x0A83, 1},
  1517  		{0x0ABC, 0x0ABC, 1},
  1518  		{0x0ABE, 0x0AC5, 1},
  1519  		{0x0AC7, 0x0AC9, 1},
  1520  		{0x0ACB, 0x0ACD, 1},
  1521  		{0x0AE6, 0x0AEF, 1},
  1522  		{0x0B01, 0x0B03, 1},
  1523  		{0x0B3C, 0x0B3C, 1},
  1524  		{0x0B3E, 0x0B43, 1},
  1525  		{0x0B47, 0x0B48, 1},
  1526  		{0x0B4B, 0x0B4D, 1},
  1527  		{0x0B56, 0x0B57, 1},
  1528  		{0x0B66, 0x0B6F, 1},
  1529  		{0x0B82, 0x0B83, 1},
  1530  		{0x0BBE, 0x0BC2, 1},
  1531  		{0x0BC6, 0x0BC8, 1},
  1532  		{0x0BCA, 0x0BCD, 1},
  1533  		{0x0BD7, 0x0BD7, 1},
  1534  		{0x0BE7, 0x0BEF, 1},
  1535  		{0x0C01, 0x0C03, 1},
  1536  		{0x0C3E, 0x0C44, 1},
  1537  		{0x0C46, 0x0C48, 1},
  1538  		{0x0C4A, 0x0C4D, 1},
  1539  		{0x0C55, 0x0C56, 1},
  1540  		{0x0C66, 0x0C6F, 1},
  1541  		{0x0C82, 0x0C83, 1},
  1542  		{0x0CBE, 0x0CC4, 1},
  1543  		{0x0CC6, 0x0CC8, 1},
  1544  		{0x0CCA, 0x0CCD, 1},
  1545  		{0x0CD5, 0x0CD6, 1},
  1546  		{0x0CE6, 0x0CEF, 1},
  1547  		{0x0D02, 0x0D03, 1},
  1548  		{0x0D3E, 0x0D43, 1},
  1549  		{0x0D46, 0x0D48, 1},
  1550  		{0x0D4A, 0x0D4D, 1},
  1551  		{0x0D57, 0x0D57, 1},
  1552  		{0x0D66, 0x0D6F, 1},
  1553  		{0x0E31, 0x0E31, 1},
  1554  		{0x0E34, 0x0E3A, 1},
  1555  		{0x0E46, 0x0E46, 1},
  1556  		{0x0E47, 0x0E4E, 1},
  1557  		{0x0E50, 0x0E59, 1},
  1558  		{0x0EB1, 0x0EB1, 1},
  1559  		{0x0EB4, 0x0EB9, 1},
  1560  		{0x0EBB, 0x0EBC, 1},
  1561  		{0x0EC6, 0x0EC6, 1},
  1562  		{0x0EC8, 0x0ECD, 1},
  1563  		{0x0ED0, 0x0ED9, 1},
  1564  		{0x0F18, 0x0F19, 1},
  1565  		{0x0F20, 0x0F29, 1},
  1566  		{0x0F35, 0x0F39, 2},
  1567  		{0x0F3E, 0x0F3F, 1},
  1568  		{0x0F71, 0x0F84, 1},
  1569  		{0x0F86, 0x0F8B, 1},
  1570  		{0x0F90, 0x0F95, 1},
  1571  		{0x0F97, 0x0F97, 1},
  1572  		{0x0F99, 0x0FAD, 1},
  1573  		{0x0FB1, 0x0FB7, 1},
  1574  		{0x0FB9, 0x0FB9, 1},
  1575  		{0x20D0, 0x20DC, 1},
  1576  		{0x20E1, 0x3005, 0x3005 - 0x20E1},
  1577  		{0x302A, 0x302F, 1},
  1578  		{0x3031, 0x3035, 1},
  1579  		{0x3099, 0x309A, 1},
  1580  		{0x309D, 0x309E, 1},
  1581  		{0x30FC, 0x30FE, 1},
  1582  	},
  1583  }
  1584  
  1585  // HTMLEntity is an entity map containing translations for the
  1586  // standard HTML entity characters.
  1587  //
  1588  // See the Decoder.Strict and Decoder.Entity fields' documentation.
  1589  var HTMLEntity map[string]string = htmlEntity
  1590  
  1591  var htmlEntity = map[string]string{
  1592  	/*
  1593  		hget http://www.w3.org/TR/html4/sgml/entities.html |
  1594  		ssam '
  1595  			,y /\&gt;/ x/\&lt;(.|\n)+/ s/\n/ /g
  1596  			,x v/^\&lt;!ENTITY/d
  1597  			,s/\&lt;!ENTITY ([^ ]+) .*U\+([0-9A-F][0-9A-F][0-9A-F][0-9A-F]) .+/	"\1": "\\u\2",/g
  1598  		'
  1599  	*/
  1600  	"nbsp":     "\u00A0",
  1601  	"iexcl":    "\u00A1",
  1602  	"cent":     "\u00A2",
  1603  	"pound":    "\u00A3",
  1604  	"curren":   "\u00A4",
  1605  	"yen":      "\u00A5",
  1606  	"brvbar":   "\u00A6",
  1607  	"sect":     "\u00A7",
  1608  	"uml":      "\u00A8",
  1609  	"copy":     "\u00A9",
  1610  	"ordf":     "\u00AA",
  1611  	"laquo":    "\u00AB",
  1612  	"not":      "\u00AC",
  1613  	"shy":      "\u00AD",
  1614  	"reg":      "\u00AE",
  1615  	"macr":     "\u00AF",
  1616  	"deg":      "\u00B0",
  1617  	"plusmn":   "\u00B1",
  1618  	"sup2":     "\u00B2",
  1619  	"sup3":     "\u00B3",
  1620  	"acute":    "\u00B4",
  1621  	"micro":    "\u00B5",
  1622  	"para":     "\u00B6",
  1623  	"middot":   "\u00B7",
  1624  	"cedil":    "\u00B8",
  1625  	"sup1":     "\u00B9",
  1626  	"ordm":     "\u00BA",
  1627  	"raquo":    "\u00BB",
  1628  	"frac14":   "\u00BC",
  1629  	"frac12":   "\u00BD",
  1630  	"frac34":   "\u00BE",
  1631  	"iquest":   "\u00BF",
  1632  	"Agrave":   "\u00C0",
  1633  	"Aacute":   "\u00C1",
  1634  	"Acirc":    "\u00C2",
  1635  	"Atilde":   "\u00C3",
  1636  	"Auml":     "\u00C4",
  1637  	"Aring":    "\u00C5",
  1638  	"AElig":    "\u00C6",
  1639  	"Ccedil":   "\u00C7",
  1640  	"Egrave":   "\u00C8",
  1641  	"Eacute":   "\u00C9",
  1642  	"Ecirc":    "\u00CA",
  1643  	"Euml":     "\u00CB",
  1644  	"Igrave":   "\u00CC",
  1645  	"Iacute":   "\u00CD",
  1646  	"Icirc":    "\u00CE",
  1647  	"Iuml":     "\u00CF",
  1648  	"ETH":      "\u00D0",
  1649  	"Ntilde":   "\u00D1",
  1650  	"Ograve":   "\u00D2",
  1651  	"Oacute":   "\u00D3",
  1652  	"Ocirc":    "\u00D4",
  1653  	"Otilde":   "\u00D5",
  1654  	"Ouml":     "\u00D6",
  1655  	"times":    "\u00D7",
  1656  	"Oslash":   "\u00D8",
  1657  	"Ugrave":   "\u00D9",
  1658  	"Uacute":   "\u00DA",
  1659  	"Ucirc":    "\u00DB",
  1660  	"Uuml":     "\u00DC",
  1661  	"Yacute":   "\u00DD",
  1662  	"THORN":    "\u00DE",
  1663  	"szlig":    "\u00DF",
  1664  	"agrave":   "\u00E0",
  1665  	"aacute":   "\u00E1",
  1666  	"acirc":    "\u00E2",
  1667  	"atilde":   "\u00E3",
  1668  	"auml":     "\u00E4",
  1669  	"aring":    "\u00E5",
  1670  	"aelig":    "\u00E6",
  1671  	"ccedil":   "\u00E7",
  1672  	"egrave":   "\u00E8",
  1673  	"eacute":   "\u00E9",
  1674  	"ecirc":    "\u00EA",
  1675  	"euml":     "\u00EB",
  1676  	"igrave":   "\u00EC",
  1677  	"iacute":   "\u00ED",
  1678  	"icirc":    "\u00EE",
  1679  	"iuml":     "\u00EF",
  1680  	"eth":      "\u00F0",
  1681  	"ntilde":   "\u00F1",
  1682  	"ograve":   "\u00F2",
  1683  	"oacute":   "\u00F3",
  1684  	"ocirc":    "\u00F4",
  1685  	"otilde":   "\u00F5",
  1686  	"ouml":     "\u00F6",
  1687  	"divide":   "\u00F7",
  1688  	"oslash":   "\u00F8",
  1689  	"ugrave":   "\u00F9",
  1690  	"uacute":   "\u00FA",
  1691  	"ucirc":    "\u00FB",
  1692  	"uuml":     "\u00FC",
  1693  	"yacute":   "\u00FD",
  1694  	"thorn":    "\u00FE",
  1695  	"yuml":     "\u00FF",
  1696  	"fnof":     "\u0192",
  1697  	"Alpha":    "\u0391",
  1698  	"Beta":     "\u0392",
  1699  	"Gamma":    "\u0393",
  1700  	"Delta":    "\u0394",
  1701  	"Epsilon":  "\u0395",
  1702  	"Zeta":     "\u0396",
  1703  	"Eta":      "\u0397",
  1704  	"Theta":    "\u0398",
  1705  	"Iota":     "\u0399",
  1706  	"Kappa":    "\u039A",
  1707  	"Lambda":   "\u039B",
  1708  	"Mu":       "\u039C",
  1709  	"Nu":       "\u039D",
  1710  	"Xi":       "\u039E",
  1711  	"Omicron":  "\u039F",
  1712  	"Pi":       "\u03A0",
  1713  	"Rho":      "\u03A1",
  1714  	"Sigma":    "\u03A3",
  1715  	"Tau":      "\u03A4",
  1716  	"Upsilon":  "\u03A5",
  1717  	"Phi":      "\u03A6",
  1718  	"Chi":      "\u03A7",
  1719  	"Psi":      "\u03A8",
  1720  	"Omega":    "\u03A9",
  1721  	"alpha":    "\u03B1",
  1722  	"beta":     "\u03B2",
  1723  	"gamma":    "\u03B3",
  1724  	"delta":    "\u03B4",
  1725  	"epsilon":  "\u03B5",
  1726  	"zeta":     "\u03B6",
  1727  	"eta":      "\u03B7",
  1728  	"theta":    "\u03B8",
  1729  	"iota":     "\u03B9",
  1730  	"kappa":    "\u03BA",
  1731  	"lambda":   "\u03BB",
  1732  	"mu":       "\u03BC",
  1733  	"nu":       "\u03BD",
  1734  	"xi":       "\u03BE",
  1735  	"omicron":  "\u03BF",
  1736  	"pi":       "\u03C0",
  1737  	"rho":      "\u03C1",
  1738  	"sigmaf":   "\u03C2",
  1739  	"sigma":    "\u03C3",
  1740  	"tau":      "\u03C4",
  1741  	"upsilon":  "\u03C5",
  1742  	"phi":      "\u03C6",
  1743  	"chi":      "\u03C7",
  1744  	"psi":      "\u03C8",
  1745  	"omega":    "\u03C9",
  1746  	"thetasym": "\u03D1",
  1747  	"upsih":    "\u03D2",
  1748  	"piv":      "\u03D6",
  1749  	"bull":     "\u2022",
  1750  	"hellip":   "\u2026",
  1751  	"prime":    "\u2032",
  1752  	"Prime":    "\u2033",
  1753  	"oline":    "\u203E",
  1754  	"frasl":    "\u2044",
  1755  	"weierp":   "\u2118",
  1756  	"image":    "\u2111",
  1757  	"real":     "\u211C",
  1758  	"trade":    "\u2122",
  1759  	"alefsym":  "\u2135",
  1760  	"larr":     "\u2190",
  1761  	"uarr":     "\u2191",
  1762  	"rarr":     "\u2192",
  1763  	"darr":     "\u2193",
  1764  	"harr":     "\u2194",
  1765  	"crarr":    "\u21B5",
  1766  	"lArr":     "\u21D0",
  1767  	"uArr":     "\u21D1",
  1768  	"rArr":     "\u21D2",
  1769  	"dArr":     "\u21D3",
  1770  	"hArr":     "\u21D4",
  1771  	"forall":   "\u2200",
  1772  	"part":     "\u2202",
  1773  	"exist":    "\u2203",
  1774  	"empty":    "\u2205",
  1775  	"nabla":    "\u2207",
  1776  	"isin":     "\u2208",
  1777  	"notin":    "\u2209",
  1778  	"ni":       "\u220B",
  1779  	"prod":     "\u220F",
  1780  	"sum":      "\u2211",
  1781  	"minus":    "\u2212",
  1782  	"lowast":   "\u2217",
  1783  	"radic":    "\u221A",
  1784  	"prop":     "\u221D",
  1785  	"infin":    "\u221E",
  1786  	"ang":      "\u2220",
  1787  	"and":      "\u2227",
  1788  	"or":       "\u2228",
  1789  	"cap":      "\u2229",
  1790  	"cup":      "\u222A",
  1791  	"int":      "\u222B",
  1792  	"there4":   "\u2234",
  1793  	"sim":      "\u223C",
  1794  	"cong":     "\u2245",
  1795  	"asymp":    "\u2248",
  1796  	"ne":       "\u2260",
  1797  	"equiv":    "\u2261",
  1798  	"le":       "\u2264",
  1799  	"ge":       "\u2265",
  1800  	"sub":      "\u2282",
  1801  	"sup":      "\u2283",
  1802  	"nsub":     "\u2284",
  1803  	"sube":     "\u2286",
  1804  	"supe":     "\u2287",
  1805  	"oplus":    "\u2295",
  1806  	"otimes":   "\u2297",
  1807  	"perp":     "\u22A5",
  1808  	"sdot":     "\u22C5",
  1809  	"lceil":    "\u2308",
  1810  	"rceil":    "\u2309",
  1811  	"lfloor":   "\u230A",
  1812  	"rfloor":   "\u230B",
  1813  	"lang":     "\u2329",
  1814  	"rang":     "\u232A",
  1815  	"loz":      "\u25CA",
  1816  	"spades":   "\u2660",
  1817  	"clubs":    "\u2663",
  1818  	"hearts":   "\u2665",
  1819  	"diams":    "\u2666",
  1820  	"quot":     "\u0022",
  1821  	"amp":      "\u0026",
  1822  	"lt":       "\u003C",
  1823  	"gt":       "\u003E",
  1824  	"OElig":    "\u0152",
  1825  	"oelig":    "\u0153",
  1826  	"Scaron":   "\u0160",
  1827  	"scaron":   "\u0161",
  1828  	"Yuml":     "\u0178",
  1829  	"circ":     "\u02C6",
  1830  	"tilde":    "\u02DC",
  1831  	"ensp":     "\u2002",
  1832  	"emsp":     "\u2003",
  1833  	"thinsp":   "\u2009",
  1834  	"zwnj":     "\u200C",
  1835  	"zwj":      "\u200D",
  1836  	"lrm":      "\u200E",
  1837  	"rlm":      "\u200F",
  1838  	"ndash":    "\u2013",
  1839  	"mdash":    "\u2014",
  1840  	"lsquo":    "\u2018",
  1841  	"rsquo":    "\u2019",
  1842  	"sbquo":    "\u201A",
  1843  	"ldquo":    "\u201C",
  1844  	"rdquo":    "\u201D",
  1845  	"bdquo":    "\u201E",
  1846  	"dagger":   "\u2020",
  1847  	"Dagger":   "\u2021",
  1848  	"permil":   "\u2030",
  1849  	"lsaquo":   "\u2039",
  1850  	"rsaquo":   "\u203A",
  1851  	"euro":     "\u20AC",
  1852  }
  1853  
  1854  // HTMLAutoClose is the set of HTML elements that
  1855  // should be considered to close automatically.
  1856  //
  1857  // See the Decoder.Strict and Decoder.Entity fields' documentation.
  1858  var HTMLAutoClose []string = htmlAutoClose
  1859  
  1860  var htmlAutoClose = []string{
  1861  	/*
  1862  		hget http://www.w3.org/TR/html4/loose.dtd |
  1863  		9 sed -n 's/<!ELEMENT ([^ ]*) +- O EMPTY.+/	"\1",/p' | tr A-Z a-z
  1864  	*/
  1865  	"basefont",
  1866  	"br",
  1867  	"area",
  1868  	"link",
  1869  	"img",
  1870  	"param",
  1871  	"hr",
  1872  	"input",
  1873  	"col",
  1874  	"frame",
  1875  	"isindex",
  1876  	"base",
  1877  	"meta",
  1878  }
  1879  
  1880  var (
  1881  	escQuot = []byte("&#34;") // shorter than "&quot;"
  1882  	escApos = []byte("&#39;") // shorter than "&apos;"
  1883  	escAmp  = []byte("&amp;")
  1884  	escLT   = []byte("&lt;")
  1885  	escGT   = []byte("&gt;")
  1886  	escTab  = []byte("&#x9;")
  1887  	escNL   = []byte("&#xA;")
  1888  	escCR   = []byte("&#xD;")
  1889  	escFFFD = []byte("\uFFFD") // Unicode replacement character
  1890  )
  1891  
  1892  // EscapeText writes to w the properly escaped XML equivalent
  1893  // of the plain text data s.
  1894  func EscapeText(w io.Writer, s []byte) error {
  1895  	return escapeText(w, s, true)
  1896  }
  1897  
  1898  // escapeText writes to w the properly escaped XML equivalent
  1899  // of the plain text data s. If escapeNewline is true, newline
  1900  // characters will be escaped.
  1901  func escapeText(w io.Writer, s []byte, escapeNewline bool) error {
  1902  	var esc []byte
  1903  	last := 0
  1904  	for i := 0; i < len(s); {
  1905  		r, width := utf8.DecodeRune(s[i:])
  1906  		i += width
  1907  		switch r {
  1908  		case '"':
  1909  			esc = escQuot
  1910  		case '\'':
  1911  			esc = escApos
  1912  		case '&':
  1913  			esc = escAmp
  1914  		case '<':
  1915  			esc = escLT
  1916  		case '>':
  1917  			esc = escGT
  1918  		case '\t':
  1919  			esc = escTab
  1920  		case '\n':
  1921  			if !escapeNewline {
  1922  				continue
  1923  			}
  1924  			esc = escNL
  1925  		case '\r':
  1926  			esc = escCR
  1927  		default:
  1928  			if !isInCharacterRange(r) || (r == 0xFFFD && width == 1) {
  1929  				esc = escFFFD
  1930  				break
  1931  			}
  1932  			continue
  1933  		}
  1934  		if _, err := w.Write(s[last : i-width]); err != nil {
  1935  			return err
  1936  		}
  1937  		if _, err := w.Write(esc); err != nil {
  1938  			return err
  1939  		}
  1940  		last = i
  1941  	}
  1942  	_, err := w.Write(s[last:])
  1943  	return err
  1944  }
  1945  
  1946  // EscapeString writes to p the properly escaped XML equivalent
  1947  // of the plain text data s.
  1948  func (p *printer) EscapeString(s string) {
  1949  	var esc []byte
  1950  	last := 0
  1951  	for i := 0; i < len(s); {
  1952  		r, width := utf8.DecodeRuneInString(s[i:])
  1953  		i += width
  1954  		switch r {
  1955  		case '"':
  1956  			esc = escQuot
  1957  		case '\'':
  1958  			esc = escApos
  1959  		case '&':
  1960  			esc = escAmp
  1961  		case '<':
  1962  			esc = escLT
  1963  		case '>':
  1964  			esc = escGT
  1965  		case '\t':
  1966  			esc = escTab
  1967  		case '\n':
  1968  			esc = escNL
  1969  		case '\r':
  1970  			esc = escCR
  1971  		default:
  1972  			if !isInCharacterRange(r) || (r == 0xFFFD && width == 1) {
  1973  				esc = escFFFD
  1974  				break
  1975  			}
  1976  			continue
  1977  		}
  1978  		p.WriteString(s[last : i-width])
  1979  		p.Write(esc)
  1980  		last = i
  1981  	}
  1982  	p.WriteString(s[last:])
  1983  }
  1984  
  1985  // Escape is like EscapeText but omits the error return value.
  1986  // It is provided for backwards compatibility with Go 1.0.
  1987  // Code targeting Go 1.1 or later should use EscapeText.
  1988  func Escape(w io.Writer, s []byte) {
  1989  	EscapeText(w, s)
  1990  }
  1991  
  1992  var (
  1993  	cdataStart  = []byte("<![CDATA[")
  1994  	cdataEnd    = []byte("]]>")
  1995  	cdataEscape = []byte("]]]]><![CDATA[>")
  1996  )
  1997  
  1998  // emitCDATA writes to w the CDATA-wrapped plain text data s.
  1999  // It escapes CDATA directives nested in s.
  2000  func emitCDATA(w io.Writer, s []byte) error {
  2001  	if len(s) == 0 {
  2002  		return nil
  2003  	}
  2004  	if _, err := w.Write(cdataStart); err != nil {
  2005  		return err
  2006  	}
  2007  	for {
  2008  		i := bytes.Index(s, cdataEnd)
  2009  		if i >= 0 && i+len(cdataEnd) <= len(s) {
  2010  			// Found a nested CDATA directive end.
  2011  			if _, err := w.Write(s[:i]); err != nil {
  2012  				return err
  2013  			}
  2014  			if _, err := w.Write(cdataEscape); err != nil {
  2015  				return err
  2016  			}
  2017  			i += len(cdataEnd)
  2018  		} else {
  2019  			if _, err := w.Write(s); err != nil {
  2020  				return err
  2021  			}
  2022  			break
  2023  		}
  2024  		s = s[i:]
  2025  	}
  2026  	_, err := w.Write(cdataEnd)
  2027  	return err
  2028  }
  2029  
  2030  // procInst parses the `param="..."` or `param='...'`
  2031  // value out of the provided string, returning "" if not found.
  2032  func procInst(param, s string) string {
  2033  	// TODO: this parsing is somewhat lame and not exact.
  2034  	// It works for all actual cases, though.
  2035  	param = param + "="
  2036  	idx := strings.Index(s, param)
  2037  	if idx == -1 {
  2038  		return ""
  2039  	}
  2040  	v := s[idx+len(param):]
  2041  	if v == "" {
  2042  		return ""
  2043  	}
  2044  	if v[0] != '\'' && v[0] != '"' {
  2045  		return ""
  2046  	}
  2047  	idx = strings.IndexRune(v[1:], rune(v[0]))
  2048  	if idx == -1 {
  2049  		return ""
  2050  	}
  2051  	return v[1 : idx+1]
  2052  }
  2053  

View as plain text