github.com/vmware/govmomi@v0.51.0/vim25/xml/read.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
     6  
     7  import (
     8  	"bytes"
     9  	"encoding"
    10  	"errors"
    11  	"fmt"
    12  	"reflect"
    13  	"runtime"
    14  	"strconv"
    15  	"strings"
    16  )
    17  
    18  // BUG(rsc): Mapping between XML elements and data structures is inherently flawed:
    19  // an XML element is an order-dependent collection of anonymous
    20  // values, while a data structure is an order-independent collection
    21  // of named values.
    22  // See [encoding/json] for a textual representation more suitable
    23  // to data structures.
    24  
    25  // Unmarshal parses the XML-encoded data and stores the result in
    26  // the value pointed to by v, which must be an arbitrary struct,
    27  // slice, or string. Well-formed data that does not fit into v is
    28  // discarded.
    29  //
    30  // Because Unmarshal uses the reflect package, it can only assign
    31  // to exported (upper case) fields. Unmarshal uses a case-sensitive
    32  // comparison to match XML element names to tag values and struct
    33  // field names.
    34  //
    35  // Unmarshal maps an XML element to a struct using the following rules.
    36  // In the rules, the tag of a field refers to the value associated with the
    37  // key 'xml' in the struct field's tag (see the example above).
    38  //
    39  //   - If the struct has a field of type []byte or string with tag
    40  //     ",innerxml", Unmarshal accumulates the raw XML nested inside the
    41  //     element in that field. The rest of the rules still apply.
    42  //
    43  //   - If the struct has a field named XMLName of type Name,
    44  //     Unmarshal records the element name in that field.
    45  //
    46  //   - If the XMLName field has an associated tag of the form
    47  //     "name" or "namespace-URL name", the XML element must have
    48  //     the given name (and, optionally, name space) or else Unmarshal
    49  //     returns an error.
    50  //
    51  //   - If the XML element has an attribute whose name matches a
    52  //     struct field name with an associated tag containing ",attr" or
    53  //     the explicit name in a struct field tag of the form "name,attr",
    54  //     Unmarshal records the attribute value in that field.
    55  //
    56  //   - If the XML element has an attribute not handled by the previous
    57  //     rule and the struct has a field with an associated tag containing
    58  //     ",any,attr", Unmarshal records the attribute value in the first
    59  //     such field.
    60  //
    61  //   - If the XML element contains character data, that data is
    62  //     accumulated in the first struct field that has tag ",chardata".
    63  //     The struct field may have type []byte or string.
    64  //     If there is no such field, the character data is discarded.
    65  //
    66  //   - If the XML element contains comments, they are accumulated in
    67  //     the first struct field that has tag ",comment".  The struct
    68  //     field may have type []byte or string. If there is no such
    69  //     field, the comments are discarded.
    70  //
    71  //   - If the XML element contains a sub-element whose name matches
    72  //     the prefix of a tag formatted as "a" or "a>b>c", unmarshal
    73  //     will descend into the XML structure looking for elements with the
    74  //     given names, and will map the innermost elements to that struct
    75  //     field. A tag starting with ">" is equivalent to one starting
    76  //     with the field name followed by ">".
    77  //
    78  //   - If the XML element contains a sub-element whose name matches
    79  //     a struct field's XMLName tag and the struct field has no
    80  //     explicit name tag as per the previous rule, unmarshal maps
    81  //     the sub-element to that struct field.
    82  //
    83  //   - If the XML element contains a sub-element whose name matches a
    84  //     field without any mode flags (",attr", ",chardata", etc), Unmarshal
    85  //     maps the sub-element to that struct field.
    86  //
    87  //   - If the XML element contains a sub-element that hasn't matched any
    88  //     of the above rules and the struct has a field with tag ",any",
    89  //     unmarshal maps the sub-element to that struct field.
    90  //
    91  //   - An anonymous struct field is handled as if the fields of its
    92  //     value were part of the outer struct.
    93  //
    94  //   - A struct field with tag "-" is never unmarshaled into.
    95  //
    96  // If Unmarshal encounters a field type that implements the Unmarshaler
    97  // interface, Unmarshal calls its UnmarshalXML method to produce the value from
    98  // the XML element.  Otherwise, if the value implements
    99  // [encoding.TextUnmarshaler], Unmarshal calls that value's UnmarshalText method.
   100  //
   101  // Unmarshal maps an XML element to a string or []byte by saving the
   102  // concatenation of that element's character data in the string or
   103  // []byte. The saved []byte is never nil.
   104  //
   105  // Unmarshal maps an attribute value to a string or []byte by saving
   106  // the value in the string or slice.
   107  //
   108  // Unmarshal maps an attribute value to an [Attr] by saving the attribute,
   109  // including its name, in the Attr.
   110  //
   111  // Unmarshal maps an XML element or attribute value to a slice by
   112  // extending the length of the slice and mapping the element or attribute
   113  // to the newly created value.
   114  //
   115  // Unmarshal maps an XML element or attribute value to a bool by
   116  // setting it to the boolean value represented by the string. Whitespace
   117  // is trimmed and ignored.
   118  //
   119  // Unmarshal maps an XML element or attribute value to an integer or
   120  // floating-point field by setting the field to the result of
   121  // interpreting the string value in decimal. There is no check for
   122  // overflow. Whitespace is trimmed and ignored.
   123  //
   124  // Unmarshal maps an XML element to a Name by recording the element
   125  // name.
   126  //
   127  // Unmarshal maps an XML element to a pointer by setting the pointer
   128  // to a freshly allocated value and then mapping the element to that value.
   129  //
   130  // A missing element or empty attribute value will be unmarshaled as a zero value.
   131  // If the field is a slice, a zero value will be appended to the field. Otherwise, the
   132  // field will be set to its zero value.
   133  func Unmarshal(data []byte, v any) error {
   134  	return NewDecoder(bytes.NewReader(data)).Decode(v)
   135  }
   136  
   137  // Decode works like [Unmarshal], except it reads the decoder
   138  // stream to find the start element.
   139  func (d *Decoder) Decode(v any) error {
   140  	return d.DecodeElement(v, nil)
   141  }
   142  
   143  // DecodeElement works like [Unmarshal] except that it takes
   144  // a pointer to the start XML element to decode into v.
   145  // It is useful when a client reads some raw XML tokens itself
   146  // but also wants to defer to [Unmarshal] for some elements.
   147  func (d *Decoder) DecodeElement(v any, start *StartElement) error {
   148  	val := reflect.ValueOf(v)
   149  	if val.Kind() != reflect.Pointer {
   150  		return errors.New("non-pointer passed to Unmarshal")
   151  	}
   152  
   153  	if val.IsNil() {
   154  		return errors.New("nil pointer passed to Unmarshal")
   155  	}
   156  	return d.unmarshal(val.Elem(), start, 0)
   157  }
   158  
   159  // An UnmarshalError represents an error in the unmarshaling process.
   160  type UnmarshalError string
   161  
   162  func (e UnmarshalError) Error() string { return string(e) }
   163  
   164  // Unmarshaler is the interface implemented by objects that can unmarshal
   165  // an XML element description of themselves.
   166  //
   167  // UnmarshalXML decodes a single XML element
   168  // beginning with the given start element.
   169  // If it returns an error, the outer call to Unmarshal stops and
   170  // returns that error.
   171  // UnmarshalXML must consume exactly one XML element.
   172  // One common implementation strategy is to unmarshal into
   173  // a separate value with a layout matching the expected XML
   174  // using d.DecodeElement, and then to copy the data from
   175  // that value into the receiver.
   176  // Another common strategy is to use d.Token to process the
   177  // XML object one token at a time.
   178  // UnmarshalXML may not use d.RawToken.
   179  type Unmarshaler interface {
   180  	UnmarshalXML(d *Decoder, start StartElement) error
   181  }
   182  
   183  // UnmarshalerAttr is the interface implemented by objects that can unmarshal
   184  // an XML attribute description of themselves.
   185  //
   186  // UnmarshalXMLAttr decodes a single XML attribute.
   187  // If it returns an error, the outer call to [Unmarshal] stops and
   188  // returns that error.
   189  // UnmarshalXMLAttr is used only for struct fields with the
   190  // "attr" option in the field tag.
   191  type UnmarshalerAttr interface {
   192  	UnmarshalXMLAttr(attr Attr) error
   193  }
   194  
   195  // receiverType returns the receiver type to use in an expression like "%s.MethodName".
   196  func receiverType(val any) string {
   197  	t := reflect.TypeOf(val)
   198  	if t.Name() != "" {
   199  		return t.String()
   200  	}
   201  	return "(" + t.String() + ")"
   202  }
   203  
   204  // unmarshalInterface unmarshals a single XML element into val.
   205  // start is the opening tag of the element.
   206  func (d *Decoder) unmarshalInterface(val Unmarshaler, start *StartElement) error {
   207  	// Record that decoder must stop at end tag corresponding to start.
   208  	d.pushEOF()
   209  
   210  	d.unmarshalDepth++
   211  	err := val.UnmarshalXML(d, *start)
   212  	d.unmarshalDepth--
   213  	if err != nil {
   214  		d.popEOF()
   215  		return err
   216  	}
   217  
   218  	if !d.popEOF() {
   219  		return fmt.Errorf("xml: %s.UnmarshalXML did not consume entire <%s> element", receiverType(val), start.Name.Local)
   220  	}
   221  
   222  	return nil
   223  }
   224  
   225  // unmarshalTextInterface unmarshals a single XML element into val.
   226  // The chardata contained in the element (but not its children)
   227  // is passed to the text unmarshaler.
   228  func (d *Decoder) unmarshalTextInterface(val encoding.TextUnmarshaler) error {
   229  	var buf []byte
   230  	depth := 1
   231  	for depth > 0 {
   232  		t, err := d.Token()
   233  		if err != nil {
   234  			return err
   235  		}
   236  		switch t := t.(type) {
   237  		case CharData:
   238  			if depth == 1 {
   239  				buf = append(buf, t...)
   240  			}
   241  		case StartElement:
   242  			depth++
   243  		case EndElement:
   244  			depth--
   245  		}
   246  	}
   247  	return val.UnmarshalText(buf)
   248  }
   249  
   250  // unmarshalAttr unmarshals a single XML attribute into val.
   251  func (d *Decoder) unmarshalAttr(val reflect.Value, attr Attr) error {
   252  	if val.Kind() == reflect.Pointer {
   253  		if val.IsNil() {
   254  			val.Set(reflect.New(val.Type().Elem()))
   255  		}
   256  		val = val.Elem()
   257  	}
   258  	if val.CanInterface() && val.Type().Implements(unmarshalerAttrType) {
   259  		// This is an unmarshaler with a non-pointer receiver,
   260  		// so it's likely to be incorrect, but we do what we're told.
   261  		return val.Interface().(UnmarshalerAttr).UnmarshalXMLAttr(attr)
   262  	}
   263  	if val.CanAddr() {
   264  		pv := val.Addr()
   265  		if pv.CanInterface() && pv.Type().Implements(unmarshalerAttrType) {
   266  			return pv.Interface().(UnmarshalerAttr).UnmarshalXMLAttr(attr)
   267  		}
   268  	}
   269  
   270  	// Not an UnmarshalerAttr; try encoding.TextUnmarshaler.
   271  	if val.CanInterface() && val.Type().Implements(textUnmarshalerType) {
   272  		// This is an unmarshaler with a non-pointer receiver,
   273  		// so it's likely to be incorrect, but we do what we're told.
   274  		return val.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(attr.Value))
   275  	}
   276  	if val.CanAddr() {
   277  		pv := val.Addr()
   278  		if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
   279  			return pv.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(attr.Value))
   280  		}
   281  	}
   282  
   283  	if val.Type().Kind() == reflect.Slice && val.Type().Elem().Kind() != reflect.Uint8 {
   284  		// Slice of element values.
   285  		// Grow slice.
   286  		n := val.Len()
   287  		val.Grow(1)
   288  		val.SetLen(n + 1)
   289  
   290  		// Recur to read element into slice.
   291  		if err := d.unmarshalAttr(val.Index(n), attr); err != nil {
   292  			val.SetLen(n)
   293  			return err
   294  		}
   295  		return nil
   296  	}
   297  
   298  	if val.Type() == attrType {
   299  		val.Set(reflect.ValueOf(attr))
   300  		return nil
   301  	}
   302  
   303  	return copyValue(val, []byte(attr.Value))
   304  }
   305  
   306  var (
   307  	attrType            = reflect.TypeFor[Attr]()
   308  	unmarshalerType     = reflect.TypeFor[Unmarshaler]()
   309  	unmarshalerAttrType = reflect.TypeFor[UnmarshalerAttr]()
   310  	textUnmarshalerType = reflect.TypeFor[encoding.TextUnmarshaler]()
   311  )
   312  
   313  const (
   314  	maxUnmarshalDepth     = 10000
   315  	maxUnmarshalDepthWasm = 5000 // go.dev/issue/56498
   316  )
   317  
   318  var errUnmarshalDepth = errors.New("exceeded max depth")
   319  
   320  // Unmarshal a single XML element into val.
   321  func (d *Decoder) unmarshal(val reflect.Value, start *StartElement, depth int) error {
   322  	if depth >= maxUnmarshalDepth || runtime.GOARCH == "wasm" && depth >= maxUnmarshalDepthWasm {
   323  		return errUnmarshalDepth
   324  	}
   325  	// Find start element if we need it.
   326  	if start == nil {
   327  		for {
   328  			tok, err := d.Token()
   329  			if err != nil {
   330  				return err
   331  			}
   332  			if t, ok := tok.(StartElement); ok {
   333  				start = &t
   334  				break
   335  			}
   336  		}
   337  	}
   338  
   339  	// Try to figure out type for empty interface values.
   340  	if val.Kind() == reflect.Interface && val.IsNil() {
   341  		typ := d.typeForElement(val, start)
   342  		if typ != nil {
   343  			pval := reflect.New(typ).Elem()
   344  			err := d.unmarshal(pval, start, depth)
   345  			if err != nil {
   346  				return err
   347  			}
   348  
   349  			for i := 0; i < 2; i++ {
   350  				if typ.Implements(val.Type()) {
   351  					val.Set(pval)
   352  					return nil
   353  				}
   354  
   355  				typ = reflect.PtrTo(typ)
   356  				pval = pval.Addr()
   357  			}
   358  
   359  			val.Set(pval)
   360  			return nil
   361  		}
   362  	}
   363  
   364  	// Load value from interface, but only if the result will be
   365  	// usefully addressable.
   366  	if val.Kind() == reflect.Interface && !val.IsNil() {
   367  		e := val.Elem()
   368  		if e.Kind() == reflect.Pointer && !e.IsNil() {
   369  			val = e
   370  		}
   371  	}
   372  
   373  	if val.Kind() == reflect.Pointer {
   374  		if val.IsNil() {
   375  			val.Set(reflect.New(val.Type().Elem()))
   376  		}
   377  		val = val.Elem()
   378  	}
   379  
   380  	if val.CanInterface() && val.Type().Implements(unmarshalerType) {
   381  		// This is an unmarshaler with a non-pointer receiver,
   382  		// so it's likely to be incorrect, but we do what we're told.
   383  		return d.unmarshalInterface(val.Interface().(Unmarshaler), start)
   384  	}
   385  
   386  	if val.CanAddr() {
   387  		pv := val.Addr()
   388  		if pv.CanInterface() && pv.Type().Implements(unmarshalerType) {
   389  			return d.unmarshalInterface(pv.Interface().(Unmarshaler), start)
   390  		}
   391  	}
   392  
   393  	if val.CanInterface() && val.Type().Implements(textUnmarshalerType) {
   394  		return d.unmarshalTextInterface(val.Interface().(encoding.TextUnmarshaler))
   395  	}
   396  
   397  	if val.CanAddr() {
   398  		pv := val.Addr()
   399  		if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
   400  			return d.unmarshalTextInterface(pv.Interface().(encoding.TextUnmarshaler))
   401  		}
   402  	}
   403  
   404  	var (
   405  		data         []byte
   406  		saveData     reflect.Value
   407  		comment      []byte
   408  		saveComment  reflect.Value
   409  		saveXML      reflect.Value
   410  		saveXMLIndex int
   411  		saveXMLData  []byte
   412  		saveAny      reflect.Value
   413  		sv           reflect.Value
   414  		tinfo        *typeInfo
   415  		err          error
   416  	)
   417  
   418  	switch v := val; v.Kind() {
   419  	default:
   420  		return errors.New("unknown type " + v.Type().String())
   421  
   422  	case reflect.Interface:
   423  		// TODO: For now, simply ignore the field. In the near
   424  		//       future we may choose to unmarshal the start
   425  		//       element on it, if not nil.
   426  		return d.Skip()
   427  
   428  	case reflect.Slice:
   429  		typ := v.Type()
   430  		if typ.Elem().Kind() == reflect.Uint8 {
   431  			// []byte
   432  			saveData = v
   433  			break
   434  		}
   435  
   436  		// Slice of element values.
   437  		// Grow slice.
   438  		n := v.Len()
   439  		v.Grow(1)
   440  		v.SetLen(n + 1)
   441  
   442  		// Recur to read element into slice.
   443  		if err := d.unmarshal(v.Index(n), start, depth+1); err != nil {
   444  			v.SetLen(n)
   445  			return err
   446  		}
   447  		return nil
   448  
   449  	case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.String:
   450  		saveData = v
   451  
   452  	case reflect.Struct:
   453  		typ := v.Type()
   454  		if typ == nameType {
   455  			v.Set(reflect.ValueOf(start.Name))
   456  			break
   457  		}
   458  
   459  		sv = v
   460  		tinfo, err = getTypeInfo(typ)
   461  		if err != nil {
   462  			return err
   463  		}
   464  
   465  		// Validate and assign element name.
   466  		if tinfo.xmlname != nil {
   467  			finfo := tinfo.xmlname
   468  			if finfo.name != "" && finfo.name != start.Name.Local {
   469  				return UnmarshalError("expected element type <" + finfo.name + "> but have <" + start.Name.Local + ">")
   470  			}
   471  			if finfo.xmlns != "" && finfo.xmlns != start.Name.Space {
   472  				e := "expected element <" + finfo.name + "> in name space " + finfo.xmlns + " but have "
   473  				if start.Name.Space == "" {
   474  					e += "no name space"
   475  				} else {
   476  					e += start.Name.Space
   477  				}
   478  				return UnmarshalError(e)
   479  			}
   480  			fv := finfo.value(sv, initNilPointers)
   481  			if _, ok := fv.Interface().(Name); ok {
   482  				fv.Set(reflect.ValueOf(start.Name))
   483  			}
   484  		}
   485  
   486  		// Assign attributes.
   487  		for _, a := range start.Attr {
   488  			handled := false
   489  			any := -1
   490  			for i := range tinfo.fields {
   491  				finfo := &tinfo.fields[i]
   492  				switch finfo.flags & fMode {
   493  				case fAttr:
   494  					strv := finfo.value(sv, initNilPointers)
   495  					if a.Name.Local == finfo.name && (finfo.xmlns == "" || finfo.xmlns == a.Name.Space) {
   496  						needTypeAttr := (finfo.flags & fTypeAttr) != 0
   497  						// HACK: avoid using xsi:type value for a "type" attribute, such as ManagedObjectReference.Type for example.
   498  						if needTypeAttr || (a.Name != xmlSchemaInstance && a.Name != xsiType) {
   499  							if err := d.unmarshalAttr(strv, a); err != nil {
   500  								return err
   501  							}
   502  						}
   503  						handled = true
   504  					}
   505  
   506  				case fAny | fAttr:
   507  					if any == -1 {
   508  						any = i
   509  					}
   510  				}
   511  			}
   512  			if !handled && any >= 0 {
   513  				finfo := &tinfo.fields[any]
   514  				strv := finfo.value(sv, initNilPointers)
   515  				if err := d.unmarshalAttr(strv, a); err != nil {
   516  					return err
   517  				}
   518  			}
   519  		}
   520  
   521  		// Determine whether we need to save character data or comments.
   522  		for i := range tinfo.fields {
   523  			finfo := &tinfo.fields[i]
   524  			switch finfo.flags & fMode {
   525  			case fCDATA, fCharData:
   526  				if !saveData.IsValid() {
   527  					saveData = finfo.value(sv, initNilPointers)
   528  				}
   529  
   530  			case fComment:
   531  				if !saveComment.IsValid() {
   532  					saveComment = finfo.value(sv, initNilPointers)
   533  				}
   534  
   535  			case fAny, fAny | fElement:
   536  				if !saveAny.IsValid() {
   537  					saveAny = finfo.value(sv, initNilPointers)
   538  				}
   539  
   540  			case fInnerXML:
   541  				if !saveXML.IsValid() {
   542  					saveXML = finfo.value(sv, initNilPointers)
   543  					if d.saved == nil {
   544  						saveXMLIndex = 0
   545  						d.saved = new(bytes.Buffer)
   546  					} else {
   547  						saveXMLIndex = d.savedOffset()
   548  					}
   549  				}
   550  			}
   551  		}
   552  	}
   553  
   554  	// Find end element.
   555  	// Process sub-elements along the way.
   556  Loop:
   557  	for {
   558  		var savedOffset int
   559  		if saveXML.IsValid() {
   560  			savedOffset = d.savedOffset()
   561  		}
   562  		tok, err := d.Token()
   563  		if err != nil {
   564  			return err
   565  		}
   566  		switch t := tok.(type) {
   567  		case StartElement:
   568  			consumed := false
   569  			if sv.IsValid() {
   570  				// unmarshalPath can call unmarshal, so we need to pass the depth through so that
   571  				// we can continue to enforce the maximum recursion limit.
   572  				consumed, err = d.unmarshalPath(tinfo, sv, nil, &t, depth)
   573  				if err != nil {
   574  					return err
   575  				}
   576  				if !consumed && saveAny.IsValid() {
   577  					consumed = true
   578  					if err := d.unmarshal(saveAny, &t, depth+1); err != nil {
   579  						return err
   580  					}
   581  				}
   582  			}
   583  			if !consumed {
   584  				if err := d.Skip(); err != nil {
   585  					return err
   586  				}
   587  			}
   588  
   589  		case EndElement:
   590  			if saveXML.IsValid() {
   591  				saveXMLData = d.saved.Bytes()[saveXMLIndex:savedOffset]
   592  				if saveXMLIndex == 0 {
   593  					d.saved = nil
   594  				}
   595  			}
   596  			break Loop
   597  
   598  		case CharData:
   599  			if saveData.IsValid() {
   600  				data = append(data, t...)
   601  			}
   602  
   603  		case Comment:
   604  			if saveComment.IsValid() {
   605  				comment = append(comment, t...)
   606  			}
   607  		}
   608  	}
   609  
   610  	if saveData.IsValid() && saveData.CanInterface() && saveData.Type().Implements(textUnmarshalerType) {
   611  		if err := saveData.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil {
   612  			return err
   613  		}
   614  		saveData = reflect.Value{}
   615  	}
   616  
   617  	if saveData.IsValid() && saveData.CanAddr() {
   618  		pv := saveData.Addr()
   619  		if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) {
   620  			if err := pv.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil {
   621  				return err
   622  			}
   623  			saveData = reflect.Value{}
   624  		}
   625  	}
   626  
   627  	if err := copyValue(saveData, data); err != nil {
   628  		return err
   629  	}
   630  
   631  	switch t := saveComment; t.Kind() {
   632  	case reflect.String:
   633  		t.SetString(string(comment))
   634  	case reflect.Slice:
   635  		t.Set(reflect.ValueOf(comment))
   636  	}
   637  
   638  	switch t := saveXML; t.Kind() {
   639  	case reflect.String:
   640  		t.SetString(string(saveXMLData))
   641  	case reflect.Slice:
   642  		if t.Type().Elem().Kind() == reflect.Uint8 {
   643  			t.Set(reflect.ValueOf(saveXMLData))
   644  		}
   645  	}
   646  
   647  	return nil
   648  }
   649  
   650  func copyValue(dst reflect.Value, src []byte) (err error) {
   651  	dst0 := dst
   652  
   653  	if dst.Kind() == reflect.Pointer {
   654  		if dst.IsNil() {
   655  			dst.Set(reflect.New(dst.Type().Elem()))
   656  		}
   657  		dst = dst.Elem()
   658  	}
   659  
   660  	// Save accumulated data.
   661  	switch dst.Kind() {
   662  	case reflect.Invalid:
   663  		// Probably a comment.
   664  	default:
   665  		return errors.New("cannot unmarshal into " + dst0.Type().String())
   666  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   667  		if len(src) == 0 {
   668  			dst.SetInt(0)
   669  			return nil
   670  		}
   671  		itmp, err := strconv.ParseInt(strings.TrimSpace(string(src)), 10, dst.Type().Bits())
   672  		if err != nil {
   673  			return err
   674  		}
   675  		dst.SetInt(itmp)
   676  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   677  		var utmp uint64
   678  		if len(src) > 0 && src[0] == '-' {
   679  			// Negative value for unsigned field.
   680  			// Assume it was serialized following two's complement.
   681  			itmp, err := strconv.ParseInt(string(src), 10, dst.Type().Bits())
   682  			if err != nil {
   683  				return err
   684  			}
   685  			// Reinterpret value based on type width.
   686  			switch dst.Type().Bits() {
   687  			case 8:
   688  				utmp = uint64(uint8(itmp))
   689  			case 16:
   690  				utmp = uint64(uint16(itmp))
   691  			case 32:
   692  				utmp = uint64(uint32(itmp))
   693  			case 64:
   694  				utmp = uint64(uint64(itmp))
   695  			}
   696  		} else {
   697  			if len(src) == 0 {
   698  				dst.SetUint(0)
   699  				return nil
   700  			}
   701  
   702  			utmp, err = strconv.ParseUint(strings.TrimSpace(string(src)), 10, dst.Type().Bits())
   703  			if err != nil {
   704  				return err
   705  			}
   706  		}
   707  		dst.SetUint(utmp)
   708  	case reflect.Float32, reflect.Float64:
   709  		if len(src) == 0 {
   710  			dst.SetFloat(0)
   711  			return nil
   712  		}
   713  		ftmp, err := strconv.ParseFloat(strings.TrimSpace(string(src)), dst.Type().Bits())
   714  		if err != nil {
   715  			return err
   716  		}
   717  		dst.SetFloat(ftmp)
   718  	case reflect.Bool:
   719  		if len(src) == 0 {
   720  			dst.SetBool(false)
   721  			return nil
   722  		}
   723  		value, err := strconv.ParseBool(strings.TrimSpace(string(src)))
   724  		if err != nil {
   725  			return err
   726  		}
   727  		dst.SetBool(value)
   728  	case reflect.String:
   729  		dst.SetString(string(src))
   730  	case reflect.Slice:
   731  		if len(src) == 0 {
   732  			// non-nil to flag presence
   733  			src = []byte{}
   734  		}
   735  		dst.SetBytes(src)
   736  	}
   737  	return nil
   738  }
   739  
   740  // unmarshalPath walks down an XML structure looking for wanted
   741  // paths, and calls unmarshal on them.
   742  // The consumed result tells whether XML elements have been consumed
   743  // from the Decoder until start's matching end element, or if it's
   744  // still untouched because start is uninteresting for sv's fields.
   745  func (d *Decoder) unmarshalPath(tinfo *typeInfo, sv reflect.Value, parents []string, start *StartElement, depth int) (consumed bool, err error) {
   746  	recurse := false
   747  Loop:
   748  	for i := range tinfo.fields {
   749  		finfo := &tinfo.fields[i]
   750  		if finfo.flags&fElement == 0 || len(finfo.parents) < len(parents) || finfo.xmlns != "" && finfo.xmlns != start.Name.Space {
   751  			continue
   752  		}
   753  		for j := range parents {
   754  			if parents[j] != finfo.parents[j] {
   755  				continue Loop
   756  			}
   757  		}
   758  		if len(finfo.parents) == len(parents) && finfo.name == start.Name.Local {
   759  			// It's a perfect match, unmarshal the field.
   760  			return true, d.unmarshal(finfo.value(sv, initNilPointers), start, depth+1)
   761  		}
   762  		if len(finfo.parents) > len(parents) && finfo.parents[len(parents)] == start.Name.Local {
   763  			// It's a prefix for the field. Break and recurse
   764  			// since it's not ok for one field path to be itself
   765  			// the prefix for another field path.
   766  			recurse = true
   767  
   768  			// We can reuse the same slice as long as we
   769  			// don't try to append to it.
   770  			parents = finfo.parents[:len(parents)+1]
   771  			break
   772  		}
   773  	}
   774  	if !recurse {
   775  		// We have no business with this element.
   776  		return false, nil
   777  	}
   778  	// The element is not a perfect match for any field, but one
   779  	// or more fields have the path to this element as a parent
   780  	// prefix. Recurse and attempt to match these.
   781  	for {
   782  		var tok Token
   783  		tok, err = d.Token()
   784  		if err != nil {
   785  			return true, err
   786  		}
   787  		switch t := tok.(type) {
   788  		case StartElement:
   789  			// the recursion depth of unmarshalPath is limited to the path length specified
   790  			// by the struct field tag, so we don't increment the depth here.
   791  			consumed2, err := d.unmarshalPath(tinfo, sv, parents, &t, depth)
   792  			if err != nil {
   793  				return true, err
   794  			}
   795  			if !consumed2 {
   796  				if err := d.Skip(); err != nil {
   797  					return true, err
   798  				}
   799  			}
   800  		case EndElement:
   801  			return true, nil
   802  		}
   803  	}
   804  }
   805  
   806  // Skip reads tokens until it has consumed the end element
   807  // matching the most recent start element already consumed,
   808  // skipping nested structures.
   809  // It returns nil if it finds an end element matching the start
   810  // element; otherwise it returns an error describing the problem.
   811  func (d *Decoder) Skip() error {
   812  	var depth int64
   813  	for {
   814  		tok, err := d.Token()
   815  		if err != nil {
   816  			return err
   817  		}
   818  		switch tok.(type) {
   819  		case StartElement:
   820  			depth++
   821  		case EndElement:
   822  			if depth == 0 {
   823  				return nil
   824  			}
   825  			depth--
   826  		}
   827  	}
   828  }