main
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
5package lzma
6
7// directCodec allows the encoding and decoding of values with a fixed number
8// of bits. The number of bits must be in the range [1,32].
9type directCodec byte
10
11// Bits returns the number of bits supported by this codec.
12func (dc directCodec) Bits() int {
13 return int(dc)
14}
15
16// Encode uses the range encoder to encode a value with the fixed number of
17// bits. The most-significant bit is encoded first.
18func (dc directCodec) Encode(e *rangeEncoder, v uint32) error {
19 for i := int(dc) - 1; i >= 0; i-- {
20 if err := e.DirectEncodeBit(v >> uint(i)); err != nil {
21 return err
22 }
23 }
24 return nil
25}
26
27// Decode uses the range decoder to decode a value with the given number of
28// given bits. The most-significant bit is decoded first.
29func (dc directCodec) Decode(d *rangeDecoder) (v uint32, err error) {
30 for i := int(dc) - 1; i >= 0; i-- {
31 x, err := d.DirectDecodeBit()
32 if err != nil {
33 return 0, err
34 }
35 v = (v << 1) | x
36 }
37 return v, nil
38}