/src/marshall.go

http://bone-aap.googlecode.com/ · Go · 69 lines · 58 code · 11 blank · 0 comment · 4 complexity · 2fd95837465f947239581b71f13bc3b1 MD5 · raw file

  1. package aal_net
  2. import (
  3. "reflect"
  4. "bytes"
  5. "encoding/binary"
  6. )
  7. type Marshallable interface {
  8. Marshall(interface{}) []byte
  9. Unmarshall([]byte) interface{}
  10. }
  11. type MarshallableThings struct {}
  12. func (MarshallableThings) Marshall(t interface{}) []byte {
  13. tValue := reflect.ValueOf(t)
  14. buf := bytes.NewBuffer([]byte{})
  15. for i := 0; i < tValue.NumField(); i += 1 {
  16. vField := tValue.Field(i)
  17. switch vField.Kind() {
  18. case reflect.Int:
  19. binary.Write(buf, binary.LittleEndian, int32(vField.Int()))
  20. case reflect.Int8:
  21. binary.Write(buf, binary.LittleEndian, int8(vField.Int()))
  22. case reflect.Int16:
  23. binary.Write(buf, binary.LittleEndian, int16(vField.Int()))
  24. case reflect.Int32:
  25. binary.Write(buf, binary.LittleEndian, int32(vField.Int()))
  26. case reflect.Int64:
  27. binary.Write(buf, binary.LittleEndian, int64(vField.Int()))
  28. case reflect.Uint:
  29. binary.Write(buf, binary.LittleEndian, uint32(vField.Int()))
  30. case reflect.Uint8:
  31. binary.Write(buf, binary.LittleEndian, uint8(vField.Int()))
  32. case reflect.Uint16:
  33. binary.Write(buf, binary.LittleEndian, uint16(vField.Int()))
  34. case reflect.Uint32:
  35. binary.Write(buf, binary.LittleEndian, uint32(vField.Int()))
  36. case reflect.Uint64:
  37. binary.Write(buf, binary.LittleEndian, uint64(vField.Int()))
  38. case reflect.Bool:
  39. if vField.Bool() {
  40. binary.Write(buf, binary.LittleEndian, uint8(1))
  41. } else {
  42. binary.Write(buf, binary.LittleEndian, uint8(0))
  43. }
  44. case reflect.String:
  45. s := vField.String()
  46. binary.Write(buf, binary.LittleEndian, uint16(len(s)))
  47. binary.Write(buf, binary.LittleEndian, []byte(s))
  48. }
  49. }
  50. return buf.Bytes()
  51. }
  52. func (MarshallableThings) Unmarshall([]byte) interface{} {
  53. return nil
  54. }
  55. func marshallNum(result []byte, num interface{}) {
  56. }
  57. func marshallString(result []byte) {
  58. }