Data::BitStream::Code::ARice - A Role implementing Adaptive Rice codes


version 0.08


A role written for Data::BitStream that provides get and set methods for Adaptive Rice codes. The role applies to a stream object.

The default method used is to store the values using Gamma-Rice codes (also called Exponential-Golomb codes). The upper k bits are stored in Elias Gamma form, and the lower k bits are stored in binary. When k=0 this becomes Gamma coding.

As each value is read or written, k is adjusted. If the upper value is zero and k > 0, k is reduced. If the upper value is greater than six and l < 60, k is increased. This simple method does a fairly good job of keeping k in a useful range as incoming values vary.


Provided Object Methods

put_arice($k, $value)
put_arice($k, @values)

Insert one or more values as Rice codes with parameter k. The value of k will change as values are inserted. Returns 1.

The parameter $k will be modified. Do not attempt to use a read-only value.

put_arice(sub { ... }, $m, @values)

Insert one or more values as Rice codes using the user provided subroutine instead of the Gamma code for the base. Traditional Rice codes:

  sub { shift->put_unary(@_); }

Note that since the adaptive codes would be used when the input data is changing, care should be taken with the code used for the upper bits. A universal code is almost always recommended, which Unary is not. Something like Gamma, Delta, Omega, Fibonacci, etc. will typically be a good choice.

get_arice($k, $count)

Decode one or more Rice codes from the stream with adaptive k. If count is omitted, one value will be read. If count is negative, values will be read until the end of the stream is reached. In scalar context it returns the last code read; in array context it returns an array of all codes read.

The parameter $k will be modified. Do not attempt to use a read-only value.

get_arice(sub { ... }, $k)

Similar to the regular get method except using the user provided subroutine instead of Gamma encoding the base.


The parameter k must be an integer greater than or equal to 0. It will be modified by the routine, so do not use a read-only parameter.

The quotient of value >> k is encoded using an Elias Gamma code (or via the user supplied subroutine), followed by the lower k bits.

The value of k is modified as values are read or written to keep the number of upper bits reasonably low as the data changes.

Required Methods


These methods are required for the role.




Dana Jacobsen <>


Copyright 2011-2012 by Dana Jacobsen <>

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.