blib/lib/Data/Bitfield.pm

filter: Statementstmt 91.2% 136 / 149 Branchbran 78.5% 44 / 56 Conditioncond 68.7% 11 / 16 MC/DCmcdc 55.5% 5 / 9 Subroutinesub 79.3% 23 / 29 Podpod 85.7% 6 / 7 totaltotal 84.5% 225 / 266 CC 39 SCAR 22.2
CC
39
Cov
86%
bitfield_into_caller
22.0
__ANON__
10.0
__ANON__
4.0
CRAP 9.2
↑ Summary
1 # You may distribute under the terms of either the GNU General Public License
2 # or the Artistic License (the same terms as Perl itself)
3 #
4 # (C) Paul Evans, 2014-2019 -- leonerd@leonerd.org.uk
5  
6 package Data::Bitfield;
7  
8 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 5 our $VERSION = '0.04';
12  
13 5 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
14 5 our @EXPORT_OK = qw( bitfield boolfield intfield signed_intfield enumfield constfield );
15  
16 5 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 =head1 NAME
19  
20 C<Data::Bitfield> - manage data packed into bytes of multiple bit fields
21  
22 =head1 SYNOPSIS
23  
24 use Data::Bitfield qw( bitfield boolfield enumfield );
25  
26 # The stat(2) st_mode field on Linux
27 bitfield MODE =>
28 format => enumfield(12,
29 undef, "fifo", "char", undef, "dir", undef, "block", undef,
30 "regular", undef, "link", undef, "socket", undef, undef, undef ),
31 set_uid => boolfield(11),
32 set_gid => boolfield(10),
33 sticky => boolfield(9),
34 user_read => boolfield(8),
35 user_write => boolfield(7),
36 user_exec => boolfield(6),
37 group_read => boolfield(5),
38 group_write => boolfield(4),
39 group_exec => boolfield(3),
40 other_read => boolfield(2),
41 other_write => boolfield(1),
42 other_exec => boolfield(0);
43  
44 my %modebits = unpack_MODE( stat($path)->mode );
45  
46 Z<>
47  
48 # The flag register of a Z80
49 bitfield FLAGS =>
50 sign => boolfield(7),
51 zero => boolfield(6),
52 halfcarry => boolfield(4),
53 parity => boolfield(2),
54 subtract => boolfield(1),
55 carry => boolfield(0);
56  
57 =head1 DESCRIPTION
58  
59 This module provides a single primary function, C<bitfield>, which creates
60 helper functions in the package that calls it, to assist in managing data that
61 is encoded in sets of bits, called bitfields. This may be useful when
62 interacting with a low-level networking protocol, binary file format, hardware
63 devices, or similar purposes.
64  
65 =head2 bitfield
66  
67 bitfield $name, %fields
68  
69 Creates two new functions in the calling package whose names are derived from
70 the string C<$name> passed here. These functions will be symmetric opposites,
71 which convert between a key/value list of field values, and their packed
72 binary byte-string or integer representation.
73  
74 $packed_value = pack_$name( %field_values )
75  
76 %field_values = unpack_$name( $packed_value )
77  
78 These two functions will work to a set of field names that match those field
79 definitions given to the C<bitfield> function that declared them.
80  
81 Each field has a name and a definition. Its definition comes from one of the
82 following field-declaration functions.
83  
84 Additional options may be passed by giving a C<HASH> reference as the first
85 argument, before the structure name.
86  
87 bitfield { %options }, $name, %fields
88  
89 Recognised options are:
90  
91 =over 4
92  
93 =item format => "bytes-LE" | "bytes-BE" | "integer"
94  
95 Defines the format that the C<pack_NAME> function will return and the
96 C<unpack_NAME> function will expect to receive as input. The two C<bytes-*>
97 formats describe a packed binary string in either little- or big-endian
98 direction, and C<integer> describes an integer numerical value.
99  
100 Note that currently the C<integer> format is limited to values 32bits wide or
101 smaller.
102  
103 Optional; will default to C<integer> if not supplied. This default may change
104 in a later version - make sure to always specify it for now.
105  
106 =item unrecognised_ok => BOOL
107  
108 If true, the C<pack_> function will not complain about unrecognised field
109 names; they will simply be ignored.
110  
111 =back
112  
113 =cut
114  
115 sub bitfield
116 18 ▶{
Subroutine bitfield: called CC=1 SCAR=0.0
Pod documented
117 18 my $pkg = caller;
118 18 bitfield_into_caller( $pkg, @_ );
119 }
120  
121 5 my %VALID_FORMATS = map { $_ => 1 } qw( bytes-LE bytes-BE integer );
122  
123 sub bitfield_into_caller
124 18 ▶{
Subroutine bitfield_into_caller: called CC=20 SCAR=30.9
Pod undocumented
125 18 my $pkg = shift;
126 18 ▶ my %options = ( ref $_[0] eq "HASH" ) ? %{ +shift } : ();
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 13 5 18
127 18 my ( $name, @args ) = @_;
128  
129 18 my $unrecognised_ok = !!$options{unrecognised_ok};
130 18 ▶ my $format = $options{format} // "integer";
Condition100%2/2
$options{"format"} // "integer"
l!l
126
MC/DC100%1/1
$options{"format"} // "integer"
$options{"format"}
Truth table100%2/2
A
A= $options{"format"}
Aresult
11
00
131 18 ▶ $VALID_FORMATS{$format} or
Branch: 1 branch
BranchTrueFalseTotal
$VALID_FORMATS{$format} or croak("Invalid 'format' value $format") 18 0 18
132 croak "Invalid 'format' value $format";
133  
134 18 my $used_bits = '';
135  
136 18 my $constmask = '';
137 18 my $constval = '';
138  
139 18 my %fields;
140  
141 18 ▶ while( @args ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args) 39 16 55
142 39 my $name = shift @args;
143 39 ▶ if( !defined $name ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $name) 1 38 39
144 1 my ( $shift, $width, $value ) = @{ shift @args };
145 1 my $mask = pack "L<", ( ( 1 << $width ) - 1 ) << $shift;
146  
147 1 ▶ croak "Constfield collides with other defined bits"
Branch: 1 branch
BranchTrueFalseTotal
unless ($used_bits & $mask) =~ /^\0*$/ 0 1 1
148 if ( $used_bits & $mask ) !~ m/^\0*$/;
149  
150 1 $constval |= pack( "L<", $value << $shift );
151 1 $used_bits |= $mask;
152  
153 1 next;
154 }
155  
156 38 my ( $shift, $width, $encoder, $decoder ) = @{ shift @args };
157 38 my $offs = int( $shift / 8 ); $shift %= 8;
158  
159 38 my $mask = ( "\x00" x $offs ) . pack "L<", ( ( 1 << $width ) - 1 ) << $shift;
160  
161 croak "Field $name is defined twice"
162 38 ▶ if $fields{$name};
Branch: 1 branch
BranchTrueFalseTotal
if $fields{$name} 1 37 38
163 37 ▶ croak "Field $name collides with other defined fields"
Branch: 1 branch
BranchTrueFalseTotal
unless ($used_bits & $mask) =~ /^\0*$/ 1 36 37
164 if ( $used_bits & $mask ) !~ m/^\0*$/;
165  
166 36 ▶ if( $format eq "bytes-BE" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($format eq "bytes-BE") 3 33 36
167 3 ▶ $shift += 8 if $width <= 8;
Branch: 1 branch
BranchTrueFalseTotal
if $width <= 8 2 1 3
168 3 ▶ $shift += 8 if $width <= 16;
Branch: 1 branch
BranchTrueFalseTotal
if $width <= 16 3 0 3
169 3 ▶ $shift += 8 if $width <= 24;
Branch: 1 branch
BranchTrueFalseTotal
if $width <= 24 3 0 3
170 }
171  
172 36 $fields{$name} = [ $mask, $offs, $shift, $encoder, $decoder ];
173 36 $used_bits |= $mask;
174 }
175  
176 16 $used_bits =~ s/\0+$//;
177 16 my $datalen = length $used_bits;
178  
179 16 ▶ my $fmt = $format eq "bytes-BE" ? "L>" : "L<";
Branch: 1 branch
BranchTrueFalseTotal
$format eq 'bytes-BE' ? : 2 14 16
180  
181 19 ▶ my $packsub = sub {
Subroutine __ANON__: called CC=10 SCAR=23.0
182 19 my %args = @_;
183 19 my $ret = $constval;
184 19 foreach ( keys %args ) {
185 31 ▶ defined( my $f = $fields{$_} ) or
Branch: 1 branch
BranchTrueFalseTotal
defined(my $f = $fields{$_}) or $unrecognised_ok and next or croak("Unexpected field '${_}'") 29 1 30
Condition80%4/5
defined(my $f = $fields{$_}) or $unrecognised_ok and next
l!l&&r!l&&!r
2902
$unrecognised_ok and next
!ll
11
MC/DC100%2/2
defined(my $f = $fields{$_}) or $unrecognised_ok and next
defined(my $f = $fields{$_}) $unrecognised_ok
Truth table100%3/3
A or B
A= defined(my $f = $fields{$_})B= $unrecognised_ok
ABresult
1X1
011
000
186 $unrecognised_ok and next or
187 croak "Unexpected field '$_'";
188  
189 29 my ( $mask, $offs, $shift, $encoder ) = @$f;
190  
191 29 my $v = $args{$_};
192 29 ▶ $v = $encoder->($v) if $encoder;
Branch: 1 branch
BranchTrueFalseTotal
if $encoder 17 12 29
193 29 ▶ defined $v or croak "Unsupported value for '$_'";
Branch: 1 branch
BranchTrueFalseTotal
defined $v or croak("Unsupported value for '${_}'") 28 1 29
194  
195 {
196 5 ▶ no warnings 'numeric';
Subroutine BEGIN: called CC=1 SCAR=0.0
197 28 ▶ int $v eq $v or
Branch: 1 branch
BranchTrueFalseTotal
int $v eq $v or croak("Expected an integer value for '${_}'") 27 1 28
198 croak "Expected an integer value for '$_'";
199 }
200  
201 27 my $bits = ( "\x00" x $offs ) . ( pack $fmt, $v << $shift );
202 27 ▶ $v >= 0 and ( $bits & ~$mask ) =~ m/^\0+$/ or
Branch: 1 branch
BranchTrueFalseTotal
$v >= 0 and ($bits & ~$mask) =~ /^\0+$/ or croak("Value out of range for '${_}'") 26 1 27
Condition66%2/3
$v >= 0 and ($bits & ~$mask) =~ /^\0+$/
!ll&&!rl&&r
0126
MC/DC50%1/2
$v >= 0 and ($bits & ~$mask) =~ /^\0+$/
$v >= 0 ($bits & ~$mask) =~ /^\0+$/
Truth table66%2/3
A and B
A= $v >= 0B= ($bits & ~$mask) =~ /^\0+$/
ABresult
0X0
100
111
203 croak "Value out of range for '$_'";
204  
205 26 $ret |= $mask & $bits;
206 }
207 15 return substr( $ret, 0, $datalen );
208 16 };
209  
210 12 ▶ my $unpacksub = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
211 12 my ( $val ) = @_;
212 # Bitwise extend so there's always enough bits to unpack
213 12 $val .= "\0\0\0";
214 # TODO: check constmask
215 12 my @ret;
216 12 foreach ( keys %fields ) {
217 26 my $f = $fields{$_};
218 26 my ( $mask, $offs, $shift, undef, $decoder ) = @$f;
219  
220 26 my $v = unpack( $fmt, substr( $val & $mask, $offs, 4 ) ) >> $shift;
221  
222 26 ▶ $v = $decoder->($v) if $decoder;
Branch: 1 branch
BranchTrueFalseTotal
if $decoder 14 12 26
223 26 push @ret, $_ => $v;
224 }
225 12 return @ret;
226 16 };
227  
228 16 ▶ if( $format eq "integer" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($format eq "integer") 4 12 16
229 4 my $orig_packsub = $packsub;
230 4 my $orig_unpacksub = $unpacksub;
231  
232 4 my $nbits = $datalen * 8;
233  
234 4 ▶ if( $nbits <= 8 ) {
Branch: 4 branches
BranchTrueFalseTotal
if ($nbits <= 8) { } 4 0 4
elsif ($nbits <= 16) { } 0 0 0
elsif ($nbits <= 24) { } 0 0 0
elsif ($nbits <= 32) { } 0 0 0
235 4 ▶ $packsub = sub { unpack "C", $orig_packsub->( @_ ) };
Subroutine __ANON__: called CC=1 SCAR=0.0
236 4 ▶ $unpacksub = sub { $orig_unpacksub->( pack "C", $_[0] ) };
Subroutine __ANON__: called CC=1 SCAR=0.0
237 }
238 elsif( $nbits <= 16 ) {
239 0 ▶ $packsub = sub { unpack "S<", $orig_packsub->( @_ ) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
240 0 ▶ $unpacksub = sub { $orig_unpacksub->( pack "S<", $_[0] ) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
241 }
242 elsif( $nbits <= 24 ) {
243 0 ▶ $packsub = sub { unpack( "L<", $orig_packsub->( @_ ) . "\0" ) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
244 0 ▶ $unpacksub = sub { $orig_unpacksub->( pack "L<", $_[0] ) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
245 }
246 elsif( $nbits <= 32 ) {
247 0 ▶ $packsub = sub { unpack "L<", $orig_packsub->( @_ ) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
248 0 ▶ $unpacksub = sub { $orig_unpacksub->( pack "L<", $_[0] ) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
249 }
250 else {
251 0 croak "Cannot currently handle integer packing of $nbits wide values";
252 }
253 }
254  
255 16 my %subs;
256  
257 16 $subs{"pack_$name"} = $packsub;
258 16 $subs{"unpack_$name"} = $unpacksub;
259  
260 5 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
261 16 *{"${pkg}::$_"} = $subs{$_} for keys %subs;
262 }
263  
264 =head1 FIELD TYPES
265  
266 =cut
267  
268 =head2 boolfield
269  
270 boolfield( $bitnum )
271  
272 Declares a single bit-wide field at the given bit index, whose value is a
273 simple boolean truth.
274  
275 =cut
276  
277 sub boolfield
278 19 ▶{
Subroutine boolfield: called CC=1 SCAR=0.0
Pod documented
279 19 my ( $bitnum ) = @_;
280 19 ▶ return [ $bitnum, 1, sub { 0 + !!shift }, sub { !!shift } ];
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
281 }
282  
283 =head2 intfield
284  
285 intfield( $bitnum, $width )
286  
287 Declares a field of C<$width> bits wide, starting at the given bit index,
288 whose value is an unsigned integer. It will be shifted appropriately.
289  
290 =cut
291  
292 sub intfield
293 20 ▶{
Subroutine intfield: called CC=1 SCAR=0.0
Pod documented
294 20 my ( $bitnum, $width ) = @_;
295 20 return [ $bitnum, $width ];
296 }
297  
298 =head2 signed_intfield
299  
300 signed_intfield( $bitnum, $width )
301  
302 I<Since version 0.04.>
303  
304 Declares a field of C<$width> bits wide, starting at the given bit index,
305 whose value is a signed integer. It will be shifted appropriately.
306  
307 =cut
308  
309 sub signed_intfield
310 2 ▶{
Subroutine signed_intfield: called CC=1 SCAR=0.0
Pod documented
311 2 my ( $bitnum, $width ) = @_;
312  
313 2 my $def = intfield( $bitnum, $width );
314  
315 2 my $excess = 2 ** $width;
316 2 my $sign = ( 1 << ($width-1) );
317  
318 2 ▶ $def->[2] = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
319 2 my $v = shift;
320 2 ▶ $v += $excess if $v < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $v < 0 1 1 2
321 2 return $v;
322 2 };
323 2 ▶ $def->[3] = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
324 2 my $v = shift;
325 2 ▶ $v -= $excess if $v & $sign;
Branch: 1 branch
BranchTrueFalseTotal
if $v & $sign 1 1 2
326 2 return $v;
327 2 };
328  
329 2 return $def;
330 }
331  
332 =head2 enumfield
333  
334 enumfield( $bitnum, @values )
335  
336 Declares a field some number of bits wide, sufficient to store an integer big
337 enough to act as an index into the list of values, starting at the given bit
338 index. Its value will be automatically converted to or from one of the values
339 given, which should act sensibly as strings for comparison purposes. Holes can
340 be placed in the range of supported values by using C<undef>.
341  
342 =cut
343  
344 sub enumfield
345 6 ▶{
Subroutine enumfield: called CC=2 SCAR=6.9
Pod documented
346 6 my ( $bitnum, @values ) = @_;
347 6 my $nvalues = scalar @values;
348  
349 # Need to ceil(log2) it
350 6 my $width = 1;
351 6 ▶ $width++ while ( 1 << $width ) < $nvalues;
Branch: 1 branch
BranchTrueFalseTotal
1 << $width < $nvalues and do { ++$width } 2 6 8
352  
353 6 my $def = intfield( $bitnum, $width );
354 3 ▶ $def->[2] = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
355 3 my $v = shift;
356 defined $values[$_] and $v eq $values[$_] and return $_
357 3 ▶ for 0 .. $#values;
Branch: 1 branch
BranchTrueFalseTotal
defined $values[$_] and $v eq $values[$_] and return $_ 2 5 7
Condition66%2/3
defined $values[$_] and $v eq $values[$_]
!ll&&!rl&&r
052
MC/DC50%1/2
defined $values[$_] and $v eq $values[$_]
defined $values[$_] $v eq $values[$_]
Truth table66%2/3
A and B
A= defined $values[$_]B= $v eq $values[$_]
ABresult
0X0
100
111
358 1 return undef;
359 6 };
360 2 ▶ $def->[3] = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
361 2 return $values[shift];
362 6 };
363  
364 6 return $def;
365 }
366  
367 =head2 constfield
368  
369 constfield( $bitnum, $width, $value )
370  
371 Declares a field some number of bits wide that stores a constant value. This
372 value will be packed automatically.
373  
374 Unlike other field definitions, this field is not named. It returns a
375 2-element list directly for use in the C<bitfield> list.
376  
377 =cut
378  
379 sub constfield
380 1 ▶{
Subroutine constfield: called CC=3 SCAR=12.5
Pod documented
381 1 my ( $bitnum, $width, $value ) = @_;
382  
383 1 ▶ $value >= 0 and $value < ( 1 << $width ) or
Branch: 1 branch
BranchTrueFalseTotal
$value >= 0 and $value < 1 << $width or croak("Invalid value for constfield of width $width") 1 0 1
Condition33%1/3
$value >= 0 and $value < 1 << $width
!ll&&!rl&&r
001
MC/DC0%0/2
$value >= 0 and $value < 1 << $width
$value >= 0 $value < 1 << $width
Truth table33%1/3
A and B
A= $value >= 0B= $value < 1 << $width
ABresult
0X0
100
111
384 croak "Invalid value for constfield of width $width";
385  
386 1 return undef, [ $bitnum, $width, $value ];
387 }
388  
389 =head1 TODO
390  
391 =over 4
392  
393 =item *
394  
395 More flexible error-handling - missing/extra values to C<pack_>, extra bits to C<unpack_>.
396  
397 =item *
398  
399 Allow truely-custom field handling, including code to support discontiguous fields.
400  
401 =back
402  
403 =cut
404  
405 =head1 AUTHOR
406  
407 Paul Evans <leonerd@leonerd.org.uk>
408  
409 =cut
410  
411 5 0x55AA;
↑ Summary