in reply to BitStream revisited

As others have suggested, doing this with OO is going to have a cost. One way of avoiding that yet preserving the modularization and ability to have multiple bitstreams would be to generate a closure. Pseudo-code:
sub BitStream::make_bitstream { my $filename = shift; open my $fh, ... or return my $buf=''; return sub { # if a buffer is available, use it my $ret_str = substr($buf, 0, (defined($_[0]) ? $_[0] : 1), ''); # fill buffer if request may not have been satisfied if (!length($buf)) { my $need = (defined($_[0]) ? $_[0] : 1) - length($ret_Str); return $ret_str if !$need; read from $fh and unpack into $buf $ret_str .= substr($buf, 0, $need, ''); } $ret_str; } } #example package main; $get_bits = BitStream::make_bitstring("foo.dat") or die "open failure: + $!"; $onebit = $get_bits->(); $twobits = $get_bits->(2);
It's not clear whether you want failure to read the desired number of bits would be a fatal error or just return what was available.

!defined($_[0])||$_[0] may be faster than the ?: way; if you are that concerned, you may want to benchmark it (or just use C :).

Update: - $ret_str was supposed to be - length($ret_str)

Replies are listed 'Best First'.
Re: Re: BitStream revisited
by spurperl (Priest) on Jan 01, 2004 at 08:04 UTC
    This is a very pretty solution, thanks ! I'm not sure by how much it will improve performance, but a closure fits here well. It's nice that Perl has this ability (borrowed from Lisp, of course) as in some case it may solve a problem graciously, but so can an object. That is said by me, who adores Lisp and FP in general and looks at OO with suspicion, as a nice solution in *some* cases, but surely not the uber-panacea hyped about so much.