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.

71 lines
1.5 KiB

10 years ago
11 years ago
11 years ago
  1. package binary
  2. import (
  3. "encoding/json"
  4. "io"
  5. "reflect"
  6. )
  7. func ReadBinary(o interface{}, r io.Reader, n *int64, err *error) interface{} {
  8. rv, rt := reflect.ValueOf(o), reflect.TypeOf(o)
  9. if rv.Kind() == reflect.Ptr {
  10. readReflect(rv.Elem(), rt.Elem(), r, n, err)
  11. return o
  12. } else {
  13. ptrRv := reflect.New(rt)
  14. readReflect(ptrRv.Elem(), rt, r, n, err)
  15. return ptrRv.Elem().Interface()
  16. }
  17. }
  18. func WriteBinary(o interface{}, w io.Writer, n *int64, err *error) {
  19. rv := reflect.ValueOf(o)
  20. rt := reflect.TypeOf(o)
  21. writeReflect(rv, rt, w, n, err)
  22. }
  23. func ReadJSON(o interface{}, bytes []byte, err *error) interface{} {
  24. var parsed interface{}
  25. *err = json.Unmarshal(bytes, &parsed)
  26. if *err != nil {
  27. return o
  28. }
  29. rv, rt := reflect.ValueOf(o), reflect.TypeOf(o)
  30. if rv.Kind() == reflect.Ptr {
  31. readReflectJSON(rv.Elem(), rt.Elem(), parsed, err)
  32. return o
  33. } else {
  34. ptrRv := reflect.New(rt)
  35. readReflectJSON(ptrRv.Elem(), rt, parsed, err)
  36. return ptrRv.Elem().Interface()
  37. }
  38. }
  39. func WriteJSON(o interface{}, w io.Writer, n *int64, err *error) {
  40. rv := reflect.ValueOf(o)
  41. rt := reflect.TypeOf(o)
  42. writeReflectJSON(rv, rt, w, n, err)
  43. }
  44. // Write all of bz to w
  45. // Increment n and set err accordingly.
  46. func WriteTo(bz []byte, w io.Writer, n *int64, err *error) {
  47. if *err != nil {
  48. return
  49. }
  50. n_, err_ := w.Write(bz)
  51. *n += int64(n_)
  52. *err = err_
  53. }
  54. // Read len(buf) from r
  55. // Increment n and set err accordingly.
  56. func ReadFull(buf []byte, r io.Reader, n *int64, err *error) {
  57. if *err != nil {
  58. return
  59. }
  60. n_, err_ := io.ReadFull(r, buf)
  61. *n += int64(n_)
  62. *err = err_
  63. }