reader.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. package mstypes
  2. import (
  3. "bufio"
  4. "encoding/binary"
  5. "fmt"
  6. "io"
  7. )
  8. // Byte sizes of primitive types
  9. const (
  10. SizeBool = 1
  11. SizeChar = 1
  12. SizeUint8 = 1
  13. SizeUint16 = 2
  14. SizeUint32 = 4
  15. SizeUint64 = 8
  16. SizeEnum = 2
  17. SizeSingle = 4
  18. SizeDouble = 8
  19. SizePtr = 4
  20. )
  21. // Reader reads simple byte stream data into a Go representations
  22. type Reader struct {
  23. r *bufio.Reader // source of the data
  24. }
  25. // NewReader creates a new instance of a simple Reader.
  26. func NewReader(r io.Reader) *Reader {
  27. reader := new(Reader)
  28. reader.r = bufio.NewReader(r)
  29. return reader
  30. }
  31. func (r *Reader) Read(p []byte) (n int, err error) {
  32. return r.r.Read(p)
  33. }
  34. func (r *Reader) Uint8() (uint8, error) {
  35. b, err := r.r.ReadByte()
  36. if err != nil {
  37. return uint8(0), err
  38. }
  39. return uint8(b), nil
  40. }
  41. func (r *Reader) Uint16() (uint16, error) {
  42. b, err := r.ReadBytes(SizeUint16)
  43. if err != nil {
  44. return uint16(0), err
  45. }
  46. return binary.LittleEndian.Uint16(b), nil
  47. }
  48. func (r *Reader) Uint32() (uint32, error) {
  49. b, err := r.ReadBytes(SizeUint32)
  50. if err != nil {
  51. return uint32(0), err
  52. }
  53. return binary.LittleEndian.Uint32(b), nil
  54. }
  55. func (r *Reader) Uint64() (uint64, error) {
  56. b, err := r.ReadBytes(SizeUint64)
  57. if err != nil {
  58. return uint64(0), err
  59. }
  60. return binary.LittleEndian.Uint64(b), nil
  61. }
  62. func (r *Reader) FileTime() (f FileTime, err error) {
  63. f.LowDateTime, err = r.Uint32()
  64. if err != nil {
  65. return
  66. }
  67. f.HighDateTime, err = r.Uint32()
  68. if err != nil {
  69. return
  70. }
  71. return
  72. }
  73. // UTF16String returns a string that is UTF16 encoded in a byte slice. n is the number of bytes representing the string
  74. func (r *Reader) UTF16String(n int) (str string, err error) {
  75. //Length divided by 2 as each run is 16bits = 2bytes
  76. s := make([]rune, n/2, n/2)
  77. for i := 0; i < len(s); i++ {
  78. var u uint16
  79. u, err = r.Uint16()
  80. if err != nil {
  81. return
  82. }
  83. s[i] = rune(u)
  84. }
  85. str = string(s)
  86. return
  87. }
  88. // readBytes returns a number of bytes from the NDR byte stream.
  89. func (r *Reader) ReadBytes(n int) ([]byte, error) {
  90. //TODO make this take an int64 as input to allow for larger values on all systems?
  91. b := make([]byte, n, n)
  92. m, err := r.r.Read(b)
  93. if err != nil || m != n {
  94. return b, fmt.Errorf("error reading bytes from stream: %v", err)
  95. }
  96. return b, nil
  97. }