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.

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