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.

95 lines
2.3 KiB

10 years ago
11 years ago
11 years ago
  1. package binary
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "io"
  6. "reflect"
  7. )
  8. // TODO document and maybe make it configurable.
  9. const MaxBinaryReadSize = 21 * 1024 * 1024
  10. var ErrBinaryReadSizeOverflow = errors.New("Error: binary read size overflow")
  11. var ErrBinaryReadSizeUnderflow = errors.New("Error: binary read size underflow")
  12. func ReadBinary(o interface{}, r io.Reader, n *int64, err *error) interface{} {
  13. rv, rt := reflect.ValueOf(o), reflect.TypeOf(o)
  14. if rv.Kind() == reflect.Ptr {
  15. readReflectBinary(rv, rt, Options{}, r, n, err)
  16. return o
  17. } else {
  18. ptrRv := reflect.New(rt)
  19. readReflectBinary(ptrRv.Elem(), rt, Options{}, r, n, err)
  20. return ptrRv.Elem().Interface()
  21. }
  22. }
  23. func ReadBinaryPtr(o interface{}, r io.Reader, n *int64, err *error) interface{} {
  24. rv, rt := reflect.ValueOf(o), reflect.TypeOf(o)
  25. if rv.Kind() == reflect.Ptr {
  26. readReflectBinary(rv.Elem(), rt.Elem(), Options{}, r, n, err)
  27. return o
  28. } else {
  29. panic("ReadBinaryPtr expects o to be a pointer")
  30. }
  31. }
  32. func WriteBinary(o interface{}, w io.Writer, n *int64, err *error) {
  33. rv := reflect.ValueOf(o)
  34. rt := reflect.TypeOf(o)
  35. writeReflectBinary(rv, rt, Options{}, w, n, err)
  36. }
  37. func ReadJSON(o interface{}, bytes []byte, err *error) interface{} {
  38. var object interface{}
  39. *err = json.Unmarshal(bytes, &object)
  40. if *err != nil {
  41. return o
  42. }
  43. return ReadJSONObject(o, object, err)
  44. }
  45. func ReadJSONObject(o interface{}, object interface{}, err *error) interface{} {
  46. rv, rt := reflect.ValueOf(o), reflect.TypeOf(o)
  47. if rv.Kind() == reflect.Ptr {
  48. readReflectJSON(rv.Elem(), rt.Elem(), object, err)
  49. return o
  50. } else {
  51. ptrRv := reflect.New(rt)
  52. readReflectJSON(ptrRv.Elem(), rt, object, err)
  53. return ptrRv.Elem().Interface()
  54. }
  55. }
  56. func WriteJSON(o interface{}, w io.Writer, n *int64, err *error) {
  57. rv := reflect.ValueOf(o)
  58. rt := reflect.TypeOf(o)
  59. if rv.Kind() == reflect.Ptr {
  60. rv, rt = rv.Elem(), rt.Elem()
  61. }
  62. writeReflectJSON(rv, rt, w, n, err)
  63. }
  64. // Write all of bz to w
  65. // Increment n and set err accordingly.
  66. func WriteTo(bz []byte, w io.Writer, n *int64, err *error) {
  67. if *err != nil {
  68. return
  69. }
  70. n_, err_ := w.Write(bz)
  71. *n += int64(n_)
  72. *err = err_
  73. }
  74. // Read len(buf) from r
  75. // Increment n and set err accordingly.
  76. func ReadFull(buf []byte, r io.Reader, n *int64, err *error) {
  77. if *err != nil {
  78. return
  79. }
  80. n_, err_ := io.ReadFull(r, buf)
  81. *n += int64(n_)
  82. *err = err_
  83. }