github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/bit/expgolomb/golomb.go (about)

     1  package expgolomb
     2  
     3  import "github.com/egonelbre/exp/bit"
     4  
     5  func WriteInt(w *bit.Writer, v int) {
     6  	if v == 0 {
     7  		w.WriteBit(1)
     8  		return
     9  	}
    10  
    11  	sign := 0
    12  	if v < 0 {
    13  		sign = 1
    14  		v = -v
    15  	}
    16  
    17  	nbits := bit.ScanRight(uint64(v)) + 1
    18  
    19  	w.WriteBits(0, nbits)
    20  	rbits := bit.Reverse(uint64(v), nbits)
    21  	w.WriteBits(rbits, nbits)
    22  	w.WriteBit(sign)
    23  }
    24  
    25  func ReadInt(r *bit.Reader) int {
    26  	nbits := uint(0)
    27  
    28  	zero, err := r.ReadBit(), r.Error()
    29  	for err == nil && zero == 0 {
    30  		nbits += 1
    31  		zero, err = r.ReadBit(), r.Error()
    32  	}
    33  
    34  	if nbits == 0 || err != nil {
    35  		return 0
    36  	}
    37  
    38  	x := r.ReadBits(nbits - 1)
    39  	x = x<<1 | 1
    40  	x = bit.Reverse(x, nbits)
    41  
    42  	sign := r.ReadBit()
    43  	v := int(x)
    44  	if sign == 1 {
    45  		v = -v
    46  	}
    47  
    48  	return v
    49  }
    50  
    51  func WriteUint(w *bit.Writer, v uint) {
    52  	if v == 0 {
    53  		w.WriteBit(1)
    54  		return
    55  	}
    56  
    57  	nbits := bit.ScanRight(uint64(v)) + 1
    58  
    59  	w.WriteBits(0, nbits)
    60  	rbits := bit.Reverse(uint64(v), nbits)
    61  	w.WriteBits(rbits, nbits)
    62  }
    63  
    64  func ReadUint(r *bit.Reader) uint {
    65  	nbits := uint(0)
    66  	zero, err := r.ReadBit(), r.Error()
    67  	for err == nil && zero == 0 {
    68  		nbits += 1
    69  		zero, err = r.ReadBit(), r.Error()
    70  	}
    71  
    72  	if nbits == 0 || err != nil {
    73  		return 0
    74  	}
    75  
    76  	x := r.ReadBits(nbits - 1)
    77  	x = x<<1 | 1
    78  	x = bit.Reverse(x, nbits)
    79  	return uint(x)
    80  }