write_bits.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package brotli
  2. import "encoding/binary"
  3. /* Copyright 2010 Google Inc. All Rights Reserved.
  4. Distributed under MIT license.
  5. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
  6. */
  7. /* Write bits into a byte array. */
  8. /* This function writes bits into bytes in increasing addresses, and within
  9. a byte least-significant-bit first.
  10. The function can write up to 56 bits in one go with WriteBits
  11. Example: let's assume that 3 bits (Rs below) have been written already:
  12. BYTE-0 BYTE+1 BYTE+2
  13. 0000 0RRR 0000 0000 0000 0000
  14. Now, we could write 5 or less bits in MSB by just sifting by 3
  15. and OR'ing to BYTE-0.
  16. For n bits, we take the last 5 bits, OR that with high bits in BYTE-0,
  17. and locate the rest in BYTE+1, BYTE+2, etc. */
  18. func writeBits(n_bits uint, bits uint64, pos *uint, array []byte) {
  19. /* This branch of the code can write up to 56 bits at a time,
  20. 7 bits are lost by being perhaps already in *p and at least
  21. 1 bit is needed to initialize the bit-stream ahead (i.e. if 7
  22. bits are in *p and we write 57 bits, then the next write will
  23. access a byte that was never initialized). */
  24. p := array[*pos>>3:]
  25. v := uint64(p[0])
  26. v |= bits << (*pos & 7)
  27. binary.LittleEndian.PutUint64(p, v)
  28. *pos += n_bits
  29. }
  30. func writeSingleBit(bit bool, pos *uint, array []byte) {
  31. if bit {
  32. writeBits(1, 1, pos, array)
  33. } else {
  34. writeBits(1, 0, pos, array)
  35. }
  36. }
  37. func writeBitsPrepareStorage(pos uint, array []byte) {
  38. assert(pos&7 == 0)
  39. array[pos>>3] = 0
  40. }