// Derived from github.com/nwaples/rardecode (BSD 2-Clause), see LICENSE. package rar5 import "io" // bitReader reads bits from the packed data of one file and stops with // io.EOF once the bit limit of the current compressed block is reached. type bitReader struct { r io.ByteReader v int // cache of bits read from r l int // number of bits (not cached) that can still be read from r n uint8 // number of unread bits in v } func (r *bitReader) reset(br io.ByteReader) { r.r = br r.v, r.l, r.n = 0, 0, 0 } func (r *bitReader) unreadBits(n uint8) { r.n += n } // readByte reads a whole byte; block headers are byte-aligned. func (r *bitReader) readByte() (byte, error) { if r.n == 0 { return r.r.ReadByte() } b, err := r.readBits(8) return byte(b), err } // setLimit sets the number of bits the current block holds. func (r *bitReader) setLimit(n int) { r.l = n r.n = 0 } // readBits returns n bits. n must be less than the integer size - 8. func (r *bitReader) readBits(n uint8) (int, error) { for n > r.n { if r.l == 0 { // reached the block's bit limit return 0, io.EOF } c, err := r.r.ReadByte() if err != nil { if err == io.EOF { err = ErrCorrupt } return 0, err } r.v = r.v<<8 | int(c) r.n += 8 r.l -= 8 if r.l < 0 { // overshot, discard the extra bits bits := uint8(-r.l) r.l = 0 r.v >>= bits r.n -= bits } } r.n -= n return (r.v >> r.n) & ((1 << n) - 1), nil }