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.

88 lines
2.1 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. readReflectBinary(rv, rt, Options{}, r, n, err)
  11. return o
  12. } else {
  13. ptrRv := reflect.New(rt)
  14. readReflectBinary(ptrRv.Elem(), rt, Options{}, r, n, err)
  15. return ptrRv.Elem().Interface()
  16. }
  17. }
  18. func ReadBinaryPtr(o interface{}, r io.Reader, n *int64, err *error) interface{} {
  19. rv, rt := reflect.ValueOf(o), reflect.TypeOf(o)
  20. if rv.Kind() == reflect.Ptr {
  21. readReflectBinary(rv.Elem(), rt.Elem(), Options{}, r, n, err)
  22. return o
  23. } else {
  24. panic("ReadBinaryPtr expects o to be a pointer")
  25. }
  26. }
  27. func WriteBinary(o interface{}, w io.Writer, n *int64, err *error) {
  28. rv := reflect.ValueOf(o)
  29. rt := reflect.TypeOf(o)
  30. writeReflectBinary(rv, rt, Options{}, w, n, err)
  31. }
  32. func ReadJSON(o interface{}, bytes []byte, err *error) interface{} {
  33. var object interface{}
  34. *err = json.Unmarshal(bytes, &object)
  35. if *err != nil {
  36. return o
  37. }
  38. return ReadJSONObject(o, object, err)
  39. }
  40. func ReadJSONObject(o interface{}, object interface{}, err *error) interface{} {
  41. rv, rt := reflect.ValueOf(o), reflect.TypeOf(o)
  42. if rv.Kind() == reflect.Ptr {
  43. readReflectJSON(rv.Elem(), rt.Elem(), object, err)
  44. return o
  45. } else {
  46. ptrRv := reflect.New(rt)
  47. readReflectJSON(ptrRv.Elem(), rt, object, err)
  48. return ptrRv.Elem().Interface()
  49. }
  50. }
  51. func WriteJSON(o interface{}, w io.Writer, n *int64, err *error) {
  52. rv := reflect.ValueOf(o)
  53. rt := reflect.TypeOf(o)
  54. if rv.Kind() == reflect.Ptr {
  55. rv, rt = rv.Elem(), rt.Elem()
  56. }
  57. writeReflectJSON(rv, rt, w, n, err)
  58. }
  59. // Write all of bz to w
  60. // Increment n and set err accordingly.
  61. func WriteTo(bz []byte, w io.Writer, n *int64, err *error) {
  62. if *err != nil {
  63. return
  64. }
  65. n_, err_ := w.Write(bz)
  66. *n += int64(n_)
  67. *err = err_
  68. }
  69. // Read len(buf) from r
  70. // Increment n and set err accordingly.
  71. func ReadFull(buf []byte, r io.Reader, n *int64, err *error) {
  72. if *err != nil {
  73. return
  74. }
  75. n_, err_ := io.ReadFull(r, buf)
  76. *n += int64(n_)
  77. *err = err_
  78. }