Initial Commit

This commit is contained in:
Riley Schneider
2025-12-03 16:38:10 +01:00
parent c5e26bf594
commit b732d8d4b5
17680 changed files with 5977495 additions and 2 deletions

View File

@@ -0,0 +1,742 @@
package Class::Accessor;
require 5.00502;
use strict;
$Class::Accessor::VERSION = '0.51';
sub new {
return bless
defined $_[1]
? {%{$_[1]}} # make a copy of $fields.
: {},
ref $_[0] || $_[0];
}
sub mk_accessors {
my($self, @fields) = @_;
$self->_mk_accessors('rw', @fields);
}
if (eval { require Sub::Name }) {
Sub::Name->import;
}
{
no strict 'refs';
sub import {
my ($class, @what) = @_;
my $caller = caller;
for (@what) {
if (/^(?:antlers|moose-?like)$/i) {
*{"${caller}::has"} = sub {
my ($f, %args) = @_;
$caller->_mk_accessors(($args{is}||"rw"), $f);
};
*{"${caller}::extends"} = sub {
@{"${caller}::ISA"} = @_;
unless (grep $_->can("_mk_accessors"), @_) {
push @{"${caller}::ISA"}, $class;
}
};
# we'll use their @ISA as a default, in case it happens to be
# set already
&{"${caller}::extends"}(@{"${caller}::ISA"});
}
}
}
sub follow_best_practice {
my($self) = @_;
my $class = ref $self || $self;
*{"${class}::accessor_name_for"} = \&best_practice_accessor_name_for;
*{"${class}::mutator_name_for"} = \&best_practice_mutator_name_for;
}
sub _mk_accessors {
my($self, $access, @fields) = @_;
my $class = ref $self || $self;
my $ra = $access eq 'rw' || $access eq 'ro';
my $wa = $access eq 'rw' || $access eq 'wo';
foreach my $field (@fields) {
my $accessor_name = $self->accessor_name_for($field);
my $mutator_name = $self->mutator_name_for($field);
if( $accessor_name eq 'DESTROY' or $mutator_name eq 'DESTROY' ) {
$self->_carp("Having a data accessor named DESTROY in '$class' is unwise.");
}
if ($accessor_name eq $mutator_name) {
my $accessor;
if ($ra && $wa) {
$accessor = $self->make_accessor($field);
} elsif ($ra) {
$accessor = $self->make_ro_accessor($field);
} else {
$accessor = $self->make_wo_accessor($field);
}
my $fullname = "${class}::$accessor_name";
my $subnamed = 0;
unless (defined &{$fullname}) {
subname($fullname, $accessor) if defined &subname;
$subnamed = 1;
*{$fullname} = $accessor;
}
if ($accessor_name eq $field) {
# the old behaviour
my $alias = "${class}::_${field}_accessor";
subname($alias, $accessor) if defined &subname and not $subnamed;
*{$alias} = $accessor unless defined &{$alias};
}
} else {
my $fullaccname = "${class}::$accessor_name";
my $fullmutname = "${class}::$mutator_name";
if ($ra and not defined &{$fullaccname}) {
my $accessor = $self->make_ro_accessor($field);
subname($fullaccname, $accessor) if defined &subname;
*{$fullaccname} = $accessor;
}
if ($wa and not defined &{$fullmutname}) {
my $mutator = $self->make_wo_accessor($field);
subname($fullmutname, $mutator) if defined &subname;
*{$fullmutname} = $mutator;
}
}
}
}
}
sub mk_ro_accessors {
my($self, @fields) = @_;
$self->_mk_accessors('ro', @fields);
}
sub mk_wo_accessors {
my($self, @fields) = @_;
$self->_mk_accessors('wo', @fields);
}
sub best_practice_accessor_name_for {
my ($class, $field) = @_;
return "get_$field";
}
sub best_practice_mutator_name_for {
my ($class, $field) = @_;
return "set_$field";
}
sub accessor_name_for {
my ($class, $field) = @_;
return $field;
}
sub mutator_name_for {
my ($class, $field) = @_;
return $field;
}
sub set {
my($self, $key) = splice(@_, 0, 2);
if(@_ == 1) {
$self->{$key} = $_[0];
}
elsif(@_ > 1) {
$self->{$key} = [@_];
}
else {
$self->_croak("Wrong number of arguments received");
}
}
sub get {
my $self = shift;
if(@_ == 1) {
return $self->{$_[0]};
}
elsif( @_ > 1 ) {
return @{$self}{@_};
}
else {
$self->_croak("Wrong number of arguments received");
}
}
sub make_accessor {
my ($class, $field) = @_;
return sub {
my $self = shift;
if(@_) {
return $self->set($field, @_);
} else {
return $self->get($field);
}
};
}
sub make_ro_accessor {
my($class, $field) = @_;
return sub {
my $self = shift;
if (@_) {
my $caller = caller;
$self->_croak("'$caller' cannot alter the value of '$field' on objects of class '$class'");
}
else {
return $self->get($field);
}
};
}
sub make_wo_accessor {
my($class, $field) = @_;
return sub {
my $self = shift;
unless (@_) {
my $caller = caller;
$self->_croak("'$caller' cannot access the value of '$field' on objects of class '$class'");
}
else {
return $self->set($field, @_);
}
};
}
use Carp ();
sub _carp {
my ($self, $msg) = @_;
Carp::carp($msg || $self);
return;
}
sub _croak {
my ($self, $msg) = @_;
Carp::croak($msg || $self);
return;
}
1;
__END__
=head1 NAME
Class::Accessor - Automated accessor generation
=head1 SYNOPSIS
package Foo;
use base qw(Class::Accessor);
Foo->follow_best_practice;
Foo->mk_accessors(qw(name role salary));
# or if you prefer a Moose-like interface...
package Foo;
use Class::Accessor "antlers";
has name => ( is => "rw", isa => "Str" );
has role => ( is => "rw", isa => "Str" );
has salary => ( is => "rw", isa => "Num" );
# Meanwhile, in a nearby piece of code!
# Class::Accessor provides new().
my $mp = Foo->new({ name => "Marty", role => "JAPH" });
my $job = $mp->role; # gets $mp->{role}
$mp->salary(400000); # sets $mp->{salary} = 400000 # I wish
# like my @info = @{$mp}{qw(name role)}
my @info = $mp->get(qw(name role));
# $mp->{salary} = 400000
$mp->set('salary', 400000);
=head1 DESCRIPTION
This module automagically generates accessors/mutators for your class.
Most of the time, writing accessors is an exercise in cutting and
pasting. You usually wind up with a series of methods like this:
sub name {
my $self = shift;
if(@_) {
$self->{name} = $_[0];
}
return $self->{name};
}
sub salary {
my $self = shift;
if(@_) {
$self->{salary} = $_[0];
}
return $self->{salary};
}
# etc...
One for each piece of data in your object. While some will be unique,
doing value checks and special storage tricks, most will simply be
exercises in repetition. Not only is it Bad Style to have a bunch of
repetitious code, but it's also simply not lazy, which is the real
tragedy.
If you make your module a subclass of Class::Accessor and declare your
accessor fields with mk_accessors() then you'll find yourself with a
set of automatically generated accessors which can even be
customized!
The basic set up is very simple:
package Foo;
use base qw(Class::Accessor);
Foo->mk_accessors( qw(far bar car) );
Done. Foo now has simple far(), bar() and car() accessors
defined.
Alternatively, if you want to follow Damian's I<best practice> guidelines
you can use:
package Foo;
use base qw(Class::Accessor);
Foo->follow_best_practice;
Foo->mk_accessors( qw(far bar car) );
B<Note:> you must call C<follow_best_practice> before calling C<mk_accessors>.
=head2 Moose-like
By popular demand we now have a simple Moose-like interface. You can now do:
package Foo;
use Class::Accessor "antlers";
has far => ( is => "rw" );
has bar => ( is => "rw" );
has car => ( is => "rw" );
Currently only the C<is> attribute is supported.
=head1 CONSTRUCTOR
Class::Accessor provides a basic constructor, C<new>. It generates a
hash-based object and can be called as either a class method or an
object method.
=head2 new
my $obj = Foo->new;
my $obj = $other_obj->new;
my $obj = Foo->new(\%fields);
my $obj = $other_obj->new(\%fields);
It takes an optional %fields hash which is used to initialize the
object (handy if you use read-only accessors). The fields of the hash
correspond to the names of your accessors, so...
package Foo;
use base qw(Class::Accessor);
Foo->mk_accessors('foo');
my $obj = Foo->new({ foo => 42 });
print $obj->foo; # 42
however %fields can contain anything, new() will shove them all into
your object.
=head1 MAKING ACCESSORS
=head2 follow_best_practice
In Damian's Perl Best Practices book he recommends separate get and set methods
with the prefix set_ and get_ to make it explicit what you intend to do. If you
want to create those accessor methods instead of the default ones, call:
__PACKAGE__->follow_best_practice
B<before> you call any of the accessor-making methods.
=head2 accessor_name_for / mutator_name_for
You may have your own crazy ideas for the names of the accessors, so you can
make those happen by overriding C<accessor_name_for> and C<mutator_name_for> in
your subclass. (I copied that idea from Class::DBI.)
=head2 mk_accessors
__PACKAGE__->mk_accessors(@fields);
This creates accessor/mutator methods for each named field given in
@fields. Foreach field in @fields it will generate two accessors.
One called "field()" and the other called "_field_accessor()". For
example:
# Generates foo(), _foo_accessor(), bar() and _bar_accessor().
__PACKAGE__->mk_accessors(qw(foo bar));
See L<CAVEATS AND TRICKS/"Overriding autogenerated accessors">
for details.
=head2 mk_ro_accessors
__PACKAGE__->mk_ro_accessors(@read_only_fields);
Same as mk_accessors() except it will generate read-only accessors
(ie. true accessors). If you attempt to set a value with these
accessors it will throw an exception. It only uses get() and not
set().
package Foo;
use base qw(Class::Accessor);
Foo->mk_ro_accessors(qw(foo bar));
# Let's assume we have an object $foo of class Foo...
print $foo->foo; # ok, prints whatever the value of $foo->{foo} is
$foo->foo(42); # BOOM! Naughty you.
=head2 mk_wo_accessors
__PACKAGE__->mk_wo_accessors(@write_only_fields);
Same as mk_accessors() except it will generate write-only accessors
(ie. mutators). If you attempt to read a value with these accessors
it will throw an exception. It only uses set() and not get().
B<NOTE> I'm not entirely sure why this is useful, but I'm sure someone
will need it. If you've found a use, let me know. Right now it's here
for orthogonality and because it's easy to implement.
package Foo;
use base qw(Class::Accessor);
Foo->mk_wo_accessors(qw(foo bar));
# Let's assume we have an object $foo of class Foo...
$foo->foo(42); # OK. Sets $self->{foo} = 42
print $foo->foo; # BOOM! Can't read from this accessor.
=head1 Moose!
If you prefer a Moose-like interface to create accessors, you can use C<has> by
importing this module like this:
use Class::Accessor "antlers";
or
use Class::Accessor "moose-like";
Then you can declare accessors like this:
has alpha => ( is => "rw", isa => "Str" );
has beta => ( is => "ro", isa => "Str" );
has gamma => ( is => "wo", isa => "Str" );
Currently only the C<is> attribute is supported. And our C<is> also supports
the "wo" value to make a write-only accessor.
If you are using the Moose-like interface then you should use the C<extends>
rather than tweaking your C<@ISA> directly. Basically, replace
@ISA = qw/Foo Bar/;
with
extends(qw/Foo Bar/);
=head1 DETAILS
An accessor generated by Class::Accessor looks something like
this:
# Your foo may vary.
sub foo {
my($self) = shift;
if(@_) { # set
return $self->set('foo', @_);
}
else {
return $self->get('foo');
}
}
Very simple. All it does is determine if you're wanting to set a
value or get a value and calls the appropriate method.
Class::Accessor provides default get() and set() methods which
your class can override. They're detailed later.
=head2 Modifying the behavior of the accessor
Rather than actually modifying the accessor itself, it is much more
sensible to simply override the two key methods which the accessor
calls. Namely set() and get().
If you -really- want to, you can override make_accessor().
=head2 set
$obj->set($key, $value);
$obj->set($key, @values);
set() defines how generally one stores data in the object.
override this method to change how data is stored by your accessors.
=head2 get
$value = $obj->get($key);
@values = $obj->get(@keys);
get() defines how data is retrieved from your objects.
override this method to change how it is retrieved.
=head2 make_accessor
$accessor = __PACKAGE__->make_accessor($field);
Generates a subroutine reference which acts as an accessor for the given
$field. It calls get() and set().
If you wish to change the behavior of your accessors, try overriding
get() and set() before you start mucking with make_accessor().
=head2 make_ro_accessor
$read_only_accessor = __PACKAGE__->make_ro_accessor($field);
Generates a subroutine reference which acts as a read-only accessor for
the given $field. It only calls get().
Override get() to change the behavior of your accessors.
=head2 make_wo_accessor
$write_only_accessor = __PACKAGE__->make_wo_accessor($field);
Generates a subroutine reference which acts as a write-only accessor
(mutator) for the given $field. It only calls set().
Override set() to change the behavior of your accessors.
=head1 EXCEPTIONS
If something goes wrong Class::Accessor will warn or die by calling Carp::carp
or Carp::croak. If you don't like this you can override _carp() and _croak() in
your subclass and do whatever else you want.
=head1 EFFICIENCY
Class::Accessor does not employ an autoloader, thus it is much faster
than you'd think. Its generated methods incur no special penalty over
ones you'd write yourself.
accessors:
Rate Basic Fast Faster Direct
Basic 367589/s -- -51% -55% -89%
Fast 747964/s 103% -- -9% -77%
Faster 819199/s 123% 10% -- -75%
Direct 3245887/s 783% 334% 296% --
mutators:
Rate Acc Fast Faster Direct
Acc 265564/s -- -54% -63% -91%
Fast 573439/s 116% -- -21% -80%
Faster 724710/s 173% 26% -- -75%
Direct 2860979/s 977% 399% 295% --
Class::Accessor::Fast is faster than methods written by an average programmer
(where "average" is based on Schwern's example code).
Class::Accessor is slower than average, but more flexible.
Class::Accessor::Faster is even faster than Class::Accessor::Fast. It uses an
array internally, not a hash. This could be a good or bad feature depending on
your point of view.
Direct hash access is, of course, much faster than all of these, but it
provides no encapsulation.
Of course, it's not as simple as saying "Class::Accessor is slower than
average". These are benchmarks for a simple accessor. If your accessors do
any sort of complicated work (such as talking to a database or writing to a
file) the time spent doing that work will quickly swamp the time spend just
calling the accessor. In that case, Class::Accessor and the ones you write
will be roughly the same speed.
=head1 EXAMPLES
Here's an example of generating an accessor for every public field of
your class.
package Altoids;
use base qw(Class::Accessor Class::Fields);
use fields qw(curiously strong mints);
Altoids->mk_accessors( Altoids->show_fields('Public') );
sub new {
my $proto = shift;
my $class = ref $proto || $proto;
return fields::new($class);
}
my Altoids $tin = Altoids->new;
$tin->curiously('Curiouser and curiouser');
print $tin->{curiously}; # prints 'Curiouser and curiouser'
# Subclassing works, too.
package Mint::Snuff;
use base qw(Altoids);
my Mint::Snuff $pouch = Mint::Snuff->new;
$pouch->strong('Blow your head off!');
print $pouch->{strong}; # prints 'Blow your head off!'
Here's a simple example of altering the behavior of your accessors.
package Foo;
use base qw(Class::Accessor);
Foo->mk_accessors(qw(this that up down));
sub get {
my $self = shift;
# Note every time someone gets some data.
print STDERR "Getting @_\n";
$self->SUPER::get(@_);
}
sub set {
my ($self, $key) = splice(@_, 0, 2);
# Note every time someone sets some data.
print STDERR "Setting $key to @_\n";
$self->SUPER::set($key, @_);
}
=head1 CAVEATS AND TRICKS
Class::Accessor has to do some internal wackiness to get its
job done quickly and efficiently. Because of this, there's a few
tricks and traps one must know about.
Hey, nothing's perfect.
=head2 Don't make a field called DESTROY
This is bad. Since DESTROY is a magical method it would be bad for us
to define an accessor using that name. Class::Accessor will
carp if you try to use it with a field named "DESTROY".
=head2 Overriding autogenerated accessors
You may want to override the autogenerated accessor with your own, yet
have your custom accessor call the default one. For instance, maybe
you want to have an accessor which checks its input. Normally, one
would expect this to work:
package Foo;
use base qw(Class::Accessor);
Foo->mk_accessors(qw(email this that whatever));
# Only accept addresses which look valid.
sub email {
my($self) = shift;
my($email) = @_;
if( @_ ) { # Setting
require Email::Valid;
unless( Email::Valid->address($email) ) {
carp("$email doesn't look like a valid address.");
return;
}
}
return $self->SUPER::email(@_);
}
There's a subtle problem in the last example, and it's in this line:
return $self->SUPER::email(@_);
If we look at how Foo was defined, it called mk_accessors() which
stuck email() right into Foo's namespace. There *is* no
SUPER::email() to delegate to! Two ways around this... first is to
make a "pure" base class for Foo. This pure class will generate the
accessors and provide the necessary super class for Foo to use:
package Pure::Organic::Foo;
use base qw(Class::Accessor);
Pure::Organic::Foo->mk_accessors(qw(email this that whatever));
package Foo;
use base qw(Pure::Organic::Foo);
And now Foo::email() can override the generated
Pure::Organic::Foo::email() and use it as SUPER::email().
This is probably the most obvious solution to everyone but me.
Instead, what first made sense to me was for mk_accessors() to define
an alias of email(), _email_accessor(). Using this solution,
Foo::email() would be written with:
return $self->_email_accessor(@_);
instead of the expected SUPER::email().
=head1 AUTHORS
Copyright 2017 Marty Pauley <marty+perl@martian.org>
This program is free software; you can redistribute it and/or modify it under
the same terms as Perl itself. That means either (a) the GNU General Public
License or (b) the Artistic License.
=head2 ORIGINAL AUTHOR
Michael G Schwern <schwern@pobox.com>
=head2 THANKS
Liz and RUZ for performance tweaks.
Tels, for his big feature request/bug report.
Various presenters at YAPC::Asia 2009 for criticising the non-Moose interface.
=head1 SEE ALSO
See L<Class::Accessor::Fast> and L<Class::Accessor::Faster> if speed is more
important than flexibility.
These are some modules which do similar things in different ways
L<Class::Struct>, L<Class::Methodmaker>, L<Class::Generate>,
L<Class::Class>, L<Class::Contract>, L<Moose>, L<Mouse>
See L<Class::DBI> for an example of this module in use.
=cut

View File

@@ -0,0 +1,97 @@
package Class::Accessor::Fast;
use base 'Class::Accessor';
use strict;
use B 'perlstring';
$Class::Accessor::Fast::VERSION = '0.51';
sub make_accessor {
my ($class, $field) = @_;
eval sprintf q{
sub {
return $_[0]{%s} if scalar(@_) == 1;
return $_[0]{%s} = scalar(@_) == 2 ? $_[1] : [@_[1..$#_]];
}
}, map { perlstring($_) } $field, $field;
}
sub make_ro_accessor {
my($class, $field) = @_;
eval sprintf q{
sub {
return $_[0]{%s} if @_ == 1;
my $caller = caller;
$_[0]->_croak(sprintf "'$caller' cannot alter the value of '%%s' on objects of class '%%s'", %s, %s);
}
}, map { perlstring($_) } $field, $field, $class;
}
sub make_wo_accessor {
my($class, $field) = @_;
eval sprintf q{
sub {
if (@_ == 1) {
my $caller = caller;
$_[0]->_croak(sprintf "'$caller' cannot access the value of '%%s' on objects of class '%%s'", %s, %s);
}
else {
return $_[0]{%s} = $_[1] if @_ == 2;
return (shift)->{%s} = \@_;
}
}
}, map { perlstring($_) } $field, $class, $field, $field;
}
1;
__END__
=head1 NAME
Class::Accessor::Fast - Faster, but less expandable, accessors
=head1 SYNOPSIS
package Foo;
use base qw(Class::Accessor::Fast);
# The rest is the same as Class::Accessor but without set() and get().
=head1 DESCRIPTION
This is a faster but less expandable version of Class::Accessor.
Class::Accessor's generated accessors require two method calls to accomplish
their task (one for the accessor, another for get() or set()).
Class::Accessor::Fast eliminates calling set()/get() and does the access itself,
resulting in a somewhat faster accessor.
The downside is that you can't easily alter the behavior of your
accessors, nor can your subclasses. Of course, should you need this
later, you can always swap out Class::Accessor::Fast for
Class::Accessor.
Read the documentation for Class::Accessor for more info.
=head1 EFFICIENCY
L<Class::Accessor/EFFICIENCY> for an efficiency comparison.
=head1 AUTHORS
Copyright 2017 Marty Pauley <marty+perl@martian.org>
This program is free software; you can redistribute it and/or modify it under
the same terms as Perl itself. That means either (a) the GNU General Public
License or (b) the Artistic License.
=head2 ORIGINAL AUTHOR
Michael G Schwern <schwern@pobox.com>
=head1 SEE ALSO
L<Class::Accessor>
=cut

View File

@@ -0,0 +1,109 @@
package Class::Accessor::Faster;
use base 'Class::Accessor';
use strict;
use B 'perlstring';
$Class::Accessor::Faster::VERSION = '0.51';
my %slot;
sub _slot {
my($class, $field) = @_;
my $n = $slot{$class}->{$field};
return $n if defined $n;
$n = keys %{$slot{$class}};
$slot{$class}->{$field} = $n;
return $n;
}
sub new {
my($proto, $fields) = @_;
my($class) = ref $proto || $proto;
my $self = bless [], $class;
$fields = {} unless defined $fields;
for my $k (keys %$fields) {
my $n = $class->_slot($k);
$self->[$n] = $fields->{$k};
}
return $self;
}
sub make_accessor {
my($class, $field) = @_;
my $n = $class->_slot($field);
eval sprintf q{
sub {
return $_[0][%d] if scalar(@_) == 1;
return $_[0][%d] = scalar(@_) == 2 ? $_[1] : [@_[1..$#_]];
}
}, $n, $n;
}
sub make_ro_accessor {
my($class, $field) = @_;
my $n = $class->_slot($field);
eval sprintf q{
sub {
return $_[0][%d] if @_ == 1;
my $caller = caller;
$_[0]->_croak(sprintf "'$caller' cannot alter the value of '%%s' on objects of class '%%s'", %s, %s);
}
}, $n, map(perlstring($_), $field, $class);
}
sub make_wo_accessor {
my($class, $field) = @_;
my $n = $class->_slot($field);
eval sprintf q{
sub {
if (@_ == 1) {
my $caller = caller;
$_[0]->_croak(sprintf "'$caller' cannot access the value of '%%s' on objects of class '%%s'", %s, %s);
}
else {
return $_[0][%d] = $_[1] if @_ == 2;
return (shift)->[%d] = \@_;
}
}
}, map(perlstring($_), $field, $class), $n, $n;
}
1;
__END__
=head1 NAME
Class::Accessor::Faster - Even faster, but less expandable, accessors
=head1 SYNOPSIS
package Foo;
use base qw(Class::Accessor::Faster);
=head1 DESCRIPTION
This is a faster but less expandable version of Class::Accessor::Fast.
Class::Accessor's generated accessors require two method calls to accomplish
their task (one for the accessor, another for get() or set()).
Class::Accessor::Fast eliminates calling set()/get() and does the access itself,
resulting in a somewhat faster accessor.
Class::Accessor::Faster uses an array reference underneath to be faster.
Read the documentation for Class::Accessor for more info.
=head1 AUTHORS
Copyright 2017 Marty Pauley <marty+perl@martian.org>
This program is free software; you can redistribute it and/or modify it under
the same terms as Perl itself. That means either (a) the GNU General Public
License or (b) the Artistic License.
=head1 SEE ALSO
L<Class::Accessor>
=cut

View File

@@ -0,0 +1,637 @@
package Class::Struct;
## See POD after __END__
use 5.006_001;
use strict;
use warnings::register;
our(@ISA, @EXPORT, $VERSION);
use Carp;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(struct);
$VERSION = '0.66';
my $print = 0;
sub printem {
if (@_) { $print = shift }
else { $print++ }
}
{
package Class::Struct::Tie_ISA;
sub TIEARRAY {
my $class = shift;
return bless [], $class;
}
sub STORE {
my ($self, $index, $value) = @_;
Class::Struct::_subclass_error();
}
sub FETCH {
my ($self, $index) = @_;
$self->[$index];
}
sub FETCHSIZE {
my $self = shift;
return scalar(@$self);
}
sub DESTROY { }
}
sub import {
my $self = shift;
if ( @_ == 0 ) {
$self->export_to_level( 1, $self, @EXPORT );
} elsif ( @_ == 1 ) {
# This is admittedly a little bit silly:
# do we ever export anything else than 'struct'...?
$self->export_to_level( 1, $self, @_ );
} else {
goto &struct;
}
}
sub struct {
# Determine parameter list structure, one of:
# struct( class => [ element-list ])
# struct( class => { element-list })
# struct( element-list )
# Latter form assumes current package name as struct name.
my ($class, @decls);
my $base_type = ref $_[1];
if ( $base_type eq 'HASH' ) {
$class = shift;
@decls = %{shift()};
_usage_error() if @_;
}
elsif ( $base_type eq 'ARRAY' ) {
$class = shift;
@decls = @{shift()};
_usage_error() if @_;
}
else {
$base_type = 'ARRAY';
$class = (caller())[0];
@decls = @_;
}
_usage_error() if @decls % 2 == 1;
# Ensure we are not, and will not be, a subclass.
my $isa = do {
no strict 'refs';
\@{$class . '::ISA'};
};
_subclass_error() if @$isa;
tie @$isa, 'Class::Struct::Tie_ISA';
# Create constructor.
croak "function 'new' already defined in package $class"
if do { no strict 'refs'; defined &{$class . "::new"} };
my @methods = ();
my %refs = ();
my %arrays = ();
my %hashes = ();
my %classes = ();
my $got_class = 0;
my $out = '';
$out = "{\n package $class;\n use Carp;\n sub new {\n";
$out .= " my (\$class, \%init) = \@_;\n";
$out .= " \$class = __PACKAGE__ unless \@_;\n";
my $cnt = 0;
my $idx = 0;
my( $cmt, $name, $type, $elem );
if( $base_type eq 'HASH' ){
$out .= " my(\$r) = {};\n";
$cmt = '';
}
elsif( $base_type eq 'ARRAY' ){
$out .= " my(\$r) = [];\n";
}
$out .= " bless \$r, \$class;\n\n";
while( $idx < @decls ){
$name = $decls[$idx];
$type = $decls[$idx+1];
push( @methods, $name );
if( $base_type eq 'HASH' ){
$elem = "{'${class}::$name'}";
}
elsif( $base_type eq 'ARRAY' ){
$elem = "[$cnt]";
++$cnt;
$cmt = " # $name";
}
if( $type =~ /^\*(.)/ ){
$refs{$name}++;
$type = $1;
}
my $init = "defined(\$init{'$name'}) ? \$init{'$name'} :";
if( $type eq '@' ){
$out .= " croak 'Initializer for $name must be array reference'\n";
$out .= " if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'ARRAY';\n";
$out .= " \$r->$name( $init [] );$cmt\n";
$arrays{$name}++;
}
elsif( $type eq '%' ){
$out .= " croak 'Initializer for $name must be hash reference'\n";
$out .= " if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'HASH';\n";
$out .= " \$r->$name( $init {} );$cmt\n";
$hashes{$name}++;
}
elsif ( $type eq '$') {
$out .= " \$r->$name( $init undef );$cmt\n";
}
elsif( $type =~ /^\w+(?:::\w+)*$/ ){
$out .= " if (defined(\$init{'$name'})) {\n";
$out .= " if (ref \$init{'$name'} eq 'HASH')\n";
$out .= " { \$r->$name( $type->new(\%{\$init{'$name'}}) ) } $cmt\n";
$out .= " elsif (UNIVERSAL::isa(\$init{'$name'}, '$type'))\n";
$out .= " { \$r->$name( \$init{'$name'} ) } $cmt\n";
$out .= " else { croak 'Initializer for $name must be hash or $type reference' }\n";
$out .= " }\n";
$classes{$name} = $type;
$got_class = 1;
}
else{
croak "'$type' is not a valid struct element type";
}
$idx += 2;
}
$out .= "\n \$r;\n}\n";
# Create accessor methods.
my( $pre, $pst, $sel );
$cnt = 0;
foreach $name (@methods){
if ( do { no strict 'refs'; defined &{$class . "::$name"} } ) {
warnings::warnif("function '$name' already defined, overrides struct accessor method");
}
else {
$pre = $pst = $cmt = $sel = '';
if( defined $refs{$name} ){
$pre = "\\(";
$pst = ")";
$cmt = " # returns ref";
}
$out .= " sub $name {$cmt\n my \$r = shift;\n";
if( $base_type eq 'ARRAY' ){
$elem = "[$cnt]";
++$cnt;
}
elsif( $base_type eq 'HASH' ){
$elem = "{'${class}::$name'}";
}
if( defined $arrays{$name} ){
$out .= " my \$i;\n";
$out .= " \@_ ? (\$i = shift) : return \$r->$elem;\n";
$out .= " if (ref(\$i) eq 'ARRAY' && !\@_) { \$r->$elem = \$i; return \$r }\n";
$sel = "->[\$i]";
}
elsif( defined $hashes{$name} ){
$out .= " my \$i;\n";
$out .= " \@_ ? (\$i = shift) : return \$r->$elem;\n";
$out .= " if (ref(\$i) eq 'HASH' && !\@_) { \$r->$elem = \$i; return \$r }\n";
$sel = "->{\$i}";
}
elsif( defined $classes{$name} ){
$out .= " croak '$name argument is wrong class' if \@_ && ! UNIVERSAL::isa(\$_[0], '$classes{$name}');\n";
}
$out .= " croak 'Too many args to $name' if \@_ > 1;\n";
$out .= " \@_ ? ($pre\$r->$elem$sel = shift$pst) : $pre\$r->$elem$sel$pst;\n";
$out .= " }\n";
}
}
$out .= "}\n1;\n";
print $out if $print;
my $result = eval $out;
carp $@ if $@;
}
sub _usage_error {
confess "struct usage error";
}
sub _subclass_error {
croak 'struct class cannot be a subclass (@ISA not allowed)';
}
1; # for require
__END__
=head1 NAME
Class::Struct - declare struct-like datatypes as Perl classes
=head1 SYNOPSIS
use Class::Struct;
# declare struct, based on array:
struct( CLASS_NAME => [ ELEMENT_NAME => ELEMENT_TYPE, ... ]);
# declare struct, based on hash:
struct( CLASS_NAME => { ELEMENT_NAME => ELEMENT_TYPE, ... });
package CLASS_NAME;
use Class::Struct;
# declare struct, based on array, implicit class name:
struct( ELEMENT_NAME => ELEMENT_TYPE, ... );
# Declare struct at compile time
use Class::Struct CLASS_NAME => [ELEMENT_NAME => ELEMENT_TYPE, ...];
use Class::Struct CLASS_NAME => {ELEMENT_NAME => ELEMENT_TYPE, ...};
# declare struct at compile time, based on array, implicit
# class name:
package CLASS_NAME;
use Class::Struct ELEMENT_NAME => ELEMENT_TYPE, ... ;
package Myobj;
use Class::Struct;
# declare struct with four types of elements:
struct( s => '$', a => '@', h => '%', c => 'My_Other_Class' );
$obj = new Myobj; # constructor
# scalar type accessor:
$element_value = $obj->s; # element value
$obj->s('new value'); # assign to element
# array type accessor:
$ary_ref = $obj->a; # reference to whole array
$ary_element_value = $obj->a(2); # array element value
$obj->a(2, 'new value'); # assign to array element
# hash type accessor:
$hash_ref = $obj->h; # reference to whole hash
$hash_element_value = $obj->h('x'); # hash element value
$obj->h('x', 'new value'); # assign to hash element
# class type accessor:
$element_value = $obj->c; # object reference
$obj->c->method(...); # call method of object
$obj->c(new My_Other_Class); # assign a new object
=head1 DESCRIPTION
C<Class::Struct> exports a single function, C<struct>.
Given a list of element names and types, and optionally
a class name, C<struct> creates a Perl 5 class that implements
a "struct-like" data structure.
The new class is given a constructor method, C<new>, for creating
struct objects.
Each element in the struct data has an accessor method, which is
used to assign to the element and to fetch its value. The
default accessor can be overridden by declaring a C<sub> of the
same name in the package. (See Example 2.)
Each element's type can be scalar, array, hash, or class.
=head2 The C<struct()> function
The C<struct> function has three forms of parameter-list.
struct( CLASS_NAME => [ ELEMENT_LIST ]);
struct( CLASS_NAME => { ELEMENT_LIST });
struct( ELEMENT_LIST );
The first and second forms explicitly identify the name of the
class being created. The third form assumes the current package
name as the class name.
An object of a class created by the first and third forms is
based on an array, whereas an object of a class created by the
second form is based on a hash. The array-based forms will be
somewhat faster and smaller; the hash-based forms are more
flexible.
The class created by C<struct> must not be a subclass of another
class other than C<UNIVERSAL>.
It can, however, be used as a superclass for other classes. To facilitate
this, the generated constructor method uses a two-argument blessing.
Furthermore, if the class is hash-based, the key of each element is
prefixed with the class name (see I<Perl Cookbook>, Recipe 13.12).
A function named C<new> must not be explicitly defined in a class
created by C<struct>.
The I<ELEMENT_LIST> has the form
NAME => TYPE, ...
Each name-type pair declares one element of the struct. Each
element name will be defined as an accessor method unless a
method by that name is explicitly defined; in the latter case, a
warning is issued if the warning flag (B<-w>) is set.
=head2 Class Creation at Compile Time
C<Class::Struct> can create your class at compile time. The main reason
for doing this is obvious, so your class acts like every other class in
Perl. Creating your class at compile time will make the order of events
similar to using any other class ( or Perl module ).
There is no significant speed gain between compile time and run time
class creation, there is just a new, more standard order of events.
=head2 Element Types and Accessor Methods
The four element types -- scalar, array, hash, and class -- are
represented by strings -- C<'$'>, C<'@'>, C<'%'>, and a class name --
optionally preceded by a C<'*'>.
The accessor method provided by C<struct> for an element depends
on the declared type of the element.
=over 4
=item Scalar (C<'$'> or C<'*$'>)
The element is a scalar, and by default is initialized to C<undef>
(but see L</Initializing with new>).
The accessor's argument, if any, is assigned to the element.
If the element type is C<'$'>, the value of the element (after
assignment) is returned. If the element type is C<'*$'>, a reference
to the element is returned.
=item Array (C<'@'> or C<'*@'>)
The element is an array, initialized by default to C<()>.
With no argument, the accessor returns a reference to the
element's whole array (whether or not the element was
specified as C<'@'> or C<'*@'>).
With one or two arguments, the first argument is an index
specifying one element of the array; the second argument, if
present, is assigned to the array element. If the element type
is C<'@'>, the accessor returns the array element value. If the
element type is C<'*@'>, a reference to the array element is
returned.
As a special case, when the accessor is called with an array reference
as the sole argument, this causes an assignment of the whole array element.
The object reference is returned.
=item Hash (C<'%'> or C<'*%'>)
The element is a hash, initialized by default to C<()>.
With no argument, the accessor returns a reference to the
element's whole hash (whether or not the element was
specified as C<'%'> or C<'*%'>).
With one or two arguments, the first argument is a key specifying
one element of the hash; the second argument, if present, is
assigned to the hash element. If the element type is C<'%'>, the
accessor returns the hash element value. If the element type is
C<'*%'>, a reference to the hash element is returned.
As a special case, when the accessor is called with a hash reference
as the sole argument, this causes an assignment of the whole hash element.
The object reference is returned.
=item Class (C<'Class_Name'> or C<'*Class_Name'>)
The element's value must be a reference blessed to the named
class or to one of its subclasses. The element is not initialized
by default.
The accessor's argument, if any, is assigned to the element. The
accessor will C<croak> if this is not an appropriate object
reference.
If the element type does not start with a C<'*'>, the accessor
returns the element value (after assignment). If the element type
starts with a C<'*'>, a reference to the element itself is returned.
=back
=head2 Initializing with C<new>
C<struct> always creates a constructor called C<new>. That constructor
may take a list of initializers for the various elements of the new
struct.
Each initializer is a pair of values: I<element name>C< =E<gt> >I<value>.
The initializer value for a scalar element is just a scalar value. The
initializer for an array element is an array reference. The initializer
for a hash is a hash reference.
The initializer for a class element is an object of the corresponding class,
or of one of it's subclasses, or a reference to a hash containing named
arguments to be passed to the element's constructor.
See Example 3 below for an example of initialization.
=head1 EXAMPLES
=over 4
=item Example 1
Giving a struct element a class type that is also a struct is how
structs are nested. Here, C<Timeval> represents a time (seconds and
microseconds), and C<Rusage> has two elements, each of which is of
type C<Timeval>.
use Class::Struct;
struct( Rusage => {
ru_utime => 'Timeval', # user time used
ru_stime => 'Timeval', # system time used
});
struct( Timeval => [
tv_secs => '$', # seconds
tv_usecs => '$', # microseconds
]);
# create an object:
my $t = Rusage->new(ru_utime=>Timeval->new(),
ru_stime=>Timeval->new());
# $t->ru_utime and $t->ru_stime are objects of type Timeval.
# set $t->ru_utime to 100.0 sec and $t->ru_stime to 5.0 sec.
$t->ru_utime->tv_secs(100);
$t->ru_utime->tv_usecs(0);
$t->ru_stime->tv_secs(5);
$t->ru_stime->tv_usecs(0);
=item Example 2
An accessor function can be redefined in order to provide
additional checking of values, etc. Here, we want the C<count>
element always to be nonnegative, so we redefine the C<count>
accessor accordingly.
package MyObj;
use Class::Struct;
# declare the struct
struct ( 'MyObj', { count => '$', stuff => '%' } );
# override the default accessor method for 'count'
sub count {
my $self = shift;
if ( @_ ) {
die 'count must be nonnegative' if $_[0] < 0;
$self->{'MyObj::count'} = shift;
warn "Too many args to count" if @_;
}
return $self->{'MyObj::count'};
}
package main;
$x = new MyObj;
print "\$x->count(5) = ", $x->count(5), "\n";
# prints '$x->count(5) = 5'
print "\$x->count = ", $x->count, "\n";
# prints '$x->count = 5'
print "\$x->count(-5) = ", $x->count(-5), "\n";
# dies due to negative argument!
=item Example 3
The constructor of a generated class can be passed a list
of I<element>=>I<value> pairs, with which to initialize the struct.
If no initializer is specified for a particular element, its default
initialization is performed instead. Initializers for non-existent
elements are silently ignored.
Note that the initializer for a nested class may be specified as
an object of that class, or as a reference to a hash of initializers
that are passed on to the nested struct's constructor.
use Class::Struct;
struct Breed =>
{
name => '$',
cross => '$',
};
struct Cat =>
[
name => '$',
kittens => '@',
markings => '%',
breed => 'Breed',
];
my $cat = Cat->new( name => 'Socks',
kittens => ['Monica', 'Kenneth'],
markings => { socks=>1, blaze=>"white" },
breed => Breed->new(name=>'short-hair', cross=>1),
or: breed => {name=>'short-hair', cross=>1},
);
print "Once a cat called ", $cat->name, "\n";
print "(which was a ", $cat->breed->name, ")\n";
print "had 2 kittens: ", join(' and ', @{$cat->kittens}), "\n";
=back
=head1 Author and Modification History
Modified by Damian Conway, 2001-09-10, v0.62.
Modified implicit construction of nested objects.
Now will also take an object ref instead of requiring a hash ref.
Also default initializes nested object attributes to undef, rather
than calling object constructor without args
Original over-helpfulness was fraught with problems:
* the class's constructor might not be called 'new'
* the class might not have a hash-like-arguments constructor
* the class might not have a no-argument constructor
* "recursive" data structures didn't work well:
package Person;
struct { mother => 'Person', father => 'Person'};
Modified by Casey West, 2000-11-08, v0.59.
Added the ability for compile time class creation.
Modified by Damian Conway, 1999-03-05, v0.58.
Added handling of hash-like arg list to class ctor.
Changed to two-argument blessing in ctor to support
derivation from created classes.
Added classname prefixes to keys in hash-based classes
(refer to "Perl Cookbook", Recipe 13.12 for rationale).
Corrected behaviour of accessors for '*@' and '*%' struct
elements. Package now implements documented behaviour when
returning a reference to an entire hash or array element.
Previously these were returned as a reference to a reference
to the element.
Renamed to C<Class::Struct> and modified by Jim Miner, 1997-04-02.
members() function removed.
Documentation corrected and extended.
Use of struct() in a subclass prohibited.
User definition of accessor allowed.
Treatment of '*' in element types corrected.
Treatment of classes as element types corrected.
Class name to struct() made optional.
Diagnostic checks added.
Originally C<Class::Template> by Dean Roehrich.
# Template.pm --- struct/member template builder
# 12mar95
# Dean Roehrich
#
# changes/bugs fixed since 28nov94 version:
# - podified
# changes/bugs fixed since 21nov94 version:
# - Fixed examples.
# changes/bugs fixed since 02sep94 version:
# - Moved to Class::Template.
# changes/bugs fixed since 20feb94 version:
# - Updated to be a more proper module.
# - Added "use strict".
# - Bug in build_methods, was using @var when @$var needed.
# - Now using my() rather than local().
#
# Uses perl5 classes to create nested data types.
# This is offered as one implementation of Tom Christiansen's
# "structs.pl" idea.
=cut

View File

@@ -0,0 +1,326 @@
package Class::XSAccessor;
use 5.008;
use strict;
use warnings;
use Carp qw/croak/;
use Class::XSAccessor::Heavy;
use XSLoader;
our $VERSION = '1.19';
XSLoader::load('Class::XSAccessor', $VERSION);
sub _make_hash {
my $ref = shift;
if (ref ($ref)) {
if (ref($ref) eq 'ARRAY') {
$ref = { map { $_ => $_ } @$ref }
}
} else {
$ref = { $ref, $ref };
}
return $ref;
}
sub import {
my $own_class = shift;
my ($caller_pkg) = caller();
# Support both { getters => ... } and plain getters => ...
my %opts = ref($_[0]) eq 'HASH' ? %{$_[0]} : @_;
$caller_pkg = $opts{class} if defined $opts{class};
# TODO: Refactor. Move more duplicated code to ::Heavy
my $read_subs = _make_hash($opts{getters} || {});
my $set_subs = _make_hash($opts{setters} || {});
my $acc_subs = _make_hash($opts{accessors} || {});
my $lvacc_subs = _make_hash($opts{lvalue_accessors} || {});
my $pred_subs = _make_hash($opts{predicates} || {});
my $ex_pred_subs = _make_hash($opts{exists_predicates} || {});
my $def_pred_subs = _make_hash($opts{defined_predicates} || {});
my $test_subs = _make_hash($opts{__tests__} || {});
my $construct_subs = $opts{constructors} || [defined($opts{constructor}) ? $opts{constructor} : ()];
my $true_subs = $opts{true} || [];
my $false_subs = $opts{false} || [];
foreach my $subtype ( ["getter", $read_subs],
["setter", $set_subs],
["accessor", $acc_subs],
["lvalue_accessor", $lvacc_subs],
["test", $test_subs],
["ex_predicate", $ex_pred_subs],
["def_predicate", $def_pred_subs],
["def_predicate", $pred_subs] )
{
my $subs = $subtype->[1];
foreach my $subname (keys %$subs) {
my $hashkey = $subs->{$subname};
_generate_method($caller_pkg, $subname, $hashkey, \%opts, $subtype->[0]);
}
}
foreach my $subtype ( ["constructor", $construct_subs],
["true", $true_subs],
["false", $false_subs] )
{
foreach my $subname (@{$subtype->[1]}) {
_generate_method($caller_pkg, $subname, "", \%opts, $subtype->[0]);
}
}
}
sub _generate_method {
my ($caller_pkg, $subname, $hashkey, $opts, $type) = @_;
croak("Cannot use undef as a hash key for generating an XS $type accessor. (Sub: $subname)")
if not defined $hashkey;
$subname = "${caller_pkg}::$subname" if $subname !~ /::/;
Class::XSAccessor::Heavy::check_sub_existence($subname) if not $opts->{replace};
no warnings 'redefine'; # don't warn about an explicitly requested redefine
if ($type eq 'getter') {
newxs_getter($subname, $hashkey);
}
elsif ($type eq 'lvalue_accessor') {
newxs_lvalue_accessor($subname, $hashkey);
}
elsif ($type eq 'setter') {
newxs_setter($subname, $hashkey, $opts->{chained}||0);
}
elsif ($type eq 'def_predicate') {
newxs_defined_predicate($subname, $hashkey);
}
elsif ($type eq 'ex_predicate') {
newxs_exists_predicate($subname, $hashkey);
}
elsif ($type eq 'constructor') {
newxs_constructor($subname);
}
elsif ($type eq 'true') {
newxs_boolean($subname, 1);
}
elsif ($type eq 'false') {
newxs_boolean($subname, 0);
}
elsif ($type eq 'test') {
newxs_test($subname, $hashkey);
}
else {
newxs_accessor($subname, $hashkey, $opts->{chained}||0);
}
}
1;
__END__
=head1 NAME
Class::XSAccessor - Generate fast XS accessors without runtime compilation
=head1 SYNOPSIS
package MyClass;
use Class::XSAccessor
replace => 1, # Replace existing methods (if any)
constructor => 'new',
getters => {
get_foo => 'foo', # 'foo' is the hash key to access
get_bar => 'bar',
},
setters => {
set_foo => 'foo',
set_bar => 'bar',
},
accessors => {
foo => 'foo',
bar => 'bar',
},
# "predicates" is an alias for "defined_predicates"
defined_predicates => {
defined_foo => 'foo',
defined_bar => 'bar',
},
exists_predicates => {
has_foo => 'foo',
has_bar => 'bar',
},
lvalue_accessors => { # see below
baz => 'baz', # ...
},
true => [ 'is_token', 'is_whitespace' ],
false => [ 'significant' ];
# The imported methods are implemented in fast XS.
# normal class code here.
As of version 1.05, some alternative syntax forms are available:
package MyClass;
# Options can be passed as a HASH reference, if preferred,
# which can also help Perl::Tidy to format the statement correctly.
use Class::XSAccessor {
# If the name => key values are always identical,
# the following shorthand can be used.
accessors => [ 'foo', 'bar' ],
};
=head1 DESCRIPTION
Class::XSAccessor implements fast read, write and read/write accessors in XS.
Additionally, it can provide predicates such as C<has_foo()> for testing
whether the attribute C<foo> exists in the object (which is different from
"is defined within the object").
It only works with objects that are implemented as ordinary hashes.
L<Class::XSAccessor::Array> implements the same interface for objects
that use arrays for their internal representation.
Since version 0.10, the module can also generate simple constructors
(implemented in XS). Simply supply the
C<constructor =E<gt> 'constructor_name'> option or the
C<constructors =E<gt> ['new', 'create', 'spawn']> option.
These constructors do the equivalent of the following Perl code:
sub new {
my $class = shift;
return bless { @_ }, ref($class)||$class;
}
That means they can be called on objects and classes but will not
clone objects entirely. Parameters to C<new()> are added to the
object.
The XS accessor methods are between 3 and 4 times faster than typical
pure-Perl accessors in some simple benchmarking.
The lower factor applies to the potentially slightly obscure
C<sub set_foo_pp {$_[0]-E<gt>{foo} = $_[1]}>, so if you usually
write clear code, a factor of 3.5 speed-up is a good estimate.
If in doubt, do your own benchmarking!
The method names may be fully qualified. The example in the synopsis could
have been written as C<MyClass::get_foo> instead
of C<get_foo>. This way, methods can be installed in classes other
than the current class. See also: the C<class> option below.
By default, the setters return the new value that was set,
and the accessors (mutators) do the same. This behaviour can be changed
with the C<chained> option - see below. The predicates return a boolean.
Since version 1.01, C<Class::XSAccessor> can generate extremely simple methods which
just return true or false (and always do so). If that seems like a
really superfluous thing to you, then consider a large class hierarchy
with interfaces such as L<PPI>. These methods are provided by the C<true>
and C<false> options - see the synopsis.
C<defined_predicates> check whether a given object attribute is defined.
C<predicates> is an alias for C<defined_predicates> for compatibility with
older versions of C<Class::XSAccessor>. C<exists_predicates> checks
whether the given attribute exists in the object using C<exists>.
=head1 OPTIONS
In addition to specifying the types and names of accessors, additional options
can be supplied which modify behaviour. The options are specified as key/value pairs
in the same manner as the accessor declaration. For example:
use Class::XSAccessor
getters => {
get_foo => 'foo',
},
replace => 1;
The list of available options is:
=head2 replace
Set this to a true value to prevent C<Class::XSAccessor> from
complaining about replacing existing subroutines.
=head2 chained
Set this to a true value to change the return value of setters
and mutators (when called with an argument).
If C<chained> is enabled, the setters and accessors/mutators will
return the object. Mutators called without an argument still
return the value of the associated attribute.
As with the other options, C<chained> affects all methods generated
in the same C<use Class::XSAccessor ...> statement.
=head2 class
By default, the accessors are generated in the calling class. The
the C<class> option allows the target class to be specified.
=head1 LVALUES
Support for lvalue accessors via the keyword C<lvalue_accessors>
was added in version 1.08. At this point, B<THEY ARE CONSIDERED HIGHLY
EXPERIMENTAL>. Furthermore, their performance hasn't been benchmarked
yet.
The following example demonstrates an lvalue accessor:
package Address;
use Class::XSAccessor
constructor => 'new',
lvalue_accessors => { zip_code => 'zip' };
package main;
my $address = Address->new(zip => 2);
print $address->zip_code, "\n"; # prints 2
$address->zip_code = 76135; # <--- This is it!
print $address->zip_code, "\n"; # prints 76135
=head1 CAVEATS
Probably won't work for objects based on I<tied> hashes. But that's a strange thing to do anyway.
Scary code exploiting strange XS features.
If you think writing an accessor in XS should be a laughably simple exercise, then
please contemplate how you could instantiate a new XS accessor for a new hash key
that's only known at run-time. Note that compiling C code at run-time a la L<Inline::C|Inline::C>
is a no go.
Threading. With version 1.00, a memory leak has been B<fixed>. Previously, a small amount of
memory would leak if C<Class::XSAccessor>-based classes were loaded in a subthread without having
been loaded in the "main" thread. If the subthread then terminated, a hash key and an int per
associated method used to be lost. Note that this mattered only if classes were B<only> loaded
in a sort of throw-away thread.
In the new implementation, as of 1.00, the memory will still not be released, in the same situation,
but it will be recycled when the same class, or a similar class, is loaded again in B<any> thread.
=head1 SEE ALSO
=over
=item * L<Class::XSAccessor::Array>
=item * L<AutoXS>
=back
=head1 AUTHOR
Steffen Mueller E<lt>smueller@cpan.orgE<gt>
chocolateboy E<lt>chocolate@cpan.orgE<gt>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013 by Steffen Mueller
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8 or,
at your option, any later version of Perl 5 you may have available.
=cut

View File

@@ -0,0 +1,284 @@
package Class::XSAccessor::Array;
use 5.008;
use strict;
use warnings;
use Carp qw/croak/;
use Class::XSAccessor;
use Class::XSAccessor::Heavy;
our $VERSION = '1.19';
sub import {
my $own_class = shift;
my ($caller_pkg) = caller();
# Support both { getters => ... } and plain getters => ...
my %opts = ref($_[0]) eq 'HASH' ? %{$_[0]} : @_;
$caller_pkg = $opts{class} if defined $opts{class};
my $read_subs = $opts{getters} || {};
my $set_subs = $opts{setters} || {};
my $acc_subs = $opts{accessors} || {};
my $lvacc_subs = $opts{lvalue_accessors} || {};
my $pred_subs = $opts{predicates} || {};
my $construct_subs = $opts{constructors} || [defined($opts{constructor}) ? $opts{constructor} : ()];
my $true_subs = $opts{true} || [];
my $false_subs = $opts{false} || [];
foreach my $subtype ( ["getter", $read_subs],
["setter", $set_subs],
["accessor", $acc_subs],
["lvalue_accessor", $lvacc_subs],
["pred_subs", $pred_subs] )
{
my $subs = $subtype->[1];
foreach my $subname (keys %$subs) {
my $array_index = $subs->{$subname};
_generate_method($caller_pkg, $subname, $array_index, \%opts, $subtype->[0]);
}
}
foreach my $subtype ( ["constructor", $construct_subs],
["true", $true_subs],
["false", $false_subs] )
{
foreach my $subname (@{$subtype->[1]}) {
_generate_method($caller_pkg, $subname, "", \%opts, $subtype->[0]);
}
}
}
sub _generate_method {
my ($caller_pkg, $subname, $array_index, $opts, $type) = @_;
croak("Cannot use undef as a array index for generating an XS $type accessor. (Sub: $subname)")
if not defined $array_index;
$subname = "${caller_pkg}::$subname" if $subname !~ /::/;
Class::XSAccessor::Heavy::check_sub_existence($subname) if not $opts->{replace};
no warnings 'redefine'; # don't warn about an explicitly requested redefine
if ($type eq 'getter') {
newxs_getter($subname, $array_index);
}
if ($type eq 'lvalue_accessor') {
newxs_lvalue_accessor($subname, $array_index);
}
elsif ($type eq 'setter') {
newxs_setter($subname, $array_index, $opts->{chained}||0);
}
elsif ($type eq 'predicate') {
newxs_predicate($subname, $array_index);
}
elsif ($type eq 'constructor') {
newxs_constructor($subname);
}
elsif ($type eq 'true') {
Class::XSAccessor::newxs_boolean($subname, 1);
}
elsif ($type eq 'false') {
Class::XSAccessor::newxs_boolean($subname, 0);
}
else {
newxs_accessor($subname, $array_index, $opts->{chained}||0);
}
}
1;
__END__
=head1 NAME
Class::XSAccessor::Array - Generate fast XS accessors without runtime compilation
=head1 SYNOPSIS
package MyClassUsingArraysAsInternalStorage;
use Class::XSAccessor::Array
constructor => 'new',
getters => {
get_foo => 0, # 0 is the array index to access
get_bar => 1,
},
setters => {
set_foo => 0,
set_bar => 1,
},
accessors => { # a mutator
buz => 2,
},
predicates => { # test for definedness
has_buz => 2,
},
lvalue_accessors => { # see below
baz => 3,
},
true => [ 'is_token', 'is_whitespace' ],
false => [ 'significant' ];
# The imported methods are implemented in fast XS.
# normal class code here.
As of version 1.05, some alternative syntax forms are available:
package MyClass;
# Options can be passed as a HASH reference if you prefer it,
# which can also help PerlTidy to flow the statement correctly.
use Class::XSAccessor {
getters => {
get_foo => 0,
get_bar => 1,
},
};
=head1 DESCRIPTION
The module implements fast XS accessors both for getting at and
setting an object attribute. Additionally, the module supports
mutators and simple predicates (C<has_foo()> like tests for definedness
of an attributes).
The module works only with objects
that are implemented as B<arrays>. Using it on hash-based objects is
bound to make your life miserable. Refer to L<Class::XSAccessor> for
an implementation that works with hash-based objects.
A simple benchmark showed a significant performance
advantage over writing accessors in Perl.
Since version 0.10, the module can also generate simple constructors
(implemented in XS) for you. Simply supply the
C<constructor =E<gt> 'constructor_name'> option or the
C<constructors =E<gt> ['new', 'create', 'spawn']> option.
These constructors do the equivalent of the following Perl code:
sub new {
my $class = shift;
return bless [], ref($class)||$class;
}
That means they can be called on objects and classes but will not
clone objects entirely. Note that any parameters to new() will be
discarded! If there is a better idiom for array-based objects, let
me know.
While generally more obscure than hash-based objects,
objects using blessed arrays as internal representation
are a bit faster as its somewhat faster to access arrays than hashes.
Accordingly, this module is slightly faster (~10-15%) than
L<Class::XSAccessor>, which works on hash-based objects.
The method names may be fully qualified. In the example of the
synopsis, you could have written C<MyClass::get_foo> instead
of C<get_foo>. This way, you can install methods in classes other
than the current class. See also: The C<class> option below.
Since version 1.01, you can generate extremely simple methods which
just return true or false (and always do so). If that seems like a
really superfluous thing to you, then think of a large class hierarchy
with interfaces such as PPI. This is implemented as the C<true>
and C<false> options, see synopsis.
=head1 OPTIONS
In addition to specifying the types and names of accessors, you can add options
which modify behaviour. The options are specified as key/value pairs just as the
accessor declaration. Example:
use Class::XSAccessor::Array
getters => {
get_foo => 0,
},
replace => 1;
The list of available options is:
=head2 replace
Set this to a true value to prevent C<Class::XSAccessor::Array> from
complaining about replacing existing subroutines.
=head2 chained
Set this to a true value to change the return value of setters
and mutators (when called with an argument).
If C<chained> is enabled, the setters and accessors/mutators will
return the object. Mutators called without an argument still
return the value of the associated attribute.
As with the other options, C<chained> affects all methods generated
in the same C<use Class::XSAccessor::Array ...> statement.
=head2 class
By default, the accessors are generated in the calling class. Using
the C<class> option, you can explicitly specify where the methods
are to be generated.
=head1 LVALUES
Support for lvalue accessors via the keyword C<lvalue_accessors>
was added in version 1.08. At this point, B<THEY ARE CONSIDERED HIGHLY
EXPERIMENTAL>. Furthermore, their performance hasn't been benchmarked
yet.
The following example demonstrates an lvalue accessor:
package Address;
use Class::XSAccessor
constructor => 'new',
lvalue_accessors => { zip_code => 0 };
package main;
my $address = Address->new(2);
print $address->zip_code, "\n"; # prints 2
$address->zip_code = 76135; # <--- This is it!
print $address->zip_code, "\n"; # prints 76135
=head1 CAVEATS
Probably wouldn't work if your objects are I<tied>. But that's a strange thing to do anyway.
Scary code exploiting strange XS features.
If you think writing an accessor in XS should be a laughably simple exercise, then
please contemplate how you could instantiate a new XS accessor for a new hash key
or array index that's only known at run-time. Note that compiling C code at run-time
a la Inline::C is a no go.
Threading. With version 1.00, a memory leak has been B<fixed> that would leak a small amount of
memory if you loaded C<Class::XSAccessor>-based classes in a subthread that hadn't been loaded
in the "main" thread before. If the subthread then terminated, a hash key and an int per
associated method used to be lost. Note that this mattered only if classes were B<only> loaded
in a sort of throw-away thread.
In the new implementation as of 1.00, the memory will not be released again either in the above
situation. But it will be recycled when the same class or a similar class is loaded
again in B<any> thread.
=head1 SEE ALSO
L<Class::XSAccessor>
L<AutoXS>
=head1 AUTHOR
Steffen Mueller E<lt>smueller@cpan.orgE<gt>
chocolateboy E<lt>chocolate@cpan.orgE<gt>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013 by Steffen Mueller
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8 or,
at your option, any later version of Perl 5 you may have available.
=cut

View File

@@ -0,0 +1,76 @@
package # hide from PAUSE
Class::XSAccessor::Heavy;
use 5.008;
use strict;
use warnings;
use Carp;
our $VERSION = '1.19';
our @CARP_NOT = qw(
Class::XSAccessor
Class::XSAccessor::Array
);
# TODO Move more duplicated code from XSA and XSA::Array here
sub check_sub_existence {
my $subname = shift;
my $sub_package = $subname;
$sub_package =~ s/([^:]+)$// or die;
my $bare_subname = $1;
my $sym;
{
no strict 'refs';
$sym = \%{"$sub_package"};
}
no warnings;
local *s = $sym->{$bare_subname};
my $coderef = *s{CODE};
if ($coderef) {
$sub_package =~ s/::$//;
Carp::croak("Cannot replace existing subroutine '$bare_subname' in package '$sub_package' with an XS implementation. If you wish to force a replacement, add the 'replace => 1' parameter to the arguments of 'use ".(caller())[0]."'.");
}
}
1;
__END__
=head1 NAME
Class::XSAccessor::Heavy - Guts you don't care about
=head1 SYNOPSIS
use Class::XSAccessor!
=head1 DESCRIPTION
Common guts for Class::XSAccessor and Class::XSAccessor::Array.
No user-serviceable parts inside!
=head1 SEE ALSO
L<Class::XSAccessor>
L<Class::XSAccessor::Array>
=head1 AUTHOR
Steffen Mueller, E<lt>smueller@cpan.orgE<gt>
chocolateboy, E<lt>chocolate@cpan.orgE<gt>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013 by Steffen Mueller
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8 or,
at your option, any later version of Perl 5 you may have available.
=cut