2013-11-05 08:25:17 +08:00
|
|
|
package sftp
|
|
|
|
|
2013-11-05 08:36:47 +08:00
|
|
|
import (
|
|
|
|
"fmt"
|
2013-11-05 09:03:58 +08:00
|
|
|
"reflect"
|
2013-11-05 08:36:47 +08:00
|
|
|
)
|
|
|
|
|
2013-11-05 08:25:17 +08:00
|
|
|
func marshalUint32(b []byte, v uint32) []byte {
|
|
|
|
return append(b, byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
|
|
|
|
}
|
|
|
|
|
|
|
|
func marshalUint64(b []byte, v uint64) []byte {
|
|
|
|
return marshalUint32(marshalUint32(b, uint32(v>>24)), uint32(v))
|
|
|
|
}
|
|
|
|
|
|
|
|
func marshalString(b []byte, v string) []byte {
|
|
|
|
return append(marshalUint32(b, uint32(len(v))), v...)
|
|
|
|
}
|
2013-11-05 08:36:47 +08:00
|
|
|
|
|
|
|
func marshal(b []byte, v interface{}) []byte {
|
|
|
|
switch v := v.(type) {
|
|
|
|
case uint32:
|
|
|
|
return marshalUint32(b, v)
|
|
|
|
case uint64:
|
|
|
|
return marshalUint64(b, v)
|
|
|
|
case string:
|
|
|
|
return marshalString(b, v)
|
|
|
|
default:
|
2013-11-05 09:03:58 +08:00
|
|
|
switch d := reflect.ValueOf(v); d.Kind() {
|
|
|
|
case reflect.Struct:
|
|
|
|
for i, n := 0, d.NumField(); i < n; i++ {
|
|
|
|
b = append(marshal(b, d.Field(i).Interface()))
|
|
|
|
}
|
|
|
|
return b
|
|
|
|
default:
|
|
|
|
panic(fmt.Sprintf("marshal(%#v): cannot handle type %T", v, v))
|
|
|
|
}
|
2013-11-05 08:36:47 +08:00
|
|
|
}
|
|
|
|
}
|
2013-11-05 09:23:48 +08:00
|
|
|
|
|
|
|
func unmarshalUint32(b []byte) (uint32, []byte) {
|
|
|
|
v := uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24
|
|
|
|
return v, b[4:]
|
|
|
|
}
|
|
|
|
|
|
|
|
func unmarshalUint64(b []byte) (uint64, []byte) {
|
|
|
|
h, b := unmarshalUint32(b)
|
|
|
|
l, b := unmarshalUint32(b)
|
|
|
|
return uint64(h)<<32 | uint64(l), b
|
|
|
|
}
|
2013-11-05 09:31:20 +08:00
|
|
|
|
|
|
|
func unmarshalString(b []byte) (string, []byte) {
|
|
|
|
n, b := unmarshalUint32(b)
|
|
|
|
return string(b[:n]), b[n:]
|
|
|
|
}
|