bitwriter.go 961 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package brotli
  2. /* Copyright 2010 Google Inc. All Rights Reserved.
  3. Distributed under MIT license.
  4. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
  5. */
  6. /* Write bits into a byte array. */
  7. type bitWriter struct {
  8. dst []byte
  9. // Data waiting to be written is the low nbits of bits.
  10. bits uint64
  11. nbits uint
  12. }
  13. func (w *bitWriter) writeBits(nb uint, b uint64) {
  14. w.bits |= b << w.nbits
  15. w.nbits += nb
  16. if w.nbits >= 32 {
  17. bits := w.bits
  18. w.bits >>= 32
  19. w.nbits -= 32
  20. w.dst = append(w.dst,
  21. byte(bits),
  22. byte(bits>>8),
  23. byte(bits>>16),
  24. byte(bits>>24),
  25. )
  26. }
  27. }
  28. func (w *bitWriter) writeSingleBit(bit bool) {
  29. if bit {
  30. w.writeBits(1, 1)
  31. } else {
  32. w.writeBits(1, 0)
  33. }
  34. }
  35. func (w *bitWriter) jumpToByteBoundary() {
  36. dst := w.dst
  37. for w.nbits != 0 {
  38. dst = append(dst, byte(w.bits))
  39. w.bits >>= 8
  40. if w.nbits > 8 { // Avoid underflow
  41. w.nbits -= 8
  42. } else {
  43. w.nbits = 0
  44. }
  45. }
  46. w.bits = 0
  47. w.dst = dst
  48. }