github.com/vmware/govmomi@v0.51.0/vim25/types/byte_slice.go (about) 1 // © Broadcom. All Rights Reserved. 2 // The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. 3 // SPDX-License-Identifier: Apache-2.0 4 5 package types 6 7 import ( 8 "fmt" 9 "io" 10 "math" 11 "strconv" 12 13 "github.com/vmware/govmomi/vim25/xml" 14 ) 15 16 // ByteSlice implements vCenter compatibile xml encoding and decoding for a byte slice. 17 // vCenter encodes each byte of the array in its own xml element, whereas 18 // Go encodes the entire byte array in a single xml element. 19 type ByteSlice []byte 20 21 // MarshalXML implements xml.Marshaler 22 func (b ByteSlice) MarshalXML(e *xml.Encoder, field xml.StartElement) error { 23 start := xml.StartElement{ 24 Name: field.Name, 25 } 26 for i := range b { 27 // Using int8() here to output a signed byte (issue #3615) 28 if err := e.EncodeElement(int8(b[i]), start); err != nil { 29 return err 30 } 31 } 32 return nil 33 } 34 35 // UnmarshalXML implements xml.Unmarshaler 36 func (b *ByteSlice) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { 37 for { 38 t, err := d.Token() 39 if err == io.EOF { 40 break 41 } 42 43 if c, ok := t.(xml.CharData); ok { 44 n, err := strconv.ParseInt(string(c), 10, 16) 45 if err != nil { 46 return err 47 } 48 if n > math.MaxUint8 { 49 return fmt.Errorf("parsing %q: uint8 overflow", start.Name.Local) 50 } 51 *b = append(*b, byte(n)) 52 } 53 } 54 55 return nil 56 }