github.com/razvanm/vanadium-go-1.3@v0.0.0-20160721203343-4a65068e5915/src/encoding/xml/xml.go (about)

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