properties.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. import (
  6. "errors"
  7. "fmt"
  8. )
  9. // maximum and minimum values for the LZMA properties.
  10. const (
  11. minPB = 0
  12. maxPB = 4
  13. )
  14. // maxPropertyCode is the possible maximum of a properties code byte.
  15. const maxPropertyCode = (maxPB+1)*(maxLP+1)*(maxLC+1) - 1
  16. // Properties contains the parameters LC, LP and PB. The parameter LC
  17. // defines the number of literal context bits; parameter LP the number
  18. // of literal position bits and PB the number of position bits.
  19. type Properties struct {
  20. LC int
  21. LP int
  22. PB int
  23. }
  24. // String returns the properties in a string representation.
  25. func (p *Properties) String() string {
  26. return fmt.Sprintf("LC %d LP %d PB %d", p.LC, p.LP, p.PB)
  27. }
  28. // PropertiesForCode converts a properties code byte into a Properties value.
  29. func PropertiesForCode(code byte) (p Properties, err error) {
  30. if code > maxPropertyCode {
  31. return p, errors.New("lzma: invalid properties code")
  32. }
  33. p.LC = int(code % 9)
  34. code /= 9
  35. p.LP = int(code % 5)
  36. code /= 5
  37. p.PB = int(code % 5)
  38. return p, err
  39. }
  40. // verify checks the properties for correctness.
  41. func (p *Properties) verify() error {
  42. if p == nil {
  43. return errors.New("lzma: properties are nil")
  44. }
  45. if !(minLC <= p.LC && p.LC <= maxLC) {
  46. return errors.New("lzma: lc out of range")
  47. }
  48. if !(minLP <= p.LP && p.LP <= maxLP) {
  49. return errors.New("lzma: lp out of range")
  50. }
  51. if !(minPB <= p.PB && p.PB <= maxPB) {
  52. return errors.New("lzma: pb out of range")
  53. }
  54. return nil
  55. }
  56. // Code converts the properties to a byte. The function assumes that
  57. // the properties components are all in range.
  58. func (p Properties) Code() byte {
  59. return byte((p.PB*5+p.LP)*9 + p.LC)
  60. }