1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
|
package Type::Tiny::Bitfield;
use 5.008001;
use strict;
use warnings;
BEGIN {
$Type::Tiny::Bitfield::AUTHORITY = 'cpan:TOBYINK';
$Type::Tiny::Bitfield::VERSION = '2.004000';
}
$Type::Tiny::Bitfield::VERSION =~ tr/_//d;
sub _croak ($;@) { require Error::TypeTiny; goto \&Error::TypeTiny::croak }
use Exporter::Tiny 1.004001 ();
use Type::Tiny ();
use Types::Common::Numeric qw( +PositiveOrZeroInt );
use Eval::TypeTiny qw( eval_closure );
our @ISA = qw( Type::Tiny Exporter::Tiny );
__PACKAGE__->_install_overloads(
q[+] => 'new_combined',
);
sub _is_power_of_two { not $_[0] & $_[0]-1 }
sub _exporter_fail {
my ( $class, $type_name, $args, $globals ) = @_;
my $caller = $globals->{into};
my %values = %$args;
/^[-]/ && delete( $values{$_} ) for keys %values;
my $type = $class->new(
name => $type_name,
values => \%values,
coercion => 1,
);
$INC{'Type/Registry.pm'}
? 'Type::Registry'->for_class( $caller )->add_type( $type, $type_name )
: ( $Type::Registry::DELAYED{$caller}{$type_name} = $type )
unless( ref($caller) or $caller eq '-lexical' or $globals->{'lexical'} );
return map +( $_->{name} => $_->{code} ), @{ $type->exportables };
}
sub new {
my $proto = shift;
my %opts = ( @_ == 1 ) ? %{ $_[0] } : @_;
_croak
"Bitfield type constraints cannot have a parent constraint passed to the constructor"
if exists $opts{parent};
_croak
"Bitfield type constraints cannot have a constraint coderef passed to the constructor"
if exists $opts{constraint};
_croak
"Bitfield type constraints cannot have a inlining coderef passed to the constructor"
if exists $opts{inlined};
_croak "Need to supply hashref of values"
unless exists $opts{values};
$opts{parent} = PositiveOrZeroInt;
for my $key ( keys %{ $opts{values} } ) {
_croak "Not an all-caps name in a bitfield: $key"
unless $key =~ /^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*/
}
my $ALL = 0;
my %already = ();
for my $value ( values %{ $opts{values} } ) {
_croak "Not a positive power of 2 in a bitfield: $value"
unless is_PositiveOrZeroInt( $value ) && _is_power_of_two( $value );
_croak "Duplicate value in a bitfield: $value"
if $already{$value}++;
$ALL |= ( 0 + $value );
}
$opts{ALL} = $ALL;
$opts{constraint} = sub {
not shift() & ~$ALL;
};
if ( defined $opts{coercion}
and !ref $opts{coercion}
and 1 eq $opts{coercion} ) {
delete $opts{coercion};
$opts{_build_coercion} = sub {
require Types::Standard;
my $c = shift;
my $t = $c->type_constraint;
$c->add_type_coercions(
Types::Standard::Str(),
$t->_stringy_coercion,
);
};
} #/ if ( defined $opts{coercion...})
return $proto->SUPER::new( %opts );
} #/ sub new
sub new_combined {
my ( $self, $other, $swap ) = @_;
Scalar::Util::blessed( $self )
&& $self->isa( __PACKAGE__ )
&& Scalar::Util::blessed( $other )
&& $other->isa( __PACKAGE__ )
or _croak( "Bad overloaded operation" );
( $other, $self ) = ( $self, $other ) if $swap;
for my $k ( keys %{ $self->values } ) {
_croak "Conflicting value: $k"
if exists $other->values->{$k};
}
my %all_values = ( %{ $self->values }, %{ $other->values } );
return ref( $self )->new(
display_name => sprintf( '%s+%s', "$self", "$other" ),
values => \%all_values,
( $self->has_coercion || $other->has_coercion )
? ( coercion => 1 )
: (),
);
}
sub values {
$_[0]{values};
}
sub _lockdown {
my ( $self, $callback ) = @_;
$callback->( $self->{values} );
}
sub exportables {
my ( $self, $base_name ) = @_;
if ( not $self->is_anon ) {
$base_name ||= $self->name;
}
my $exportables = $self->SUPER::exportables( $base_name );
require Eval::TypeTiny;
require B;
for my $key ( keys %{ $self->values } ) {
my $value = $self->values->{$key};
push @$exportables, {
name => uc( sprintf '%s_%s', $base_name, $key ),
tags => [ 'constants' ],
code => Eval::TypeTiny::eval_closure(
source => sprintf( 'sub () { %d }', $value ),
environment => {},
),
};
}
my $weak = $self;
require Scalar::Util;
Scalar::Util::weaken( $weak );
push @$exportables, {
name => sprintf( '%s_to_Str', $base_name ),
tags => [ 'from' ],
code => sub { $weak->to_string( @_ ) },
};
return $exportables;
}
sub constant_names {
my $self = shift;
return map { $_->{name} }
grep { my $tags = $_->{tags}; grep $_ eq 'constants', @$tags; }
@{ $self->exportables || [] };
}
sub can_be_inlined {
!!1;
}
sub inline_check {
my ( $self, $var ) = @_;
return sprintf(
'( %s and not %s & ~%d )',
PositiveOrZeroInt->inline_check( $var ),
$var,
$self->{ALL},
);
}
sub _stringy_coercion {
my ( $self, $varname ) = @_;
$varname ||= '$_';
my %vals = %{ $self->values };
my $pfx = uc( "$self" );
my $pfxl = length $pfx;
my $hash = sprintf(
'( %s )',
join(
q{, },
map sprintf( '%s => %d', B::perlstring($_), $vals{$_} ),
sort keys %vals,
),
);
return qq{do { my \$bits = 0; my \%lookup = $hash; for my \$tok ( grep /\\w/, split /[\\s|+]+/, uc( $varname ) ) { if ( substr( \$tok, 0, $pfxl) eq "$pfx" ) { \$tok = substr( \$tok, $pfxl ); \$tok =~ s/^_//; } if ( exists \$lookup{\$tok} ) { \$bits |= \$lookup{\$tok}; next; } require Carp; Carp::carp("Unknown token: \$tok"); } \$bits; }};
}
sub from_string {
my ( $self, $str ) = @_;
$self->{from_string} ||= eval_closure(
environment => {},
source => sprintf( 'sub { my $STR = shift; %s }', $self->_stringy_coercion( '$STR' ) ),
);
$self->{from_string}->( $str );
}
sub to_string {
my ( $self, $int ) = @_;
$self->check( $int ) or return undef;
my %values = %{ $self->values };
$self->{all_names} ||= [ sort { $values{$a} <=> $values{$b} } keys %values ];
$int += 0;
my @names;
for my $n ( @{ $self->{all_names} } ) {
push @names, $n if $int & $values{$n};
}
return join q{|}, @names;
}
sub AUTOLOAD {
our $AUTOLOAD;
my $self = shift;
my ( $m ) = ( $AUTOLOAD =~ /::(\w+)$/ );
return if $m eq 'DESTROY';
if ( ref $self and exists $self->{values}{$m} ) {
return 0 + $self->{values}{$m};
}
local $Type::Tiny::AUTOLOAD = $AUTOLOAD;
return $self->SUPER::AUTOLOAD( @_ );
}
sub can {
my ( $self, $m ) = ( shift, @_ );
if ( ref $self and exists $self->{values}{$m} ) {
return sub () { 0 + $self->{values}{$m} };
}
return $self->SUPER::can( @_ );
}
1;
__END__
=pod
=encoding utf-8
=head1 NAME
Type::Tiny::Bitfield - bitfield/bitflag type constraints
=head1 SYNOPSIS
Using Type::Tiny::Bitfield's export feature:
package LightSource {
use Moo;
use Type::Tiny::Bitfield LedSet => {
RED => 1,
GREEN => 2,
BLUE => 4,
};
has leds => ( is => 'ro', isa => LedSet, default => 0, coerce => 1 );
sub new_red {
my $class = shift;
return $class->new( leds => LEDSET_RED );
}
sub new_green {
my $class = shift;
return $class->new( leds => LEDSET_GREEN );
}
sub new_yellow {
my $class = shift;
return $class->new( leds => LEDSET_RED | LEDSET_GREEN );
}
}
Using Type::Tiny::Bitfield's object-oriented interface:
package LightSource {
use Moo;
use Type::Tiny::Bitfield;
my $LedSet = Type::Tiny::Bitfield->new(
name => 'LedSet',
values => {
RED => 1,
GREEN => 2,
BLUE => 4,
},
coercion => 1,
);
has leds => ( is => 'ro', isa => $LedSet, default => 0, coerce => 1 );
sub new_red {
my $class = shift;
return $class->new( leds => $LedSet->RED );
}
sub new_green {
my $class = shift;
return $class->new( leds => $LedSet->GREEN );
}
sub new_yellow {
my $class = shift;
return $class->new( leds => $LedSet->coerce('red|green') );
}
}
=head1 STATUS
This module is covered by the
L<Type-Tiny stability policy|Type::Tiny::Manual::Policies/"STABILITY">.
=head1 DESCRIPTION
Bitfield type constraints.
This package inherits from L<Type::Tiny>; see that for most documentation.
Major differences are listed below:
=head2 Attributes
=over
=item C<values>
Hashref of bits allowed in the bitfield. Keys must be UPPER_SNAKE_CASE strings.
Values must be positive integers which are powers of two. The same number
cannot be used multiple times.
=item C<constraint>
Unlike Type::Tiny, you I<cannot> pass a constraint coderef to the constructor.
Instead rely on the default.
=item C<inlined>
Unlike Type::Tiny, you I<cannot> pass an inlining coderef to the constructor.
Instead rely on the default.
=item C<parent>
Parent is always B<Types::Common::Numeric::PositiveOrZeroInt>, and cannot be
passed to the constructor.
=item C<coercion>
If C<< coercion => 1 >> is passed to the constructor, the type will have an
automatic coercion from B<Str>. Types built by the C<import> method will
always have C<< coercion => 1 >>.
In the SYNOPSIS example, the coercion from B<Str> will accept strings like:
"RED"
"red"
"Red Green"
"Red+Blue"
"blue | GREEN"
"LEDSET_RED + LeDsEt_green"
=back
=head2 Methods
This class uses C<AUTOLOAD> to allow the names of each bit in the bitfield
to be used as methods. These method names will always be UPPER_SNAKE_CASE.
For example, in the synopsis, C<< LedSet->GREEN >> would return 2.
Other methods it provides:
=over
=item C<< from_string( $str ) >>
Provides the standard coercion from a string, even if this type constraint
doesn't have a coercion.
=item C<< to_string( $int ) >>
Does the reverse coercion.
=item C<< constant_names() >>
This is a convenience to allow for:
use base 'Exporter::Tiny';
push our @EXPORT_OK, LineStyle->constant_names;
=back
=head2 Exports
Type::Tiny::Bitfield can be used as an exporter.
use Type::Tiny::Bitfield LedSet => {
RED => 1,
GREEN => 2,
BLUE => 4,
};
This will export the following functions into your namespace:
=over
=item C<< LedSet >>
=item C<< is_LedSet( $value ) >>
=item C<< assert_LedSet( $value ) >>
=item C<< to_LedSet( $string ) >>
=item C<< LedSet_to_Str( $value ) >>
=item C<< LEDSET_RED >>
=item C<< LEDSET_GREEN >>
=item C<< LEDSET_BLUE >>
=back
Multiple bitfield types can be exported at once:
use Type::Tiny::Enum (
LedSet => { RED => 1, GREEN => 2, BLUE => 4 },
LedPattern => { FLASHING => 1 },
);
=head2 Overloading
It is possible to combine two Bitfield types using the C<< + >> operator.
use Type::Tiny::Enum (
LedSet => { RED => 1, GREEN => 2, BLUE => 4 },
LedPattern => { FLASHING => 8 },
);
has leds => (
is => 'ro',
isa => LedSet + LedPattern,
default => 0,
coerce => 1
);
This will allow values like "11" (LEDSET_RED|LEDSET_GREEN|LEDPATTERN_FLASHING).
An exception will be thrown if any of the names in the two types being combined
conflict.
=head1 BUGS
Please report any bugs to
L<https://github.com/tobyink/p5-type-tiny/issues>.
=head1 SEE ALSO
L<Type::Tiny::Manual>.
L<Type::Tiny>.
=head1 AUTHOR
Toby Inkster E<lt>tobyink@cpan.orgE<gt>.
=head1 COPYRIGHT AND LICENCE
This software is copyright (c) 2023 by Toby Inkster.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=head1 DISCLAIMER OF WARRANTIES
THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
|