golomb_reader.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package bits
  2. import (
  3. "io"
  4. )
  5. type GolombBitReader struct {
  6. R io.Reader
  7. buf [1]byte
  8. left byte
  9. }
  10. func (self *GolombBitReader) ReadBit() (res uint, err error) {
  11. if self.left == 0 {
  12. if _, err = self.R.Read(self.buf[:]); err != nil {
  13. return
  14. }
  15. self.left = 8
  16. }
  17. self.left--
  18. res = uint(self.buf[0]>>self.left) & 1
  19. return
  20. }
  21. func (self *GolombBitReader) ReadBits(n int) (res uint, err error) {
  22. for i := 0; i < n; i++ {
  23. var bit uint
  24. if bit, err = self.ReadBit(); err != nil {
  25. return
  26. }
  27. res |= bit << uint(n-i-1)
  28. }
  29. return
  30. }
  31. func (self *GolombBitReader) ReadExponentialGolombCode() (res uint, err error) {
  32. i := 0
  33. for {
  34. var bit uint
  35. if bit, err = self.ReadBit(); err != nil {
  36. return
  37. }
  38. if !(bit == 0 && i < 32) {
  39. break
  40. }
  41. i++
  42. }
  43. if res, err = self.ReadBits(i); err != nil {
  44. return
  45. }
  46. res += (1 << uint(i)) - 1
  47. return
  48. }
  49. func (self *GolombBitReader) ReadSE() (res uint, err error) {
  50. if res, err = self.ReadExponentialGolombCode(); err != nil {
  51. return
  52. }
  53. if res&0x01 != 0 {
  54. res = (res + 1) / 2
  55. } else {
  56. res = -res / 2
  57. }
  58. return
  59. }