You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.0 KiB

10 years ago
11 years ago
11 years ago
  1. package binary
  2. import (
  3. "io"
  4. "reflect"
  5. )
  6. type Unreader interface {
  7. io.Reader
  8. UnreadByte() error
  9. }
  10. func ReadBinary(o interface{}, r Unreader, n *int64, err *error) interface{} {
  11. rv, rt := reflect.ValueOf(o), reflect.TypeOf(o)
  12. if rv.Kind() == reflect.Ptr {
  13. readReflect(rv.Elem(), rt.Elem(), r, n, err)
  14. return o
  15. } else {
  16. ptrRv := reflect.New(rt)
  17. readReflect(ptrRv.Elem(), rt, r, n, err)
  18. return ptrRv.Elem().Interface()
  19. }
  20. }
  21. func WriteBinary(o interface{}, w io.Writer, n *int64, err *error) {
  22. rv := reflect.ValueOf(o)
  23. rt := reflect.TypeOf(o)
  24. writeReflect(rv, rt, w, n, err)
  25. }
  26. // Write all of bz to w
  27. // Increment n and set err accordingly.
  28. func WriteTo(bz []byte, w io.Writer, n *int64, err *error) {
  29. if *err != nil {
  30. return
  31. }
  32. n_, err_ := w.Write(bz)
  33. *n += int64(n_)
  34. *err = err_
  35. }
  36. // Read len(buf) from r
  37. // Increment n and set err accordingly.
  38. func ReadFull(buf []byte, r io.Reader, n *int64, err *error) {
  39. if *err != nil {
  40. return
  41. }
  42. n_, err_ := io.ReadFull(r, buf)
  43. *n += int64(n_)
  44. *err = err_
  45. }