Bit::Vector::Minimal - Object-oriented wrapper around vec()


Bit-Vector-Minimal documentation Contained in the Bit-Vector-Minimal distribution.

Index


Code Index:

NAME

Top

Bit::Vector::Minimal - Object-oriented wrapper around vec()

SYNOPSIS

Top

  use Bit::Vector::Minimal;
  my $vec = Bit::Vector->new(size => 8, width => 1, endianness => "little");
  # These are the defaults

  $vec->set(1); # $vec's internal vector now looks like "00000010"
  $vec->get(3); # 0

DESCRIPTION

Top

This is a much simplified, lightweight version of Bit::Vector, and wraps Perl's (sometimes confusing) vec function in an object-oriented abstraction.

METHODS

Top

new

Creates a new bit vector. By default, this creates a one-byte vector with 8 one-bit "slots", with bit zero on the right of the bit pattern. These settings can be changed by passing parameters to the constructor: size will alter the size in bits of the vector; width will alter the width of the slots. The module will die if width is not an integer divisor of size. endianness controls whether the zeroth place is on the right or the left of the bit vector.

set(POS[, VALUE])

Sets the bit or slot at position POS to value VALUE or "all bits on" if VALUE is not given.

get(POS)

Returns the bit or slot at position POS.

display

Display the vector. For debugging purposes.

AUTHOR

Top

Current maintainer: Tony Bowden

Original author: Simon Cozens

BUGS and QUERIES

Top

Please direct all correspondence regarding this module to: bug-Bit-Vector-Minimal@rt.cpan.org

SEE ALSO

Top

Bit::Vector

COPYRIGHT AND LICENSE

Top


Bit-Vector-Minimal documentation Contained in the Bit-Vector-Minimal distribution.
package Bit::Vector::Minimal;

use 5.006;

use strict;
use warnings;

use Carp;

our $VERSION = '1.3';

sub new {
	my $class = shift;
	my $self = bless {
		width      => 1,
		size       => 8,
		endianness => "little",
		@_
	}, $class;
	croak "Don't know what endianness $self->{endianness} is meant to be"
		unless $self->{endianness} =~ /^(little|big)$/i;

	croak "Width ought to be a power of two"
		if !$self->{width}
		or (($self->{width} - 1) & $self->{width});

	my $slots = $self->{size} / $self->{width};
	croak "Cowardly refusing to store $slots items in a vector"
		unless $slots == int($slots);
	my $num_bytes =
		$self->{size} % 8
		? (($self->{size} + (8 - $self->{size} % 8)) / 8)
		: ($self->{size} / 8);
	$self->{pattern} = "\0" x $num_bytes;
	return $self;
}

sub set {
	my ($self, $pos, $value) = @_;
	$value = 2**$self->{width} - 1 unless defined $value;
	$pos = 1 + $self->{width} - $pos if $self->{endianness} eq "big";
	vec($self->{pattern}, $pos, $self->{width}) = $value;
}

sub get {
	my ($self, $pos) = @_;
	$pos = 1 + $self->{width} - $pos if $self->{endianness} eq "big";
	return vec($self->{pattern}, $pos, $self->{width});
}

sub display { 
	my $self = shift;
	return join "", map sprintf("%08b", ord $_), split //, $self->{pattern};
}