prob.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Copyright 2014-2022 Ulrich Kunitz. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package lzma
  5. // movebits defines the number of bits used for the updates of probability
  6. // values.
  7. const movebits = 5
  8. // probbits defines the number of bits of a probability value.
  9. const probbits = 11
  10. // probInit defines 0.5 as initial value for prob values.
  11. const probInit prob = 1 << (probbits - 1)
  12. // Type prob represents probabilities. The type can also be used to encode and
  13. // decode single bits.
  14. type prob uint16
  15. // Dec decreases the probability. The decrease is proportional to the
  16. // probability value.
  17. func (p *prob) dec() {
  18. *p -= *p >> movebits
  19. }
  20. // Inc increases the probability. The Increase is proportional to the
  21. // difference of 1 and the probability value.
  22. func (p *prob) inc() {
  23. *p += ((1 << probbits) - *p) >> movebits
  24. }
  25. // Computes the new bound for a given range using the probability value.
  26. func (p prob) bound(r uint32) uint32 {
  27. return (r >> probbits) * uint32(p)
  28. }
  29. // Bits returns 1. One is the number of bits that can be encoded or decoded
  30. // with a single prob value.
  31. func (p prob) Bits() int {
  32. return 1
  33. }
  34. // Encode encodes the least-significant bit of v. Note that the p value will be
  35. // changed.
  36. func (p *prob) Encode(e *rangeEncoder, v uint32) error {
  37. return e.EncodeBit(v, p)
  38. }
  39. // Decode decodes a single bit. Note that the p value will change.
  40. func (p *prob) Decode(d *rangeDecoder) (v uint32, err error) {
  41. return d.DecodeBit(p)
  42. }