github.com/vmware/govmomi@v0.37.2/toolbox/hgfs/encoding.go (about) 1 /* 2 Copyright (c) 2017 VMware, Inc. All Rights Reserved. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package hgfs 18 19 import ( 20 "bytes" 21 "encoding" 22 "encoding/binary" 23 ) 24 25 // MarshalBinary is a wrapper around binary.Write 26 func MarshalBinary(fields ...interface{}) ([]byte, error) { 27 buf := new(bytes.Buffer) 28 29 for _, p := range fields { 30 switch m := p.(type) { 31 case encoding.BinaryMarshaler: 32 data, err := m.MarshalBinary() 33 if err != nil { 34 return nil, ProtocolError(err) 35 } 36 37 _, _ = buf.Write(data) 38 case []byte: 39 _, _ = buf.Write(m) 40 case string: 41 _, _ = buf.WriteString(m) 42 default: 43 err := binary.Write(buf, binary.LittleEndian, p) 44 if err != nil { 45 return nil, ProtocolError(err) 46 } 47 } 48 } 49 50 return buf.Bytes(), nil 51 } 52 53 // UnmarshalBinary is a wrapper around binary.Read 54 func UnmarshalBinary(data []byte, fields ...interface{}) error { 55 buf := bytes.NewBuffer(data) 56 57 for _, p := range fields { 58 switch m := p.(type) { 59 case encoding.BinaryUnmarshaler: 60 return m.UnmarshalBinary(buf.Bytes()) 61 case *[]byte: 62 *m = buf.Bytes() 63 return nil 64 default: 65 err := binary.Read(buf, binary.LittleEndian, p) 66 if err != nil { 67 return ProtocolError(err) 68 } 69 } 70 } 71 72 return nil 73 }