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.

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