Tree-1.07000755001750001750 012453731754 11132 5ustar00ronron000000000000Tree-1.07/Build.PL000444001750001750 316512453731754 12570 0ustar00ronron000000000000use strict; use warnings; use Module::Build; use 5.6.0; # ----------------------------------------------- my $class = Module::Build->subclass(code => <<'EOF'); sub ACTION_authortest { my($self) = @_; $self->depends_on('build'); $self->depends_on('manifest'); $self->depends_on('distmeta'); $self->test_files( qw< t xt/author > ); $self->recursive_test_files(1); $self->depends_on('test'); return; } EOF $class -> new ( module_name => 'Tree', license => 'artistic_2', dist_abstract => 'An N-ary tree', dist_author => 'Ron Savage ', build_requires => { 'base' => 0, 'constant' => 0, 'Data::Dumper' => 2.136, 'Exporter' => 5.66, 'overload' => 0, 'Scalar::Util' => 1.10, 'strict' => 0, 'Test::Deep' => 0.088, 'Test::Exception' => 0.15, # 'Test::Pod' => 1.45, # Make it optional. See t/pod.t # 'Test::Pod::Coverage' => 1.08, # Make it optional. See t/pod.t 'Test::More' => 0.47, 'Test::Warn' => 0.08, 'warnings' => 0, }, configure_requires => { 'Module::Build' => 0.40, }, meta_merge => { resources => { repository => 'https://github.com/ronsavage/Tree', }, }, requires => { 'perl' => '5.6.0', 'Scalar::Util' => 1.10, }, recursive_test_files => 1, add_to_cleanup => [ 'META.yml', '*.bak', '*.gz', 'Makefile.PL', ], resources => { bugtracker => 'https://rt.cpan.org/Public/Dist/Display.html?Name=Tree', license => 'http://opensource.org/licenses/Artistic-2.0', }, ) -> create_build_script; Tree-1.07/README000444001750001750 242712453731754 12154 0ustar00ronron000000000000README file for Tree. See also: CHANGES and Changelog.ini. Warning: WinZip 8.1 and 9.0 both contain an 'accidental' bug which stops them recognizing POSIX-style directory structures in valid tar files. You are better off using a reliable tool such as InfoZip: ftp://ftp.info-zip.org/pub/infozip/ 1 Installing from a Unix-like distro ------------------------------------ shell>gunzip Tree-1.05.tgz shell>tar mxvf Tree-1.05.tar On Unix-like systems, assuming you have installed Module::Build V 0.25+: shell>perl Build.PL shell>./Build shell>./Build test shell>./Build install On MS Windows-like systems, assuming you have installed Module::Build V 0.25+: shell>perl Build.PL shell>perl Build shell>perl Build test shell>perl Build install Alternately, without Module::Build, you do this: Note: 'make' on MS Windows-like systems may be called 'nmake' or 'dmake'. shell>perl Makefile.PL shell>make shell>make test shell>su (for Unix-like systems) shell>make install shell>exit (for Unix-like systems) On all systems: Run Tree.pm through your favourite pod2html translator. 2 Installing from an ActiveState distro --------------------------------------- shell>unzip Tree-1.05.zip shell>ppm install --location=. Tree shell>del Tree-1.05.ppd shell>del PPM-Tree-1.05.tar.gz Tree-1.07/META.json000444001750001750 327412453731754 12716 0ustar00ronron000000000000{ "abstract" : "An N-ary tree", "author" : [ "Ron Savage " ], "dynamic_config" : 1, "generated_by" : "Module::Build version 0.421", "license" : [ "artistic_2" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Tree", "prereqs" : { "build" : { "requires" : { "Data::Dumper" : "2.136", "Exporter" : "5.66", "Scalar::Util" : "1.1", "Test::Deep" : "0.088", "Test::Exception" : "0.15", "Test::More" : "0.47", "Test::Warn" : "0.08", "base" : "0", "constant" : "0", "overload" : "0", "strict" : "0", "warnings" : "0" } }, "configure" : { "requires" : { "Module::Build" : "0.4" } }, "runtime" : { "requires" : { "Scalar::Util" : "1.1", "perl" : "v5.6.0" } } }, "provides" : { "Tree" : { "file" : "lib/Tree.pm", "version" : "1.07" }, "Tree::Binary2" : { "file" : "lib/Tree/Binary2.pm", "version" : "1.07" }, "Tree::Fast" : { "file" : "lib/Tree/Fast.pm", "version" : "1.07" }, "Tree::Null" : { "file" : "lib/Tree/Fast.pm", "version" : "1.07" } }, "release_status" : "stable", "resources" : { "license" : [ "http://www.perlfoundation.org/artistic_license_2_0" ], "repository" : { "url" : "https://github.com/ronsavage/Tree" } }, "version" : "1.07" } Tree-1.07/Makefile.PL000444001750001750 357212453731754 13250 0ustar00ronron000000000000use strict; use warnings; require 5.006000; use ExtUtils::MakeMaker; # ---------------------- # See lib/ExtUtils/MakeMaker.pm for details of how to influence # the contents of the Makefile that is written. my(%params) = ( ($] ge '5.005') ? ( AUTHOR => 'Rob Kinyin (rkinyon@cpan.org)', ABSTRACT => 'Persist multiple trees in a single db table, preserving child order', ) : (), clean => { FILES => 'blib/* Makefile MANIFEST Tree-*' }, dist => { COMPRESS => 'gzip', SUFFIX => 'gz' }, DISTNAME => 'Tree', NAME => 'Tree', PL_FILES => {}, LICENSE => 'artistic_2', PREREQ_PM => { 'base' => 0, 'constant' => 0, 'Data::Dumper' => 2.136, 'Exporter' => 5.66, 'overload' => 0, 'Scalar::Util' => 1.10, 'strict' => 0, 'Test::Deep' => 0.088, 'Test::Exception' => 0.15, # 'Test::Pod' => 1.45, # Make it optional. See t/pod.t # 'Test::Pod::Coverage' => 1.08, # Make it optional. See t/pod.t 'Test::More' => 0.47, 'Test::Warn' => 0.08, 'warnings' => 0, }, VERSION_FROM => 'lib/Tree.pm', INSTALLDIRS => 'site', EXE_FILES => [], test => { TESTS => 't/*.t t/Tree_Binary/*.t t/Tree/*.t t/Tree_Fast/*.t', }, ); if ( ($ExtUtils::MakeMaker::VERSION =~ /^\d\.\d\d$/) && ($ExtUtils::MakeMaker::VERSION > 6.30) ) { $params{LICENSE} = 'artistic_2'; } if ($ExtUtils::MakeMaker::VERSION ge '6.46') { $params{META_MERGE} = { 'meta-spec' => { version => 2, }, resources => { bugtracker => 'https://rt.cpan.org/Public/Dist/Display.html?Name=Tree', license => 'http://opensource.org/licenses/Artistic-2.0', repository => { type => 'git', url => 'https://github.com/ronsavage/Tree.git', web => 'https://github.com/ronsavage/Tree', }, }, }; } WriteMakefile(%params); Tree-1.07/.gitignore000444001750001750 26712453731754 13244 0ustar00ronron000000000000/blib/ /.build/ _build/ cover_db/ inc/ Build !Build/ Build.bat .last_cover_stats /Makefile /Makefile.old /MANIFEST.bak /META.yml /META.json /MYMETA.* nytprof.out /pm_to_blib *.o *.bs Tree-1.07/Changelog.ini000444001750001750 474512453731754 13671 0ustar00ronron000000000000[Module] Name=Tree Changelog.Creator=Module::Metadata::Changes V 2.05 Changelog.Parser=Config::IniFiles V 2.83 [V 1.07] Date=2014-01-10T21:39:00 Comments= < value($new_value). - Patch Tree::Fast's meta() to accept a hashref so metadata can be set with $n -> meta({key => value}), as well as by directly accessing the internal hashref '_meta'. - Patch t/Tree/001_root_node.t to test the above. - Rename Changes to CHANGES. - Use ini.report.pl (shipped with Module::Metadata::Changes) to add Changelog.ini to the distro. - Reformat the dates in this file. - Change lib/Tree/Fast.pm to Unix line endings. - Clean up the POD. - Re-work Makefile.PL rather than have Build.PL generate it. - Update pre-reqs in Build.PL and Makefile.PL. - Move t/tests.pm to t/lib/Tests.pm. EOT [V 1.01] Date=2007-10-18T12:00:00 Comments= < 5.006 - Fix for RT# 16889 (clone broken for Tree::Binary) - Patch submitted by HDP - Fix for other miscellenous bugs - Patch submitted by HDP EOT [V 1.00] Date=2005-11-08T12:00:00 Comments=- Initial release [V 0.99] Date=2005-10-24T10:30:00 Comments=- Initial revision Tree-1.07/Changes000444001750001750 443312453731754 12566 0ustar00ronron000000000000Revision history for Perl distribution Tree. 1.07 Fri Jan 10 21:39:00 2014 - Not released - Integrate with github. - Make Build.PL and Makefile.PL look like all my other ones, including using strict and warnings. 1.06 Fri Jan 9 13:24:00 2014 - Add methods and docs for tree2string(), node2string(), format_node(), hashref2string(). Only tree2string() is normally called by end users. 1.05 Wed Jun 5 08:34:00 2014 - No code changes. - For pre-reqs base, constant and overload, which ship with Perl, set the version # to 0. Requested by Andreas Mock. Actually, I should have done this with version 1.04. - Rename CHANGES to Changes as per CPAN::Changes::Spec. 1.04 Thu Nov 8 12:38:00 2012 - No code changes. - For pre-reqs such as strict, warnings, etc, which ship with Perl, set the version # to 0. Reported as RT#80663 by Father Chrysostomos for Tree::DAG_Node. - Add README. 1.03 Fri Nov 2 09:34:00 2012 - Rename Tree::Binary to Tree::Binary2 so it no longer clashes with the Tree::Binary shipped in the Tree-Binary distro. MetaCPAN was getting confused, and automatically redirected links to this module's Tree:Binary to the other one. 1.02 Thu Oct 4 12:10:00 2012 - Ron Savage is now co-maint. - Patch Tree::Fast's value() to accept a defained value so the node's value can be set with $n -> value($new_value). - Patch Tree::Fast's meta() to accept a hashref so metadata can be set with $n -> meta({key => value}), as well as by directly accessing the internal hashref '_meta'. - Patch t/Tree/001_root_node.t to test the above. - Rename Changes to CHANGES. - Use ini.report.pl (shipped with Module::Metadata::Changes) to add Changelog.ini to the distro. - Reformat the dates in this file. - Change lib/Tree/Fast.pm to Unix line endings. - Clean up the POD. - Re-work Makefile.PL rather than have Build.PL generate it. - Update pre-reqs in Build.PL and Makefile.PL. - Move t/tests.pm to t/lib/Tests.pm. 1.01 Thu Oct 18 12:00:00 2007 - Fixed Changes file - Right distro name. - 1.00 release noted - Cleaned up 5.6.0 -> 5.006 - Fix for RT# 16889 (clone broken for Tree::Binary) - Patch submitted by HDP - Fix for other miscellenous bugs - Patch submitted by HDP 1.00 Tue Nov 08 12:00:00 2005 - Initial release 0.99 Mon Oct 24 10:30:00 2005 - Initial revision Tree-1.07/META.yml000444001750001750 177412453731754 12551 0ustar00ronron000000000000--- abstract: 'An N-ary tree' author: - 'Ron Savage ' build_requires: Data::Dumper: '2.136' Exporter: '5.66' Scalar::Util: '1.1' Test::Deep: '0.088' Test::Exception: '0.15' Test::More: '0.47' Test::Warn: '0.08' base: '0' constant: '0' overload: '0' strict: '0' warnings: '0' configure_requires: Module::Build: '0.4' dynamic_config: 1 generated_by: 'Module::Build version 0.421, CPAN::Meta::Converter version 2.142060' license: artistic_2 meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Tree provides: Tree: file: lib/Tree.pm version: '1.07' Tree::Binary2: file: lib/Tree/Binary2.pm version: '1.07' Tree::Fast: file: lib/Tree/Fast.pm version: '1.07' Tree::Null: file: lib/Tree/Fast.pm version: '1.07' requires: Scalar::Util: '1.1' perl: v5.6.0 resources: license: http://www.perlfoundation.org/artistic_license_2_0 repository: https://github.com/ronsavage/Tree version: '1.07' Tree-1.07/MANIFEST000444001750001750 136612453731754 12426 0ustar00ronron000000000000.gitignore Build.PL Changelog.ini Changes lib/Tree.pm lib/Tree/Binary2.pm lib/Tree/Fast.pm LICENSE Makefile.PL MANIFEST This list of files META.json META.yml README scripts/print.tree.pl t/lib/Tests.pm t/pod.t t/pod_coverage.t t/Tree/000_interface.t t/Tree/001_root_node.t t/Tree/002_null_object.t t/Tree/003_child_node.t t/Tree/004_multiple_children.t t/Tree/005_multilevel_tree.t t/Tree/007_add_child.t t/Tree/008_weak_refs.t t/Tree/009_error_handling.t t/Tree/010_errors_addchild.t t/Tree/011_errors_removechild.t t/Tree/012_height.t t/Tree/013_width.t t/Tree/014_clone.t t/Tree/015_traverse.t t/Tree/016_events.t t/Tree/017_traverse_scalar.t t/Tree_Binary/000_binary_trees.t t/Tree_Binary/001_mirror.t t/Tree_Binary/002_clone.t t/Tree_Fast/001_clone.t Tree-1.07/LICENSE000444001750001750 2130412453731754 12314 0ustar00ronron000000000000The Artistic License 2.0 Copyright (c) 2015 Ron Savage Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Tree-1.07/lib000755001750001750 012453731754 11700 5ustar00ronron000000000000Tree-1.07/lib/Tree.pm000555001750001750 6235612453731754 13331 0ustar00ronron000000000000package Tree; use 5.006; use strict; use warnings FATAL => 'all'; our $VERSION = '1.07'; use Scalar::Util qw( blessed refaddr weaken ); use base 'Tree::Fast'; # These are the class methods my %error_handlers = ( 'quiet' => sub { my $node = shift; $node->last_error( join "\n", @_); return; }, 'warn' => sub { my $node = shift; $node->last_error( join "\n", @_); warn @_; return; }, 'die' => sub { my $node = shift; $node->last_error( join "\n", @_); die @_; }, ); sub QUIET { return $error_handlers{ 'quiet' } } sub WARN { return $error_handlers{ 'warn' } } sub DIE { return $error_handlers{ 'die' } } # The default error handler is quiet my $ERROR_HANDLER = $error_handlers{ 'quiet' }; sub _init { my $self = shift; $self->SUPER::_init( @_ ); $self->{_height} = 1, $self->{_width} = 1, $self->{_depth} = 0, $self->{_error_handler} = $ERROR_HANDLER, $self->{_last_error} = undef; $self->{_handlers} = { add_child => [], remove_child => [], value => [], }; $self->{_root} = undef, $self->_set_root( $self ); return $self; } # These are the behaviors sub add_child { my $self = shift; my @nodes = @_; $self->last_error( undef ); my $options = $self->_strip_options( \@nodes ); unless ( @nodes ) { return $self->error( "add_child(): No children passed in" ); } if ( defined $options->{at}) { my $num_children = () = $self->children; unless ( $options->{at} =~ /^-?\d+$/ ) { return $self->error( "add_child(): '$options->{at}' is not a legal index" ); } if ( $options->{at} > $num_children || $num_children + $options->{at} < 0 ) { return $self->error( "add_child(): '$options->{at}' is out-of-bounds" ); } } for my $node ( @nodes ) { unless ( blessed($node) && $node->isa( __PACKAGE__ ) ) { return $self->error( "add_child(): '$node' is not a " . __PACKAGE__ ); } if ( $node->root eq $self->root ) { return $self->error( "add_child(): Cannot add a node in the tree back into the tree" ); } if ( $node->parent ) { return $self->error( "add_child(): Cannot add a child to another parent" ); } } $self->SUPER::add_child( $options, @nodes ); for my $node ( @nodes ) { $node->_set_root( $self->root ); $node->_fix_depth; } $self->_fix_height; $self->_fix_width; $self->event( 'add_child', $self, @_ ); return $self; } sub remove_child { my $self = shift; my @nodes = @_; $self->last_error( undef ); my $options = $self->_strip_options( \@nodes ); unless ( @nodes ) { return $self->error( "remove_child(): Nothing to remove" ); } my @indices; my $num_children = () = $self->children; foreach my $proto (@nodes) { if ( !defined( $proto ) ) { return $self->error( "remove_child(): 'undef' is out-of-bounds" ); } if ( !blessed( $proto ) ) { unless ( $proto =~ /^-?\d+$/ ) { return $self->error( "remove_child(): '$proto' is not a legal index" ); } if ( $proto >= $num_children || $num_children + $proto <= 0 ) { return $self->error( "remove_child(): '$proto' is out-of-bounds" ); } push @indices, $proto; } else { my ($index) = $self->get_index_for( $proto ); unless ( defined $index ) { return $self->error( "remove_child(): '$proto' not found" ); } push @indices, $index; } } my @return = $self->SUPER::remove_child( $options, @indices ); for my $node ( @return ) { $node->_set_root( $node ); $node->_fix_depth; } $self->_fix_height; $self->_fix_width; $self->event( 'remove_child', $self, @_ ); return @return; } sub add_event_handler { my $self = shift; my ($opts) = @_; while ( my ($type,$handler) = each %$opts ) { push @{$self->{_handlers}{$type}}, $handler; } return $self; } sub event { my $self = shift; my ( $type, @args ) = @_; foreach my $handler ( @{$self->{_handlers}{$type}} ) { $handler->( @args ); } $self->parent->event( @_ ); return $self; } # These are the state-queries sub is_root { my $self = shift; return !$self->parent; } sub is_leaf { my $self = shift; return $self->height == 1; } sub has_child { my $self = shift; my @nodes = @_; my @children = $self->children; my %temp = map { refaddr($children[$_]) => $_ } 0 .. $#children; my $rv = 1; $rv &&= exists $temp{refaddr($_)} for @nodes; return $rv; } sub get_index_for { my $self = shift; my @nodes = @_; my @children = $self->children; my %temp = map { refaddr($children[$_]) => $_ } 0 .. $#children; return map { $temp{refaddr($_)} } @nodes; } # These are the smart accessors sub root { my $self = shift; return $self->{_root}; } sub _set_root { my $self = shift; $self->{_root} = shift; weaken( $self->{_root} ); # Propagate the root-change down to all children # Because this is called from DESTROY, we need to verify # that the child still exists because destruction in Perl5 # is neither ordered nor timely. $_->_set_root( $self->{_root} ) for grep { $_ } @{$self->{_children}}; return $self; } for my $name ( qw( height width depth ) ) { no strict 'refs'; *{ __PACKAGE__ . "::${name}" } = sub { use strict; my $self = shift; return $self->{"_${name}"}; }; } sub size { my $self = shift; my $size = 1; $size += $_->size for $self->children; return $size; } sub set_value { my $self = shift; my $old_value = $self->value(); $self->SUPER::set_value( @_ ); $self->event( 'value', $self, $old_value, $self->value ); return $self; } # These are the error-handling functions sub error_handler { my $self = shift; if ( !blessed( $self ) ) { my $old = $ERROR_HANDLER; $ERROR_HANDLER = shift if @_; return $old; } my $root = $self->root; my $old = $root->{_error_handler}; $root->{_error_handler} = shift if @_; return $old; } sub error { my $self = shift; my @args = @_; return $self->error_handler->( $self, @_ ); } sub last_error { my $self = shift; $self->root->{_last_error} = shift if @_; return $self->root->{_last_error}; } # These are private convenience methods sub _fix_height { my $self = shift; my $height = 1; for my $child ($self->children) { my $temp_height = $child->height + 1; $height = $temp_height if $height < $temp_height; } $self->{_height} = $height; $self->parent->_fix_height; return $self; } sub _fix_width { my $self = shift; my $width = 0; $width += $_->width for $self->children; $self->{_width} = $width ? $width : 1; $self->parent->_fix_width; return $self; } sub _fix_depth { my $self = shift; if ( $self->is_root ) { $self->{_depth} = 0; } else { $self->{_depth} = $self->parent->depth + 1; } $_->_fix_depth for $self->children; return $self; } sub _strip_options { my $self = shift; my ($params) = @_; if ( @$params && !blessed($params->[0]) && ref($params->[0]) eq 'HASH' ) { return shift @$params; } else { return {}; } } # ----------------------------------------------- sub format_node { my($self, $options, $node) = @_; my($s) = $node -> value; $s .= '. Attributes: ' . $self -> hashref2string($node -> meta) if (! $$options{no_attributes}); return $s; } # End of format_node. # ----------------------------------------------- sub hashref2string { my($self, $hashref) = @_; $hashref ||= {}; return '{' . join(', ', map{qq|$_ => "$$hashref{$_}"|} sort keys %$hashref) . '}'; } # End of hashref2string. # ----------------------------------------------- sub node2string { my($self, $options, $node, $vert_dashes) = @_; my($depth) = $node -> depth; my(@siblings) = $node -> parent -> children; my($sibling_count) = scalar @siblings; # Warning: Don't combine this with the previous line. my($offset) = ' ' x 4; my(@indent) = map{$$vert_dashes[$_] || $offset} 0 .. $depth - 1; @$vert_dashes = ( @indent, ($sibling_count == 0 ? $offset : ' |'), ); my(@i) = $node -> parent -> get_index_for($node); my(@indexes) = $node -> parent -> get_index_for($node); $$vert_dashes[$depth] = ($offset . ' ') if ($sibling_count == ($indexes[0] + 1) ); return join('', @indent[1 .. $#indent]) . ($depth ? ' |--- ' : '') . $self -> format_node($options, $node); } # End of node2string. # ------------------------------------------------ sub tree2string { my($self, $options) = @_; $options ||= {}; $$options{no_attributes} ||= 0; my(@nodes) = $self -> traverse; my(@out); my(@vert_dashes); for my $i (0 .. $#nodes) { push @out, $self -> node2string($options, $nodes[$i], \@vert_dashes); } return [@out]; } # End of tree2string. # ----------------------------------------------- 1; __END__ =head1 NAME Tree - An N-ary tree =head1 SYNOPSIS my $tree = Tree->new( 'root' ); my $child = Tree->new( 'child' ); $tree->add_child( $child ); $tree->add_child( { at => 0 }, Tree->new( 'first child' ) ); $tree->add_child( { at => -1 }, Tree->new( 'last child' ) ); $tree->set_value( 'toor' ); my $value = $tree->value; my @children = $tree->children; my @some_children = $tree->children( 0, 2 ); my $height = $tree->height; my $width = $tree->width; my $depth = $tree->depth; my $size = $tree->size; if ( $tree->has_child( $child ) ) { $tree->remove_child( $child ); } $tree->remove_child( 0 ); my @nodes = $tree->traverse( $tree->POST_ORDER ); my $clone = $tree->clone; my $mirror = $tree->clone->mirror; $tree->add_event_handler({ add_child => sub { ... }, remove_child => sub { ... }, value => sub { ... }, }); my $old_default_error_handler = $tree->error_handler(Tree->DIE); my $old_object_error_handler = $tree->error_handler($tree->DIE); =head1 DESCRIPTION This is meant to be a full-featured N-ary tree representation with configurable error-handling and a simple events system that allows for transparent persistence to a variety of datastores. It is derived from L, but has a simpler interface and much, much more. =head1 METHODS =head2 Constructors =head2 new([$value]) Here, [] indicate an optional parameter. This will return a C object. It will accept one parameter which, if passed, will become the I (accessible by C). All other parameters will be ignored. If you call C<< $tree->new([$value]) >>, it will instead call C, then set the I of the clone to $value. =head2 clone() This will return a clone of C<$tree>. The clone will be a root tree, but all children will be cloned. If you call C<< Tree->clone([$value]) >>, it will instead call C. B the value is merely a shallow copy. This means that all references will be kept. =head2 Behaviors =head2 add_child([$options], @nodes) This will add all the C<@nodes> as children of C<$tree>. $options is a optional unblessed hashref that specifies options for C. The optional parameters are: =over 4 =item * at This specifies the index to add C<@nodes> at. If specified, this will be passed into splice(). The only exceptions are if this is 0, it will act as an unshift(). If it is unset or undefined, it will act as a push(). Lastly, if it is out of range (too negative or too big [beyond the number of children]) the child is not added, and an error msg will be available in L. =back add_child() resets last_error() upon entry. =head2 remove_child([$options], @nodes) Here, [] indicate an optional parameter. This will remove all the C<@nodes> from the children of C<$tree>. You can either pass in the actual child object you wish to remove, the index of the child you wish to remove, or a combination of both. $options is a optional unblessed hashref that specifies parameters for remove_child(). Currently, no parameters are used. remove_child() resets last_error() upon entry. =head2 mirror() This will modify the tree such that it is a mirror of what it was before. This means that the order of all children is reversed. B: This is a destructive action. It I modify the internal structure of the tree. If you wish to get a mirror, yet keep the original tree intact, use C<< my $mirror = $tree->clone->mirror >>. mirror() does not reset last_error() because it (mirror() ) is implemented in L, which has no error handling. =head2 traverse([$order]) Here, [] indicate an optional parameter. This will return a list of the nodes in the given traversal order. The default traversal order is pre-order. The various traversal orders do the following steps: =over 4 =item * Pre-order This will return the node, then the first sub tree in pre-order traversal, then the next sub tree, etc. Use C<< $tree->PRE_ORDER >> as the C<$order>. =item * Post-order This will return the each sub-tree in post-order traversal, then the node. Use C<< $tree->POST_ORDER >> as the C<$order>. =item * Level-order This will return the node, then the all children of the node, then all grandchildren of the node, etc. Use C<< $tree->LEVEL_ORDER >> as the C<$order>. =back traverse() does not reset last_error() because it (traverse() ) is implemented in L, which has no error handling. =head2 tree2string($options) Returns an arrayref of lines, suitable for printing. These lines do not end in "\n". Draws a nice ASCII-art representation of the tree structure. The tree looks like: Root. Attributes: {uid => "0"} |--- H. Attributes: {uid => "1"} | |--- I. Attributes: {uid => "2"} | | |--- J. Attributes: {uid => "3"} | |--- K. Attributes: {uid => "4"} | |--- L. Attributes: {uid => "5"} |--- M. Attributes: {uid => "6"} |--- N. Attributes: {uid => "7"} |--- O. Attributes: {uid => "8"} |--- P. Attributes: {uid => "9"} |--- Q. Attributes: {uid => "10"} Or, without attributes: Root |--- H | |--- I | | |--- J | |--- K | |--- L |--- M |--- N |--- O |--- P |--- Q See scripts/print.tree.pl. Example usage: print map("$_\n", @{$tree -> tree2string}); If you do not wish to supply options, use C or C. Possible keys in the $options hashref (which defaults to {}): =over 4 =item o no_attributes => $Boolean If 1, the node attributes are not included in the string returned. Default: 0 (include attributes). =back Calls L. =head2 State Queries =head2 is_root() This will return true if C<$tree> has no parent and false otherwise. =head2 is_leaf() This will return true if C<$tree> has no children and false otherwise. =head2 has_child(@nodes) This will return true if C<$tree> has each of the C<@nodes> as a child. Otherwise, it will return false. The test to see if a node is in the tree uses refaddr() from L, not the I of the node. This means C<@nodes> must be an array of C objects. =head2 get_index_for(@nodes) This will return the index into the children list of C<$tree> for each of the C<@nodes> passed in. =head2 Accessors =head2 parent() This will return the parent of C<$tree>. =head2 children( [ $idx, [$idx, ..] ] ) Here, [] indicate optional parameters. This will return the children of C<$tree>. If called in list context, it will return all the children. If called in scalar context, it will return the number of children. You may optionally pass in a list of indices to retrieve. This will return the children in the order you asked for them. This is very much like an arrayslice. =head2 root() This will return the root node of the tree that C<$tree> is in. The root of the root node is itself. =head2 height() This will return the height of C<$tree>. A leaf has a height of 1. A parent has a height of its tallest child, plus 1. =head2 width() This will return the width of C<$tree>. A leaf has a width of 1. A parent has a width equal to the sum of all the widths of its children. =head2 depth() This will return the depth of C<$tree>. A root has a depth of 0. A child has the depth of its parent, plus 1. This is the distance from the root. It is useful for things like pretty-printing the tree. =head2 size() This will return the number of nodes within C<$tree>. A leaf has a size of 1. A parent has a size equal to the 1 plus the sum of all the sizes of its children. =head2 value() This will return the value stored in the node. =head2 set_value([$value]) Here, [] indicate an optional parameter. This will set the I stored in the node to $value, then return $self. If C<$value> is not provided, undef is used. =head2 meta() This will return a hashref that can be used to store whatever metadata the client wishes to store. For example, L uses this to store database row ids. It is recommended that you store your metadata in a subhashref and not in the top-level metadata hashref, keyed by your package name. L does this, using a unique key for each persistence layer associated with that tree. This will help prevent clobbering of metadata. =head2 format_node($options, $node) Returns a string consisting of the node's name and, optionally, it's attributes. Possible keys in the $options hashref: =over 4 =item o no_attributes => $Boolean If 1, the node attributes are not included in the string returned. Default: 0 (include attributes). =back Calls L. Called by L. You would not normally call this method. If you do not wish to supply options, use format_node({}, $node). =head2 hashref2string($hashref) Returns the given hashref as a string. Called by L. =head2 node2string($options, $node, $vert_dashes) Returns a string of the node name and attributes, with a leading indent, suitable for printing. Possible keys in the $options hashref: =over 4 =item o no_attributes => $Boolean If 1, the node attributes are not included in the string returned. Default: 0 (include attributes). =back Ignore the parameter $vert_dashes. The code uses it as temporary storage. Calls L. Called by L. =head1 ERROR HANDLING Describe what the default error handlers do and what a custom error handler is expected to do. =head2 Error-related methods =head2 error_handler( [ $handler ] ) This will return the current error handler for the tree. If a value is passed in, then it will be used to set the error handler for the tree. If called as a class method, this will instead work with the default error handler. =head2 error( $error, [ arg1 [, arg2 ...] ] ) Call this when you wish to report an error using the currently defined error_handler for the tree. The only guaranteed parameter is an error string describing the issue. There may be other arguments, and you may certainly provide other arguments in your subclass to be passed to your custom handler. =head2 last_error() If an error occurred during the last behavior, this will return the error string. It is reset only by add_child() and remove_child(). =head2 Default error handlers =over 4 =item QUIET Use this error handler if you want to have quiet error-handling. The L method will retrieve the error from the last operation, if there was one. If an error occurs, the operation will return undefined. =item WARN =item DIE =back =head1 EVENT HANDLING Tree provides for basic event handling. You may choose to register one or more callbacks to be called when the appropriate event occurs. The events are: =over 4 =item * add_child This event will trigger as the last step in an L call. The parameters will be C<( $self, @args )> where C<@args> is the arguments passed into the add_child() call. =item * remove_child This event will trigger as the last step in an L call. The parameters will be C<( $self, @args )> where C<@args> is the arguments passed into the remove_child() call. =item * value This event will trigger as the last step in a L call. The parameters will be C<( $self, $old_value )> where C<$old_value> is what the value was before it was changed. The new value can be accessed through C<$self-Evalue()>. =back =head2 Event handling methods =head2 add_event_handler( {$type => $callback [, $type => $callback, ... ]} ) You may choose to add event handlers for any known type. Callbacks must be references to subroutines. They will be called in the order they are defined. =head2 event( $type, $actor, @args ) This will trigger an event of type C<$type>. All event handlers registered on C<$tree> will be called with parameters of C<($actor, @args)>. Then, the parent will be notified of the event and its handlers will be called, on up to the root. This allows you specify an event handler on the root and be guaranteed that it will fire every time the appropriate event occurs anywhere in the tree. =head1 NULL TREE If you call C<$self-Eparent> on a root node, it will return a Tree::Null object. This is an implementation of the Null Object pattern optimized for usage with L. It will evaluate as false in every case (using I) and all methods called on it will return a Tree::Null object. =head2 Notes =over 4 =item * Tree::Null does B inherit from Tree. This is so that all the methods will go through AUTOLOAD vs. the actual method. =item * However, calling isa() on a Tree::Null object will report that it is-a any object that is either Tree or in the Tree:: hierarchy. =item * The Tree::Null object is a singleton. =item * The Tree::Null object I defined, though. I could not find a way to make it evaluate as undefined. That may be a good thing. =back =head1 CIRCULAR REFERENCES Please q.v. L for more info on this topic. =head1 FAQ =head2 Which is the best tree processing module? L. More details: L. =head2 How do I implement the visitor pattern? I have deliberately chosen to not implement the Visitor pattern as described by Gamma et al. Given a sufficiently powerful C and the capabilities of Perl, an explicit visitor object is almost always unneeded. If you want one, it is easy to write one yourself. Here is a simple one I wrote in 5 minutes: package My::Visitor; sub new { my $class = shift; my $opts = @_; return bless { tree => $opts->{tree}, action => $opts->{action}, }, $class; } sub visit { my $self = shift; my ($mode) = @_; foreach my $node ( $self->{tree}->traverse( $mode ) ) { $self->{action}->( $node ); } } =head2 Should I implement the visitor pattern? No. You are better off using the L method. =head1 SEE ALSO =over 4 =item o L Lightweight. =item o L Lightweight, and with a long list of methods. =item o L Lightweight. =item o L Lightweight. =item o L Uses L. =back C itself is also lightweight. =head1 CODE COVERAGE These statistics are as of V 1.01. We use L to test the code coverage of our tests. Below is the L report on this module's test suite. ---------------------------- ------ ------ ------ ------ ------ ------ ------ File stmt bran cond sub pod time total ---------------------------- ------ ------ ------ ------ ------ ------ ------ blib/lib/Tree.pm 100.0 100.0 94.4 100.0 100.0 67.3 99.7 blib/lib/Tree/Binary.pm 96.4 95.0 100.0 100.0 100.0 10.7 96.7 blib/lib/Tree/Fast.pm 99.4 95.5 91.7 100.0 100.0 22.0 98.6 Total 98.9 96.8 94.9 100.0 100.0 100.0 98.5 ---------------------------- ------ ------ ------ ------ ------ ------ ------ =head1 ACKNOWLEDGEMENTS =over 4 =item * Stevan Little for writing L, upon which Tree is based. =back =head1 Repository L =head1 SUPPORT The mailing list is at L. I also read L on a daily basis. =head1 AUTHORS Rob Kinyon Erob.kinyon@iinteractive.comE Stevan Little Estevan.little@iinteractive.comE Thanks to Infinity Interactive for generously donating our time. Co-maintenance since V 1.02 is by Ron Savage . Uses of 'I' in previous versions is not me, but will be hereafter. =head1 COPYRIGHT AND LICENSE Copyright 2004, 2005 by Infinity Interactive, Inc. L This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut Tree-1.07/lib/Tree000755001750001750 012453731754 12577 5ustar00ronron000000000000Tree-1.07/lib/Tree/Fast.pm000444001750001750 3211712453731754 14213 0ustar00ronron000000000000package Tree::Fast; use 5.006; use strict; use warnings FATAL => 'all'; our $VERSION = '1.07'; use Scalar::Util qw( blessed weaken ); sub new { my $class = shift; return $class->clone( @_ ) if blessed $class; my $self = bless {}, $class; $self->_init( @_ ); return $self; } sub _init { my $self = shift; my ($value) = @_; $self->{_parent} = $self->_null, $self->{_children} = []; $self->{_value} = $value, $self->{_meta} = {}; return $self; } sub _clone_self { my $self = shift; my $value = @_ ? shift : $self->value; my $clone = blessed($self)->new( $value ); return blessed($self)->new( $value ); } sub _clone_children { my ($self, $clone) = @_; if ( my @children = @{$self->{_children}} ) { $clone->add_child({}, map { $_->clone } @children ); } } sub clone { my $self = shift; return $self->new(@_) unless blessed $self; my $clone = $self->_clone_self(@_); $self->_clone_children($clone); return $clone; } sub add_child { my $self = shift; my ( $options, @nodes ) = @_; for my $node ( @nodes ) { $node->_set_parent( $self ); } if ( defined $options->{at} ) { if ( $options->{at} ) { splice @{$self->{_children}}, $options->{at}, 0, @nodes; } else { unshift @{$self->{_children}}, @nodes; } } else { push @{$self->{_children}}, @nodes; } return $self; } sub remove_child { my $self = shift; my ($options, @indices) = @_; my @return; for my $idx (sort { $b <=> $a } @indices) { my $node = splice @{$self->{_children}}, $idx, 1; $node->_set_parent( $node->_null ); push @return, $node; } return @return; } sub parent { my $self = shift; return $self->{_parent}; } sub _set_parent { my $self = shift; $self->{_parent} = shift; weaken( $self->{_parent} ); return $self; } sub children { my $self = shift; if ( @_ ) { my @idx = @_; return @{$self->{_children}}[@idx]; } else { if ( caller->isa( __PACKAGE__ ) || $self->isa( scalar(caller) ) ) { return wantarray ? @{$self->{_children}} : $self->{_children}; } else { return @{$self->{_children}}; } } } sub value { my $self = shift; my $value = shift; $self->{_value} = $value if (defined $value); return $self->{_value}; } sub set_value { my $self = shift; $self->{_value} = $_[0]; return $self; } sub meta { my $self = shift; my $meta = shift; $self->{_meta} = {%{$self->{_meta} }, %$meta} if ($meta && !blessed($meta) && ref($meta) eq 'HASH'); return $self->{_meta}; } sub mirror { my $self = shift; @{$self->{_children}} = reverse @{$self->{_children}}; $_->mirror for @{$self->{_children}}; return $self; } use constant PRE_ORDER => 1; use constant POST_ORDER => 2; use constant LEVEL_ORDER => 3; sub traverse { my $self = shift; my $order = shift; $order = $self->PRE_ORDER unless $order; if ( wantarray ) { my @list; if ( $order eq $self->PRE_ORDER ) { @list = ($self); push @list, map { $_->traverse( $order ) } @{$self->{_children}}; } elsif ( $order eq $self->POST_ORDER ) { @list = map { $_->traverse( $order ) } @{$self->{_children}}; push @list, $self; } elsif ( $order eq $self->LEVEL_ORDER ) { my @queue = ($self); while ( my $node = shift @queue ) { push @list, $node; push @queue, @{$node->{_children}}; } } else { return $self->error( "traverse(): '$order' is an illegal traversal order" ); } return @list; } else { my $closure; if ( $order eq $self->PRE_ORDER ) { my $next_node = $self; my @stack = ( $self ); my @next_idx = ( 0 ); $closure = sub { my $node = $next_node; return unless $node; $next_node = undef; while ( @stack && !$next_node ) { while ( @stack && !exists $stack[0]->{_children}[ $next_idx[0] ] ) { shift @stack; shift @next_idx; } if ( @stack ) { $next_node = $stack[0]->{_children}[ $next_idx[0]++ ]; unshift @stack, $next_node; unshift @next_idx, 0; } } return $node; }; } elsif ( $order eq $self->POST_ORDER ) { my @stack = ( $self ); my @next_idx = ( 0 ); while ( @{ $stack[0]->{_children} } ) { unshift @stack, $stack[0]->{_children}[0]; unshift @next_idx, 0; } $closure = sub { my $node = $stack[0]; return unless $node; shift @stack; shift @next_idx; $next_idx[0]++; while ( @stack && exists $stack[0]->{_children}[ $next_idx[0] ] ) { unshift @stack, $stack[0]->{_children}[ $next_idx[0] ]; unshift @next_idx, 0; } return $node; }; } elsif ( $order eq $self->LEVEL_ORDER ) { my @nodes = ($self); $closure = sub { my $node = shift @nodes; return unless $node; push @nodes, @{$node->{_children}}; return $node; }; } else { return $self->error( "traverse(): '$order' is an illegal traversal order" ); } return $closure; } } sub _null { return Tree::Null->new; } package Tree::Null; our $VERSION = '1.07'; #XXX Add this in once it's been thought out #our @ISA = qw( Tree ); # You want to be able to interrogate the null object as to # its class, so we don't override isa() as we do can() use overload '""' => sub { return "" }, '0+' => sub { return 0 }, 'bool' => sub { return }, fallback => 1, ; { my $singleton = bless \my($x), __PACKAGE__; sub new { return $singleton } sub AUTOLOAD { return $singleton } sub can { return sub { return $singleton } } } # The null object can do anything sub isa { my ($proto, $class) = @_; if ( $class =~ /^Tree(?:::.*)?$/ ) { return 1; } return $proto->SUPER::isa( $class ); } 1; __END__ =head1 NAME Tree::Fast - the fastest possible implementation of a tree in pure Perl =head1 SYNOPSIS my $tree = Tree::Fast->new( 'root' ); my $child = Tree::Fast->new( 'child' ); $tree->add_child( {}, $child ); $tree->add_child( { at => 0 }, Tree::Fast->new( 'first child' ) ); $tree->add_child( { at => -1 }, Tree::Fast->new( 'last child' ) ); my @children = $tree->children; my @some_children = $tree->children( 0, 2 ); $tree->remove_child( 0 ); my @nodes = $tree->traverse( $tree->POST_ORDER ); my $traversal = $tree->traverse( $tree->POST_ORDER ); while ( my $node = $traversal->() ) { # Do something with $node here } my $clone = $tree->clone; my $mirror = $tree->clone->mirror; =head1 DESCRIPTION This is meant to be the core implementation for L, stripped down as much as possible. There is no error-checking, bounds-checking, event-handling, convenience methods, or anything else of the sort. If you want something fuller-featured, please look at L, which is a wrapper around Tree::Fast. =head1 METHODS =head2 Constructors =head2 new([$value]) Here, [] indicate an optional parameter. This will return a C object. It will accept one parameter which, if passed, will become the I (accessible by C). All other parameters will be ignored. If you call C<< $tree->new([$value]) >>, it will instead call C, then set the I of the clone to $value. =head2 clone() This will return a clone of C<$tree>. The clone will be a root tree, but all children will be cloned. If you call C<< Tree::Fast->clone([$value]) >>, it will instead call C. B the value is merely a shallow copy. This means that all references will be kept. =head2 Behaviors =head2 add_child($options, @nodes) This will add all the C<@nodes> as children of C<$tree>. C<$options> is a required hashref that specifies options for C. The optional parameters are: =over 4 =item * at This specifies the index to add C<@nodes> at. If specified, this will be passed into splice(). The only exceptions are if this is 0, it will act as an unshift(). If it is unset or undefined, it will act as a push(). =back =head2 remove_child($options, @nodes) This will remove all the C<@nodes> from the children of C<$tree>. You can either pass in the actual child object you wish to remove, the index of the child you wish to remove, or a combination of both. $options is a required hashref that specifies parameters for remove_child(). Currently, no parameters are used. =head2 mirror() This will modify the tree such that it is a mirror of what it was before. This means that the order of all children is reversed. B: This is a destructive action. It I modify the tree's internal structure. If you wish to get a mirror, yet keep the original tree intact, use C<< my $mirror = $tree->clone->mirror >>. =head2 traverse( [$order] ) Here, [] indicate an optional parameter. When called in list context (C<< my @traversal = $tree->traverse() >>), this will return a list of the nodes in the given traversal order. When called in scalar context (C<< my $traversal = $tree->traverse() >>), this will return a closure that will, over successive calls, iterate over the nodes in the given traversal order. When finished it will return false. The default traversal order is pre-order. The various traversal orders do the following steps: =over 4 =item * Pre-order This will return the node, then the first sub tree in pre-order traversal, then the next sub tree, etc. Use C<< $tree->PRE_ORDER >> as the C<$order>. =item * Post-order This will return the each sub-tree in post-order traversal, then the node. Use C<< $tree->POST_ORDER >> as the C<$order>. =item * Level-order This will return the node, then the all children of the node, then all grandchildren of the node, etc. Use C<< $tree->LEVEL_ORDER >> as the C<$order>. =back =head2 Accessors =head2 parent() This will return the parent of C<$tree>. =head2 children( [ $idx, [$idx, ..] ] ) Here, [] indicate optional parameters. This will return the children of C<$tree>. If called in list context, it will return all the children. If called in scalar context, it will return the number of children. You may optionally pass in a list of indices to retrieve. This will return the children in the order you asked for them. This is very much like an arrayslice. =head2 value() This will return the value stored in the node. =head2 set_value([$value]) Here, [] indicate an optional parameter. This will set the I stored in the node to $value, then return $self. If C<$value> is not provided, undef is used. =head2 meta() This will return a hashref that can be used to store whatever metadata the client wishes to store. For example, L uses this to store database row ids. It is recommended that you store your metadata in a subhashref and not in the top-level metadata hashref, keyed by your package name. L does this, using a unique key for each persistence layer associated with that tree. This will help prevent clobbering of metadata. =head1 NULL TREE If you call C<< $self->parent >> on a root node, it will return a Tree::Null object. This is an implementation of the Null Object pattern optimized for usage with L. It will evaluate as false in every case (using I) and all methods called on it will return a Tree::Null object. =head2 Notes =over 4 =item * Tree::Null does B inherit from anything. This is so that all the methods will go through AUTOLOAD vs. the actual method. =item * However, calling isa() on a Tree::Null object will report that it is-a any object that is either Tree or in the Tree:: hierarchy. =item * The Tree::Null object is a singleton. =item * The Tree::Null object I defined, though. I couldn't find a way to make it evaluate as undefined. That may be a good thing. =back =head1 CODE COVERAGE Please see the relevant sections of L. =head1 SUPPORT Please see the relevant sections of L. =head1 ACKNOWLEDGEMENTS =over 4 =item * Stevan Little for writing L, upon which Tree is based. =back =head1 AUTHORS Rob Kinyon Erob.kinyon@iinteractive.comE Stevan Little Estevan.little@iinteractive.comE Thanks to Infinity Interactive for generously donating our time. =head1 COPYRIGHT AND LICENSE Copyright 2004, 2005 by Infinity Interactive, Inc. L This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut Tree-1.07/lib/Tree/Binary2.pm000444001750001750 2076012453731754 14625 0ustar00ronron000000000000package Tree::Binary2; use 5.006; use strict; use warnings FATAL => 'all'; use Scalar::Util qw( blessed ); use base qw( Tree ); our $VERSION = '1.07'; sub _init { my $self = shift; $self->SUPER::_init( @_ ); # Make this class a complete binary tree, # filling in with Tree::Null as appropriate. $self->{_children}->[$_] = $self->_null for 0 .. 1; return $self; } sub left { my $self = shift; return $self->_set_get_child( 0, @_ ); } sub right { my $self = shift; return $self->_set_get_child( 1, @_ ); } sub _set_get_child { my $self = shift; my $index = shift; if ( @_ ) { my $node = shift; $node = $self->_null unless $node; my $old = $self->children->[$index]; $self->children->[$index] = $node; if ( $node ) { $node->_set_parent( $self ); $node->_set_root( $self->root ); $node->_fix_depth; } if ( $old ) { $old->_set_parent( $old->_null ); $old->_set_root( $old->_null ); $old->_fix_depth; } $self->_fix_height; $self->_fix_width; return $self; } else { return $self->children->[$index]; } } sub _clone_children { my ($self, $clone) = @_; @{ $clone->{_children} } = (); $clone->add_child({}, map { $_->clone } @{ $self->{_children} }); } sub children { my $self = shift; if ( @_ ) { my @idx = @_; return @{$self->{_children}}[@idx]; } else { if ( caller->isa( __PACKAGE__ ) || $self->isa( scalar(caller) ) ) { return wantarray ? @{$self->{_children}} : $self->{_children}; } else { return grep { $_ } @{$self->{_children}}; } } } use constant IN_ORDER => 4; # One of the things we have to do in a traversal is to remove all of the # Tree::Null elements that are appended to the tree to make this a complete # binary tree. The user isn't going to expect them, because they're an # internal nicety. sub traverse { my $self = shift; my $order = shift; $order = $self->PRE_ORDER unless $order; if ( wantarray ) { if ( $order == $self->IN_ORDER ) { return grep { $_ } ( $self->left->traverse( $order ), $self, $self->right->traverse( $order ), ); } else { return grep { $_ } $self->SUPER::traverse( $order ); } } else { my $closure; if ( $order eq $self->IN_ORDER ) { my @list = $self->traverse( $order ); $closure = sub { return unless @list; return shift @list; }; } elsif ( $order eq $self->PRE_ORDER ) { my $next_node = $self; my @stack = ( $self ); my @next_meth = ( 0 ); my @meths = qw( left right ); $closure = sub { my $node = $next_node; return unless $node; $next_node = undef; while ( @stack && !$next_node ) { while ( @next_meth && $next_meth[0] == 2 ) { shift @stack; shift @next_meth; } if ( @stack ) { my $meth = $meths[ $next_meth[0]++ ]; $next_node = $stack[0]->$meth; next unless $next_node; unshift @stack, $next_node; unshift @next_meth, 0; } } return $node; }; } elsif ( $order eq $self->POST_ORDER ) { my @list = $self->traverse( $order ); $closure = sub { return unless @list; return shift @list; }; #my @stack = ( $self ); #my @next_idx = ( 0 ); #while ( @{ $stack[0]->{_children} } ) { # unshift @stack, $stack[0]->{_children}[0]; # unshift @next_idx, 0; #} # #$closure = sub { # my $node = $stack[0] || return; # # shift @stack; shift @next_idx; # $next_idx[0]++; # # while ( @stack && exists $stack[0]->{_children}[ $next_idx[0] ] ) { # unshift @stack, $stack[0]->{_children}[ $next_idx[0] ]; # unshift @next_idx, 0; # } # # return $node; #}; } elsif ( $order eq $self->LEVEL_ORDER ) { my @nodes = ($self); $closure = sub { my $node = shift @nodes; return unless $node; push @nodes, grep { $_ } @{$node->{_children}}; return $node; }; } else { return $self->error( "traverse(): '$order' is an illegal traversal order" ); } return $closure; } } 1; __END__ =head1 NAME Tree::Binary2 - An implementation of a binary tree =head1 SYNOPSIS my $tree = Tree::Binary2->new( 'root' ); my $left = Tree::Binary2->new( 'left' ); $tree->left( $left ); my $right = Tree::Binary2->new( 'left' ); $tree->right( $right ); my $right_child = $tree->right; $tree->right( undef ); # Unset the right child. my @nodes = $tree->traverse( $tree->POST_ORDER ); my $traversal = $tree->traverse( $tree->IN_ORDER ); while ( my $node = $traversal->() ) { # Do something with $node here } =head1 DESCRIPTION This is an implementation of a binary tree. This class inherits from L, which is an N-ary tree implemenation. Because of this, this class actually provides an implementation of a complete binary tree vs. a sparse binary tree. The empty nodes are instances of Tree::Null, which is described in L. This should have no effect on your usage of this class. =head1 METHODS In addition to the methods provided by L, the following items are provided or overriden. =over 4 =item * C / C These access the left and right children, respectively. They are mutators, which means that their behavior changes depending on if you pass in a value. If you do not pass in any parameters, then it will act as a getter for the specific child, return the child (if set) or undef (if not). If you pass in a child, it will act as a setter for the specific child, setting the child to the passed-in value and returning the $tree. (Thus, this method chains.) If you wish to unset the child, do C<$treeEleft( undef );> =item * C This will return the children of the tree. B There will be two children, always. Tree::Binary2 implements a complete binary tree, filling in missing children with Tree::Null objects. (Please see L for more information on Tree::Null.) =item * B When called in list context (Ctraverse()>), this will return a list of the nodes in the given traversal order. When called in scalar context (Ctraverse()>), this will return a closure that will, over successive calls, iterate over the nodes in the given traversal order. When finished it will return false. The default traversal order is pre-order. In addition to the traversal orders provided by L, Tree::Binary2 provides in-order traversals. =over 4 =item * In-order This will return the result of an in-order traversal on the left node (if any), then the node, then the result of an in-order traversal on the right node (if any). =back =back B You have access to all the methods provided by L, but it is not recommended that you use many of them, unless you know what you're doing. This list includes C and C. =head1 TODO =over 4 =item * Make in-order closure traversal work iteratively =item * Make post-order closure traversal work iteratively =back =head1 CODE COVERAGE Please see the relevant sections of L. =head1 SUPPORT Please see the relevant sections of L. =head1 AUTHORS Rob Kinyon Erob.kinyon@iinteractive.comE Stevan Little Estevan.little@iinteractive.comE Thanks to Infinity Interactive for generously donating our time. =head1 COPYRIGHT AND LICENSE Copyright 2004, 2005 by Infinity Interactive, Inc. L This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut Tree-1.07/t000755001750001750 012453731754 11375 5ustar00ronron000000000000Tree-1.07/t/pod_coverage.t000444001750001750 33112453731754 14331 0ustar00ronron000000000000use strict; use warnings; use Test::More; eval "use Test::Pod::Coverage 1.08"; plan skip_all => "Test::Pod::Coverage 1.08 required for testing POD coverage" if $@; all_pod_coverage_ok({ also_private => [], }); Tree-1.07/t/pod.t000444001750001750 23612453731754 12462 0ustar00ronron000000000000use strict; use warnings; use Test::More; eval "use Test::Pod 1.45"; plan skip_all => "Test::Pod 1.45 required for testing POD" if $@; all_pod_files_ok(); Tree-1.07/t/Tree_Binary000755001750001750 012453731754 13600 5ustar00ronron000000000000Tree-1.07/t/Tree_Binary/001_mirror.t000444001750001750 1213212453731754 16033 0ustar00ronron000000000000use strict; use warnings; use Test::More; plan tests => 16; my $CLASS = 'Tree::Binary2'; use_ok( $CLASS ) or Test::More->builder->BAILOUT( "Cannot load $CLASS" ); my $c; my @order; sub convert { my $c = shift; my @l; while ( my $n = $c->() ) { push @l, $n; } return @l; } { my $tree = $CLASS->new( 'A' ) ->left( $CLASS->new( 'B' ) ->left( $CLASS->new( 'C' ) ) ->right( $CLASS->new( 'D' ) ) ) ->right( $CLASS->new( 'E' ) ->left( $CLASS->new( 'F' ) ) ->right( $CLASS->new( 'G' ) ) ) ; @order = $tree->traverse( $tree->IN_ORDER ); is_deeply( [ map { $_->value } @order ], [ qw( C B D A F E G ) ], "The tree's ordering for in-order traversal is correct", ); is_deeply( [ map { $_->value } $tree->traverse() ], [ qw( A B C D E F G ) ], "pre-order traversal works correctly", ); @order = convert( $c = $tree->traverse() ); is_deeply( [ map { $_->value } @order ], [ qw( A B C D E F G ) ], "pre-order traversal works correctly", ); @order = map { $_ -> value } convert( $c = $tree->traverse( $tree->PRE_ORDER ) ); is_deeply( [ @order ], [ qw( A B C D E F G ) ], "pre-order traversal works correctly", ); @order = convert( $c = $tree->traverse( $tree->IN_ORDER ) ); is_deeply( [ map { $_->value } @order ], [ qw( C B D A F E G ) ], "The tree's ordering for in-order traversal is correct", ); @order = map { $_->value } convert( $c = $tree->traverse( $tree->POST_ORDER ) ); is_deeply( [ @order ], [ qw( C D B F G E A ) ], "post-order traversal works correctly", ); @order = convert( $c = $tree->traverse( $tree->LEVEL_ORDER ) ); is_deeply( [ map { $_->value } @order ], [ qw( A B E C D F G ) ], "level-order traversal works correctly", ); my $mirror = $tree->clone->mirror; my @clone_order = $mirror->traverse( $mirror->IN_ORDER ); is_deeply( [ map { $_->value } @clone_order ], [ qw( G E F A D B C ) ], "The mirror's ordering for in-order traversal is correct", ); } { my $tree = $CLASS->new(4) ->left( $CLASS->new(20) ->left( $CLASS->new(1) ->right( $CLASS->new(10) ->left($CLASS->new(5)) ) ) ->right( $CLASS->new(3) ) ) ->right( $CLASS->new(6) ->left( $CLASS->new(5) ->right( $CLASS->new(7) ->left( $CLASS->new(90) ) ->right( $CLASS->new(91) ) ) ) ) ; my @results = map { $_->value } $tree->traverse( $tree->IN_ORDER ); is_deeply( [ @results ], [ 1, 5, 10, 20, 3, 4, 5, 90, 7, 91, 6 ], "The tree's ordering for in-order traversal is correct", ); my $mirror = $tree->clone->mirror; my @m_results = map { $_->value } $mirror->traverse( $mirror->IN_ORDER ); is_deeply( [ @m_results ], [ reverse @results ], "... the in-order traversal of the mirror is the reverse of the in-order traversal of the original tree", ); @order = map { $_->value } convert( $c = $tree->traverse() ); is_deeply( [ @order ], [ 4, 20, 1, 10, 5, 3, 6, 5, 7, 90, 91 ], "pre-order traversal works correctly", ); @order = convert( $c = $tree->traverse( $tree->PRE_ORDER ) ); is_deeply( [ map { $_->value } @order ], [ 4, 20, 1, 10, 5, 3, 6, 5, 7, 90, 91 ], "pre-order traversal works correctly", ); @order = map { $_->value } convert( $c = $tree->traverse( $tree->IN_ORDER ) ); is_deeply( [ @order ], [ 1, 5, 10, 20, 3, 4, 5, 90, 7, 91, 6 ], "The tree's ordering for in-order traversal is correct", ); @order = convert( $c = $tree->traverse( $tree->POST_ORDER ) ); is_deeply( [ map { $_->value } @order ], [ 5, 10, 1, 3, 20, 90, 91, 7, 5, 6, 4 ], "post-order traversal works correctly", ); @order = convert( $c = $tree->traverse( $tree->LEVEL_ORDER ) ); is_deeply( [ map { $_->value } @order ], [ 4, 20, 6, 1, 3, 5, 10, 7, 5, 90, 91 ], "level-order traversal works correctly", ); } Tree-1.07/t/Tree_Binary/000_binary_trees.t000444001750001750 723012453731754 17171 0ustar00ronron000000000000use lib 't/lib'; use strict; use warnings; use Test::More; use Tests qw( %runs ); plan tests => 28 + 15 * $runs{stats}{plan}; my $CLASS = 'Tree::Binary2'; use_ok( $CLASS ) or Test::More->builder->BAILOUT( "Cannot load $CLASS" ); my $root = $CLASS->new( 'root' ); isa_ok( $root, $CLASS ); isa_ok( $root, 'Tree' ); is( $root->root, $root, "The root's root is itself" ); is( $root->value, 'root', "value() works" ); $runs{stats}{func}->( $root, height => 1, width => 1, depth => 0, size => 1, is_root => 1, is_leaf => 1, ); can_ok( $root, qw( left right ) ); my $left = $CLASS->new( 'left' ); $runs{stats}{func}->( $left, height => 1, width => 1, depth => 0, size => 1, is_root => 1, is_leaf => 1, ); is( $root->left(), '', "Calling left with no params is a getter" ); is( $root->left( $left ), $root, "Calling left as a setter chains" ); is( $root->left(), $left, "... and set the left" ); cmp_ok( $root->children, '==', 1, "children() works" ); ok( $root->has_child( $left ), "has_child(BOOL) works on left" ); is_deeply( [ $root->get_index_for( $left ) ], [ 0 ], "get_index_for works on left" ); $runs{stats}{func}->( $root, height => 2, width => 1, depth => 0, size => 2, is_root => 1, is_leaf => 0, ); $runs{stats}{func}->( $left, height => 1, width => 1, depth => 1, size => 1, is_root => 0, is_leaf => 1, ); is( $root->left( undef ), $root, "Calling left with undef as a param" ); is( $root->left(), '', "... unsets left" ); cmp_ok( $root->children, '==', 0, "children() works" ); $runs{stats}{func}->( $root, height => 1, width => 1, depth => 0, size => 1, is_root => 1, is_leaf => 1, ); $runs{stats}{func}->( $left, height => 1, width => 1, depth => 0, size => 1, is_root => 1, is_leaf => 1, ); my $right = $CLASS->new( 'right' ); $runs{stats}{func}->( $right, height => 1, width => 1, depth => 0, size => 1, is_root => 1, is_leaf => 1, ); is( $root->right(), '', "Calling right with no params is a getter" ); is( $root->right( $right ), $root, "Calling right as a setter chains" ); is( $root->right(), $right, "... and set the right" ); cmp_ok( $root->children, '==', 1, "children() works" ); ok( $root->has_child( $right ), "has_child(BOOL) works on right" ); is_deeply( [ $root->get_index_for( $right ) ], [ 1 ], "get_index_for works on right" ); $runs{stats}{func}->( $root, height => 2, width => 1, depth => 0, size => 2, is_root => 1, is_leaf => 0, ); $runs{stats}{func}->( $right, height => 1, width => 1, depth => 1, size => 1, is_root => 0, is_leaf => 1, ); is( $root->right( undef ), $root, "Calling right with undef as a param" ); is( $root->right(), '', "... unsets right" ); cmp_ok( $root->children, '==', 0, "children() works" ); $runs{stats}{func}->( $root, height => 1, width => 1, depth => 0, size => 1, is_root => 1, is_leaf => 1, ); $runs{stats}{func}->( $right, height => 1, width => 1, depth => 0, size => 1, is_root => 1, is_leaf => 1, ); $root->left( $left ); $root->right( $right ); cmp_ok( $root->children, '==', 2, "children() works" ); ok( $root->has_child( $left ), "has_child(BOOL) works on right" ); ok( $root->has_child( $right ), "has_child(BOOL) works on right" ); ok( $root->has_child( $left, $right ), "has_child(SCALAR) works on right" ); $runs{stats}{func}->( $root, height => 2, width => 2, depth => 0, size => 3, is_root => 1, is_leaf => 0, ); $runs{stats}{func}->( $left, height => 1, width => 1, depth => 1, size => 1, is_root => 0, is_leaf => 1,); $runs{stats}{func}->( $right, height => 1, width => 1, depth => 1, size => 1, is_root => 0, is_leaf => 1, ); my $right2 = $right->clone; $runs{stats}{func}->( $right2, height => 1, width => 1, depth => 0, size => 1, is_root => 1, is_leaf => 1, ); Tree-1.07/t/Tree_Binary/002_clone.t000444001750001750 150112453731754 15600 0ustar00ronron000000000000# This test and corresponding fix was submitted by HDP to fix RT #16889 use 5.006; use strict; use warnings FATAL => 'all'; use Test::More tests => 6; use_ok( 'Tree::Binary2' ); my $tree = Tree::Binary2->new('root'); $tree->left(Tree::Binary2->new('left')); $tree->right(Tree::Binary2->new('right')); my $clone = $tree->clone; use Data::Dumper; is($clone->left->value, $tree->left->value, "clone has same value as original") or diag Dumper($clone, $tree); is( scalar @{ $tree->{_children} }, 2, "original tree still has 2 children", ); is( scalar @{ $clone->{_children} }, 2, "clone also has 2 children", ); is( $clone->left->parent, $clone, "left child of clone has correct parent", ); is( $clone->right->parent, $clone, "right child of clone has correct parent", ); __END__ Tree-1.07/t/Tree000755001750001750 012453731754 12274 5ustar00ronron000000000000Tree-1.07/t/Tree/007_add_child.t000444001750001750 1167512453731754 15131 0ustar00ronron000000000000use strict; use warnings; use Test::More tests => 61; my $CLASS = 'Tree'; use_ok( $CLASS ) or Test::More->builder->BAILOUT( "Cannot load $CLASS" ); # Test Plan: # 1) Add children to a root node to make a 2-level tree, using add_child() in various # configurations # 2) Verify that the children are in the correct order # 3) Remove children using remove_child() in various configurations # 4) Verify that the children are in the correct order my $root = $CLASS->new; my @children = map { $CLASS->new } 1 .. 10; $root->add_child( $children[0] ); cmp_ok( $root->children, '==', 1, "There is one child" ); $root->add_child( { at => 0 }, $children[1] ); cmp_ok( $root->children, '==', 2, "There are now two children" ); is( $root->children(0), $children[1], "First child correct" ); is( $root->children(1), $children[0], "Second child correct" ); $root->add_child( { at => 1 }, $children[2], $children[3] ); cmp_ok( $root->children, '==', 4, "There are now four children" ); is( $root->children(0), $children[1], "First child correct" ); is( $root->children(1), $children[2], "Second child correct" ); is( $root->children(2), $children[3], "Third child correct" ); is( $root->children(3), $children[0], "Fourth child correct" ); $root->add_child( { at => 3 }, $children[4] ); cmp_ok( $root->children, '==', 5, "There are now five children" ); is( $root->children(0), $children[1], "First child correct" ); is( $root->children(1), $children[2], "Second child correct" ); is( $root->children(2), $children[3], "Third child correct" ); is( $root->children(3), $children[4], "Fourth child correct" ); is( $root->children(4), $children[0], "Fifth child correct" ); $root->add_child( { at => 3 }, @children[5,6] ); cmp_ok( $root->children, '==', 7, "There are now seven children" ); is( $root->children(0), $children[1], "First child correct" ); is( $root->children(1), $children[2], "Second child correct" ); is( $root->children(2), $children[3], "Third child correct" ); is( $root->children(3), $children[5], "Fourth child correct" ); is( $root->children(4), $children[6], "Fifth child correct" ); is( $root->children(5), $children[4], "Sixth child correct" ); is( $root->children(6), $children[0], "Seventh child correct" ); $root->remove_child( 2 ); cmp_ok( $root->children, '==', 6, "There are now six children" ); is( $root->children(0), $children[1], "First child correct" ); is( $root->children(1), $children[2], "Second child correct" ); is( $root->children(2), $children[5], "Third child correct" ); is( $root->children(3), $children[6], "Fourth child correct" ); is( $root->children(4), $children[4], "Fifth child correct" ); is( $root->children(5), $children[0], "Sixth child correct" ); $root->remove_child( 2, 4 ); cmp_ok( $root->children, '==', 4, "There are now four children" ); is( $root->children(0), $children[1], "First child correct" ); is( $root->children(1), $children[2], "Second child correct" ); is( $root->children(2), $children[6], "Third child correct" ); is( $root->children(3), $children[0], "Fourth child correct" ); $root->remove_child( 2, $children[1] ); cmp_ok( $root->children, '==', 2, "There are now two children" ); is( $root->children(0), $children[2], "First child correct" ); is( $root->children(1), $children[0], "Second child correct" ); $root->add_child( { at => -1 }, $children[1] ); cmp_ok( $root->children, '==', 3, "There are now three children" ); is( $root->children(0), $children[2], "First child correct" ); is( $root->children(1), $children[1], "Second child correct" ); is( $root->children(2), $children[0], "Third child correct" ); $root->add_child( { at => undef }, $children[3] ); cmp_ok( $root->children, '==', 4, "There are now four children" ); is( $root->children(0), $children[2], "First child correct" ); is( $root->children(1), $children[1], "Second child correct" ); is( $root->children(2), $children[0], "Third child correct" ); is( $root->children(3), $children[3], "Fourth child correct" ); $root->remove_child( 0 ); cmp_ok( $root->children, '==', 3, "There are now three children" ); is( $root->children(0), $children[1], "First child correct" ); is( $root->children(1), $children[0], "Second child correct" ); is( $root->children(2), $children[3], "Third child correct" ); $children[6]->add_child( $children[7] ); cmp_ok( $children[6]->children, '==', 1, "There are now one children" ); is( $children[6]->children(0), $children[7], "First child correct" ); $children[6]->add_child( { at => -1 }, $children[8] ); cmp_ok( $children[6]->children, '==', 2, "There are now two children" ); is( $children[6]->children(0), $children[8], "First child correct" ); is( $children[6]->children(1), $children[7], "Second child correct" ); $children[6]->add_child( { at => -2 }, $children[9] ); cmp_ok( $children[6]->children, '==', 3, "There are now three children" ); is( $children[6]->children(0), $children[9], "First child correct" ); is( $children[6]->children(1), $children[8], "Second child correct" ); is( $children[6]->children(2), $children[7], "Third child correct" ); Tree-1.07/t/Tree/010_errors_addchild.t000444001750001750 413312453731754 16327 0ustar00ronron000000000000use lib 't/lib'; use strict; use warnings; use Test::More; use Tests qw( %runs ); plan tests => 1 + 12 * $runs{error}{plan}; my $CLASS = 'Tree'; use_ok( $CLASS ) or Test::More->builder->BAILOUT( "Cannot load $CLASS" ); my $root = $CLASS->new; my $child1 = $CLASS->new; my $child2 = $CLASS->new; my $bad_node = bless({},'Not::A::Tree' ); my $bad_node2 = bless({},'Really::Not::A::Tree' ); my %defaults = ( func => 'add_child', validator => 'children', value => 0, ); $runs{error}{func}->( $root, %defaults, args => [], error => "add_child(): No children passed in", ); $runs{error}{func}->( $root, %defaults, args => ['not_a_child'], error => "add_child(): 'not_a_child' is not a Tree", ); $runs{error}{func}->( $root, %defaults, args => [ $bad_node ], error => "add_child(): '$bad_node' is not a Tree", ); $runs{error}{func}->( $root, %defaults, args => [ $bad_node, $bad_node2 ], error => "add_child(): '$bad_node' is not a Tree", ); $runs{error}{func}->( $root, %defaults, args => [ $child1, $bad_node2 ], error => "add_child(): '$bad_node2' is not a Tree", ); $runs{error}{func}->( $root, %defaults, args => [ { at => $child1 }, $bad_node2 ], error => "add_child(): '$child1' is not a legal index", ); $runs{error}{func}->( $root, %defaults, args => [ { at => $bad_node2 }, $child1 ], error => "add_child(): '$bad_node2' is not a legal index", ); $runs{error}{func}->( $root, %defaults, args => [ { at => 1 }, $child1 ], error => "add_child(): '1' is out-of-bounds", ); $runs{error}{func}->( $root, %defaults, args => [ { at => -1 }, $child1 ], error => "add_child(): '-1' is out-of-bounds", ); $runs{error}{func}->( $root, %defaults, args => [ $root ], error => "add_child(): Cannot add a node in the tree back into the tree", ); $child1->add_child( $child2 ); $runs{error}{func}->( $root, %defaults, args => [ $child2 ], error => "add_child(): Cannot add a child to another parent", ); $runs{error}{func}->( $child1, %defaults, args => [ $child2 ], error => "add_child(): Cannot add a node in the tree back into the tree", value => 1, ); Tree-1.07/t/Tree/017_traverse_scalar.t000444001750001750 1375112453731754 16414 0ustar00ronron000000000000use strict; use warnings; use Test::More tests => 35; my $CLASS = 'Tree'; use_ok( $CLASS ) or Test::More->builder->BAILOUT( "Cannot load $CLASS" ); my @list; my @nodes; my $c; sub convert { my $c = shift; my @l; while ( my $n = $c->() ) { push @l, $n; } return @l; } push @nodes, $CLASS->new('A'); @list = convert( $c = $nodes[0]->traverse ); is_deeply( \@list, [$nodes[0]], "A preorder traversal of a single-node tree is itself" ); @list = convert( $c = $nodes[0]->traverse( $nodes[0]->PRE_ORDER ) ); is_deeply( \@list, [$nodes[0]], "A preorder traversal of a single-node tree is itself" ); @list = convert( $c = $nodes[0]->traverse( $nodes[0]->POST_ORDER )); is_deeply( \@list, [$nodes[0]], "A postorder traversal of a single-node tree is itself" ); @list = convert( $c = $nodes[0]->traverse( $nodes[0]->LEVEL_ORDER )); is_deeply( \@list, [$nodes[0]], "A levelorder traversal of a single-node tree is itself" ); is( $nodes[0]->traverse( 'floober' ), undef, "traverse(): An illegal traversal order is an error" ); is( $nodes[0]->last_error, "traverse(): 'floober' is an illegal traversal order", "... and the error is good" ); push @nodes, $CLASS->new('B'); $nodes[0]->add_child( $nodes[-1] ); @list = convert( $c = $nodes[0]->traverse ); is_deeply( \@list, [ @nodes[0,1] ], "A preorder traversal of this tree is A-B" ); @list = convert( $c = $nodes[0]->traverse( $nodes[0]->PRE_ORDER ) ); is_deeply( \@list, [ @nodes[0,1] ], "A preorder traversal of this tree is A-B" ); @list = convert( $c = $nodes[0]->traverse( $nodes[0]->POST_ORDER )); is_deeply( \@list, [ @nodes[1,0] ], "A postorder traversal of this tree is B-A" ); print scalar @list, $/; @list = convert( $c = $nodes[0]->traverse( $nodes[0]->LEVEL_ORDER )); is_deeply( \@list, [ @nodes[0,1] ], "A levelorder traversal of this tree is A-B" ); push @nodes, $CLASS->new('C'); $nodes[0]->add_child( $nodes[-1] ); @list = convert( $c = $nodes[0]->traverse ); is_deeply( \@list, [ @nodes[0,1,2] ], "A preorder traversal of this tree is A-B-C" ); @list = convert( $c = $nodes[0]->traverse( $nodes[0]->PRE_ORDER ) ); is_deeply( \@list, [ @nodes[0,1,2] ], "A preorder traversal of this tree is A-B-C" ); @list = convert( $c = $nodes[0]->traverse( $nodes[0]->POST_ORDER )); is_deeply( \@list, [ @nodes[1,2,0] ], "A postorder traversal of this tree is B-C-A" ); @list = convert( $c = $nodes[0]->traverse( $nodes[0]->LEVEL_ORDER )); is_deeply( \@list, [ @nodes[0,1,2] ], "A levelorder traversal of this tree is A-B-C" ); push @nodes, $CLASS->new('D'); $nodes[1]->add_child( $nodes[-1] ); @list = convert( $c = $nodes[0]->traverse ); is_deeply( \@list, [ @nodes[0,1,3,2] ], "A preorder traversal of this tree is A-B-D-C" ); @list = convert( $c = $nodes[0]->traverse( $nodes[0]->PRE_ORDER ) ); is_deeply( \@list, [ @nodes[0,1,3,2] ], "A preorder traversal of this tree is A-B-D-C" ); @list = convert( $c = $nodes[0]->traverse( $nodes[0]->POST_ORDER )); is_deeply( \@list, [ @nodes[3,1,2,0] ], "A postorder traversal of this tree is D-B-C-A" ); @list = convert( $c = $nodes[0]->traverse( $nodes[0]->LEVEL_ORDER )); is_deeply( \@list, [ @nodes[0,1,2,3] ], "A levelorder traversal of this tree is A-B-C-D" ); push @nodes, $CLASS->new('E'); $nodes[1]->add_child( $nodes[-1] ); @list = convert( $c = $nodes[0]->traverse ); is_deeply( \@list, [ @nodes[0,1,3,4,2] ], "A preorder traversal of this tree is A-B-D-E-C" ); @list = convert( $c = $nodes[0]->traverse( $nodes[0]->PRE_ORDER ) ); is_deeply( \@list, [ @nodes[0,1,3,4,2] ], "A preorder traversal of this tree is A-B-D-E-C" ); @list = convert( $c = $nodes[0]->traverse( $nodes[0]->POST_ORDER )); is_deeply( \@list, [ @nodes[3,4,1,2,0] ], "A postorder traversal of this tree is D-E-B-C-A" ); @list = convert( $c = $nodes[0]->traverse( $nodes[0]->LEVEL_ORDER )); is_deeply( \@list, [ @nodes[0,1,2,3,4] ], "A levelorder traversal of this tree is A-B-C-D" ); push @nodes, $CLASS->new('F'); $nodes[1]->add_child( $nodes[-1] ); @list = convert( $c = $nodes[0]->traverse ); is_deeply( \@list, [ @nodes[0,1,3,4,5,2] ], "A preorder traversal of this tree is A-B-D-E-F-C" ); @list = convert( $c = $nodes[0]->traverse( $nodes[0]->PRE_ORDER ) ); is_deeply( \@list, [ @nodes[0,1,3,4,5,2] ], "A preorder traversal of this tree is A-B-D-E-F-C" ); @list = convert( $c = $nodes[0]->traverse( $nodes[0]->POST_ORDER )); is_deeply( \@list, [ @nodes[3,4,5,1,2,0] ], "A postorder traversal of this tree is A-B-D-E-F-C" ); @list = convert( $c = $nodes[0]->traverse( $nodes[0]->LEVEL_ORDER )); is_deeply( \@list, [ @nodes[0,1,2,3,4,5] ], "A levelorder traversal of this tree is A-B-D-E-F-C" ); push @nodes, $CLASS->new('G'); $nodes[4]->add_child( $nodes[-1] ); @list = convert( $c = $nodes[0]->traverse ); is_deeply( \@list, [ @nodes[0,1,3,4,6,5,2] ], "A preorder traversal of this tree is A-B-D-E-G-F-C" ); @list = convert( $c = $nodes[0]->traverse( $nodes[0]->PRE_ORDER ) ); is_deeply( \@list, [ @nodes[0,1,3,4,6,5,2] ], "A preorder traversal of this tree is A-B-D-E-G-F-C" ); @list = convert( $c = $nodes[0]->traverse( $nodes[0]->POST_ORDER )); is_deeply( \@list, [ @nodes[3,6,4,5,1,2,0] ], "A postorder traversal of this tree is D-G-E-F-B-C-A" ); @list = convert( $c = $nodes[0]->traverse( $nodes[0]->LEVEL_ORDER )); is_deeply( \@list, [ @nodes[0,1,2,3,4,5,6] ], "A levelorder traversal of this tree is A-B-C-D-E-F-G" ); push @nodes, $CLASS->new('H'); $nodes[2]->add_child( $nodes[-1] ); @list = convert( $c = $nodes[0]->traverse ); is_deeply( \@list, [ @nodes[0,1,3,4,6,5,2,7] ], "A preorder traversal of this tree is A-B-D-E-G-F-C-H" ); @list = convert( $c = $nodes[0]->traverse( $nodes[0]->PRE_ORDER ) ); is_deeply( \@list, [ @nodes[0,1,3,4,6,5,2,7] ], "A preorder traversal of this tree is A-B-D-E-G-F-C-H" ); @list = convert( $c = $nodes[0]->traverse( $nodes[0]->POST_ORDER )); is_deeply( \@list, [ @nodes[3,6,4,5,1,7,2,0] ], "A postorder traversal of this tree is D-G-E-F-B-H-C-A" ); @list = convert( $c = $nodes[0]->traverse( $nodes[0]->LEVEL_ORDER )); is_deeply( \@list, [ @nodes[0,1,2,3,4,5,7,6] ], "A levelorder traversal of this tree is A-B-C-D-E-F-H-G" ); Tree-1.07/t/Tree/008_weak_refs.t000444001750001750 1051212453731754 15172 0ustar00ronron000000000000use strict; use warnings; use Test::More; eval "use Test::Memory::Cycle 1.02"; plan skip_all => "Test::Memory::Cycle required for testing memory leaks" if $@; plan tests => 43; my $CLASS = 'Tree'; use_ok( $CLASS, 'use_weak_refs' ) or Test::More->builder->BAILOUT( "Cannot load $CLASS" ); { #diag "parental connections are weak"; my $tree2 = $CLASS->new(); ok($tree2->is_root(), '... tree2 is a ROOT'); { my $tree1 = $CLASS->new("1"); $tree1->add_child($tree2); ok(!$tree2->is_root(), '... now tree2 is not a ROOT'); weakened_memory_cycle_exists($tree2, '... there is a weakened cycle in tree2'); } weakened_memory_cycle_ok($tree2, '... tree2 is no longer connected to tree1'); ok($tree2->is_root(), '... now tree2 is a ROOT again'); ok(!$tree2->parent(), '... now tree2s parent is no longer defined'); } { #diag "expand the problem to check child connections"; my $tree2 = $CLASS->new("2"); ok($tree2->is_root(), '... tree2 is a ROOT'); ok($tree2->is_leaf(), '... tree2 is a Leaf'); my $tree3 = $CLASS->new("3"); ok($tree3->is_root(), '... tree3 is a ROOT'); ok($tree3->is_leaf(), '... tree3 is a Leaf'); { my $tree1 = $CLASS->new("1"); $tree1->add_child($tree2); ok(!$tree2->is_root(), '... now tree2 is not a ROOT'); $tree2->add_child($tree3); ok(!$tree2->is_leaf(), '... now tree2 is not a Leaf'); ok(!$tree3->is_root(), '... tree3 is no longer a ROOT'); ok($tree3->is_leaf(), '... but tree3 is still a Leaf'); weakened_memory_cycle_exists($tree1, '... there is a cycle in tree1'); weakened_memory_cycle_exists($tree2, '... there is a cycle in tree2'); weakened_memory_cycle_exists($tree3, '... there is a cycle in tree3'); } weakened_memory_cycle_exists($tree2, '... calling DESTORY on tree1 broke the connection with tree2'); ok($tree2->is_root(), '... now tree2 is a ROOT again'); ok(!$tree2->is_leaf(), '... now tree2 is a not a leaf again'); ok(!$tree2->parent(), '... now tree2s parent is no longer defined'); cmp_ok($tree2->children(), '==', 1, '... now tree2 has one child'); weakened_memory_cycle_exists($tree3, '... calling DESTORY on tree1 did not break the connection betwee tree2 and tree3'); ok(!$tree3->is_root(), '... now tree3 is not a ROOT'); ok($tree3->is_leaf(), '... now tree3 is still a leaf'); ok(defined($tree3->parent()), '... now tree3s parent is still defined'); is($tree3->parent(), $tree2, '... now tree3s parent is still tree2'); } { #diag "child connections are strong"; my $tree1 = $CLASS->new("1"); my $tree2_string; { my $tree2 = $CLASS->new("2"); $tree1->add_child($tree2); $tree2_string = $tree2 . ""; weakened_memory_cycle_exists($tree1, '... tree1 is connected to tree2'); weakened_memory_cycle_exists($tree2, '... tree2 is connected to tree1'); } weakened_memory_cycle_exists($tree1, '... tree2 is still connected to tree1 because child connections are strong'); is($tree1->children(0) . "", $tree2_string, '... tree2 is still connected to tree1'); is($tree1->children(0)->parent(), $tree1, '... tree2s parent is tree1'); cmp_ok($tree1->children(), '==', 1, '... tree1 has a child count of 1'); } { #diag "expand upon this issue"; my $tree1 = $CLASS->new("1"); my $tree2_string; my $tree3 = $CLASS->new("3"); { my $tree2 = $CLASS->new("2"); $tree1->add_child($tree2); $tree2_string = $tree2 . ""; $tree2->add_child($tree3); weakened_memory_cycle_exists($tree1, '... tree1 is connected to tree2'); weakened_memory_cycle_exists($tree2, '... tree2 is connected to tree1'); weakened_memory_cycle_exists($tree3, '... tree3 is connected to tree2'); } weakened_memory_cycle_exists($tree1, '... tree2 is still connected to tree1 because child connections are strong'); is($tree1->children(0) . "", $tree2_string, '... tree2 is still connected to tree1'); is($tree1->children(0)->parent(), $tree1, '... tree2s parent is tree1'); cmp_ok($tree1->children(), '==', 1, '... tree1 has a child count of 1'); cmp_ok($tree1->children(0)->children(), '==', 1, '... tree2 is still connected to tree3'); is($tree1->children(0)->children(0), $tree3, '... tree2 is still connected to tree3'); } Tree-1.07/t/Tree/004_multiple_children.t000444001750001750 1042212453731754 16723 0ustar00ronron000000000000use lib 't/lib'; use strict; use warnings; use Test::More; use Tests qw( %runs ); plan tests => 27 + 15 * $runs{stats}{plan}; my $CLASS = 'Tree'; use_ok( $CLASS ) or Test::More->builder->BAILOUT( "Cannot load $CLASS" ); # Test Plan: # 1) Add two children at once to a root node. # 2) Verify # 3) Remove one child # 4) Verify that the other child is still a child of the root # 5) Add the removed child back, then remove both to test removing multiple children my $root = $CLASS->new( '1' ); isa_ok( $root, $CLASS ); my $child1 = $CLASS->new( '1.1' ); isa_ok( $child1, $CLASS ); my $child2 = $CLASS->new( '1.2' ); isa_ok( $child2, $CLASS ); $runs{stats}{func}->( $root, height => 1, width => 1, depth => 0, size => 1, is_root => 1, is_leaf => 1, ); $runs{stats}{func}->( $child1, height => 1, width => 1, depth => 0, size => 1, is_root => 1, is_leaf => 1, ); $runs{stats}{func}->( $child2, height => 1, width => 1, depth => 0, size => 1, is_root => 1, is_leaf => 1, ); is( $root->add_child( $child1, $child2 ), $root, "add_child(\@many) still chains" ); $runs{stats}{func}->( $root, height => 2, width => 2, depth => 0, size => 3, is_root => 1, is_leaf => 0, ); $runs{stats}{func}->( $child1, height => 1, width => 1, depth => 1, size => 1, is_root => 0, is_leaf => 1, ); $runs{stats}{func}->( $child2, height => 1, width => 1, depth => 1, size => 1, is_root => 0, is_leaf => 1, ); cmp_ok( $root->children, '==', 2, "The root has two children" ); ok( $root->has_child( $child1 ), "The root has child1" ); ok( $root->has_child( $child2 ), "The root has child2" ); ok( $root->has_child( $child1, $child2 ), "The root has both children" ); my @v = $root->children(1, 0); cmp_ok( @v, '==', 2, "Accessing children() by index out of order gives both back" ); is( $v[0], $child2, "... the first child is correct" ); is( $v[1], $child1, "... the second child is correct" ); $root->remove_child( $child1 ); cmp_ok( $root->children, '==', 1, "After removing child1, the root has one child" ); my @children = $root->children; is( $children[0], $child2, "... and the right child is still there" ); ok( !$root->has_child( $child1 ), "The root doesn't have child1" ); ok( $root->has_child( $child2 ), "The root has child2" ); ok( !$root->has_child( $child1, $child2 ), "The root doesn't have both children" ); ok( !$root->has_child( $child2, $child1 ), "The root doesn't have both children (reversed)" ); $runs{stats}{func}->( $root, height => 2, width => 1, depth => 0, size => 2, is_root => 1, is_leaf => 0, ); $runs{stats}{func}->( $child1, height => 1, width => 1, depth => 0, size => 1, is_root => 1, is_leaf => 1, ); $runs{stats}{func}->( $child2, height => 1, width => 1, depth => 1, size => 1, is_root => 0, is_leaf => 1, ); $root->add_child( $child1 ); cmp_ok( $root->children, '==', 2, "Adding child1 back works as expected" ); $runs{stats}{func}->( $root, height => 2, width => 2, depth => 0, size => 3, is_root => 1, is_leaf => 0, ); $runs{stats}{func}->( $child1, height => 1, width => 1, depth => 1, size => 1, is_root => 0, is_leaf => 1, ); $runs{stats}{func}->( $child2, height => 1, width => 1, depth => 1, size => 1, is_root => 0, is_leaf => 1, ); { my $mirror = $root->clone->mirror; my @children = $root->children; my @reversed_children = $mirror->children; is( $children[0]->value, $reversed_children[1]->value ); is( $children[1]->value, $reversed_children[0]->value ); } my @removed = $root->remove_child( $child1, $child2 ); is( $removed[0], $child1 ); is( $removed[1], $child2 ); cmp_ok( $root->children, '==', 0, "remove_child(\@many) works" ); $runs{stats}{func}->( $root, height => 1, width => 1, depth => 0, size => 1, is_root => 1, is_leaf => 1, ); $runs{stats}{func}->( $child1, height => 1, width => 1, depth => 0, size => 1, is_root => 1, is_leaf => 1, ); $runs{stats}{func}->( $child2, height => 1, width => 1, depth => 0, size => 1, is_root => 1, is_leaf => 1, ); # Test various permutations of the return values from remove_child() { $root->add_child( $child1, $child2 ); my @removed = $root->remove_child( $child2, $child1 ); is( $removed[0], $child2 ); is( $removed[1], $child1 ); } { $root->add_child( $child1, $child2 ); my $removed = $root->remove_child( $child2, $child1 ); is( $removed, 2 ); } Tree-1.07/t/Tree/003_child_node.t000444001750001750 501012453731754 15264 0ustar00ronron000000000000use lib 't/lib'; use strict; use warnings; use Test::More; use Tests qw( %runs ); plan tests => 22 + 4 * $runs{stats}{plan}; my $CLASS = 'Tree'; use_ok( $CLASS ) or Test::More->builder->BAILOUT( "Cannot load $CLASS" ); # Test plan: # Add a single child, then retrieve it, then remove it. # 1) Verify that one can retrieve a child added # 2) Verify that the appropriate status methods reflect the change # 3) Verify that the child can be removed # 4) Verify that the appropriate status methods reflect the change my $root = $CLASS->new(); isa_ok( $root, $CLASS ); my $child = $CLASS->new(); isa_ok( $child, $CLASS ); ok( $child->is_root, "The child is a root ... for now" ); ok( $child->is_leaf, "The child is also a leaf" ); ok( !$root->has_child( $child ), "The root doesn't have the child ... yet" ); is( $root->add_child( $child ), $root, "add_child() chains" ); cmp_ok( $root->children, '==', 1, "The root has one child" ); { my @children = $root->children; cmp_ok( @children, '==', 1, "The list of children is still 1 long" ); is( $children[0], $child, "... and the child is correct" ); } is( $root->children(0), $child, "You can also access the children by index" ); { my @children = $root->children(0); cmp_ok( @children, '==', 1, "The list of children by index is still 1 long" ); is( $children[0], $child, "... and the child is correct" ); } is( $child->parent, $root, "The child's parent is also set correctly" ); is( $child->root, $root, "The child's root is also set correctly" ); ok( $root->has_child( $child ), "The tree has the child" ); my ($idx) = $root->get_index_for( $child ); cmp_ok( $idx, '==', 0, "... and the child is at index 0 (scalar)" ); my @idx = $root->get_index_for( $child ); is_deeply( \@idx, [ 0 ], "... and the child is at index 0 (list)" ); $runs{stats}{func}->( $root, height => 2, width => 1, depth => 0, size => 2, is_root => 1, is_leaf => 0, ); $runs{stats}{func}->( $child, height => 1, width => 1, depth => 1, size => 1, is_root => 0, is_leaf => 1, ); is_deeply( [ $root->remove_child( $child ) ], [ $child ], "remove_child() returns the removed node" ); is( $child->parent, "", "The child's parent is now empty" ); is( $child->root, $child, "The child's root is now itself" ); cmp_ok( $root->children, '==', 0, "The root has no children" ); $runs{stats}{func}->( $root, height => 1, width => 1, depth => 0, size => 1, is_root => 1, is_leaf => 1, ); $runs{stats}{func}->( $child, height => 1, width => 1, depth => 0, size => 1, is_root => 1, is_leaf => 1, ); Tree-1.07/t/Tree/001_root_node.t000444001750001750 526112453731754 15172 0ustar00ronron000000000000use lib 't/lib'; use strict; use warnings; use Test::More; use Tests qw( %runs ); plan tests => 26 + 3 * $runs{stats}{plan}; my $CLASS = 'Tree'; use_ok( $CLASS ) or Test::More->builder->BAILOUT( "Cannot load $CLASS" ); # Test plan: # 1) Create with an empty new(). # 2) Create with a payload passed into new(). # 3) Create with 2 parameters passed into new(). { my $tree = $CLASS->new(); isa_ok( $tree, $CLASS ); my $parent = $tree->parent; is( $parent, $tree->_null, "The root's parent is the null node" ); $runs{stats}{func}->( $tree, height => 1, width => 1, depth => 0, size => 1, is_root => 1, is_leaf => 1, ); is( $tree->root, $tree, "The root's root is itself" ); is( $tree->value, undef, "The root's value is undef" ); is( $tree->set_value( 'foobar' ), $tree, "Setting value() chains" ); is( $tree->value(), 'foobar', "Calling value() returns the value passed in" ); is_deeply( $tree->mirror, $tree, "A single-node tree's mirror is itself" ); is( $tree->root( 'foo' ), $tree, "Attempting to set the root outside the tree hierarchy acts as a getter" ); is( $tree->root, $tree, "... and doesn't change the value" ); $tree->meta->{foo} = 1; is( $tree->meta->{foo}, 1, "Meta works via in-situ update." ); $tree->meta({baa => 2}); is( ${$tree->meta}{baa}, 2, "Meta works via method call." ); } { my $tree = $CLASS->new( 'payload' ); isa_ok( $tree, $CLASS ); my $parent = $tree->parent; is( $parent, $tree->_null, "The root's parent is the null node" ); $runs{stats}{func}->( $tree, height => 1, width => 1, depth => 0, size => 1, is_root => 1, is_leaf => 1, ); is( $tree->root, $tree, "The root's root is itself" ); is( $tree->value, 'payload', "The root's value is undef" ); is( $tree->set_value( 'foobar' ), $tree, "Setting value() chains" ); is( $tree->value(), 'foobar', "Setting value() returns the value passed in" ); is_deeply( $tree->mirror, $tree, "A single-node tree's mirror is itself" ); } { my $tree = $CLASS->new( 'payload', 'unused value' ); isa_ok( $tree, $CLASS ); my $parent = $tree->parent; is( $parent, $tree->_null, "The root's parent is the null node" ); $runs{stats}{func}->( $tree, height => 1, width => 1, depth => 0, size => 1, is_root => 1, is_leaf => 1, ); is( $tree->root, $tree, "The root's root is itself" ); is( $tree->value, 'payload', "The root's value is undef" ); is( $tree->set_value( 'foobar' ), $tree, "Setting value() chains" ); is( $tree->value(), 'foobar', "Setting value() returns the value passed in" ); is_deeply( $tree->mirror, $tree, "A single-node tree's mirror is itself" ); } Tree-1.07/t/Tree/005_multilevel_tree.t000444001750001750 736512453731754 16416 0ustar00ronron000000000000use lib 't/lib'; use strict; use warnings; use Test::More; use Tests qw( %runs ); plan tests => 41 + 3 * $runs{stats}{plan}; my $CLASS = 'Tree'; use_ok( $CLASS ) or Test::More->builder->BAILOUT( "Cannot load $CLASS" ); # Test Plan: # 1) Add two children to a root node to make a 3-level tree. # 2) Verify that all state is correctly reported # 3) Remove the mid-level node # 4) Verify that all state is correctly reported # 5) Re-add the mid-level node # 6) Verify that all state is correctly reported my $root = $CLASS->new; isa_ok( $root, $CLASS ); my $child1 = $CLASS->new; isa_ok( $child1, $CLASS ); my $child2 = $CLASS->new; isa_ok( $child2, $CLASS ); $root->add_child( $child1 ); $child1->add_child( $child2 ); cmp_ok( $root->children, '==', 1, "The root has one child" ); cmp_ok( $child1->children, '==', 1, "The child1 has one child" ); cmp_ok( $child2->children, '==', 0, "The child2 has zero children" ); $runs{stats}{func}->( $root, height => 3, width => 1, depth => 0, size => 3, is_root => 1, is_leaf => 0, ); $runs{stats}{func}->( $child1, height => 2, width => 1, depth => 1, size => 2, is_root => 0, is_leaf => 0, ); $runs{stats}{func}->( $child2, height => 1, width => 1, depth => 2, size => 1, is_root => 0, is_leaf => 1, ); is( $child1->root, $root, "The child1's root is the root" ); is( $child2->root, $root, "The child2's root is the root" ); $root->remove_child( $child1 ); cmp_ok( $root->height, '==', 1, "The root's height is one after removal." ); cmp_ok( $child1->height, '==', 2, "The child1's height is two." ); cmp_ok( $child2->height, '==', 1, "The child2's height is one." ); cmp_ok( $root->width, '==', 1, "The root's width is one." ); cmp_ok( $child1->width, '==', 1, "The child1's width is one." ); cmp_ok( $child2->width, '==', 1, "The child2's width is one." ); is( $child1->root, $child1, "The child1's root is the child1" ); is( $child2->root, $child1, "The child2's root is the child1" ); $root->add_child( $child1 ); cmp_ok( $root->height, '==', 3, "The root's height is three." ); cmp_ok( $child1->height, '==', 2, "The child1's height is two." ); cmp_ok( $child2->height, '==', 1, "The child2's height is one." ); cmp_ok( $root->width, '==', 1, "The root's width is one." ); cmp_ok( $child1->width, '==', 1, "The child1's width is one." ); cmp_ok( $child2->width, '==', 1, "The child2's width is one." ); is( $child1->root, $root, "The child1's root is the root" ); is( $child2->root, $root, "The child2's root is the root" ); $child1->remove_child( $child2 ); cmp_ok( $root->height, '==', 2, "The root's height is two." ); cmp_ok( $child1->height, '==', 1, "The child1's height is one." ); cmp_ok( $child2->height, '==', 1, "The child2's height is one." ); cmp_ok( $root->width, '==', 1, "The root's width is one." ); cmp_ok( $child1->width, '==', 1, "The child1's width is one." ); cmp_ok( $child2->width, '==', 1, "The child2's width is one." ); is( $child1->root, $root, "The child1's root is the root" ); is( $child2->root, $child2, "The child2's root is the root" ); # Test 4-level trees and how root works my @nodes = map { $CLASS->new } 1 .. 4; $nodes[2]->add_child( $nodes[3] ); $nodes[1]->add_child( $nodes[2] ); $nodes[0]->add_child( $nodes[1] ); is( $nodes[0]->root, $nodes[0], "The root is correct for level 0" ); is( $nodes[1]->root, $nodes[0], "The root is correct for level 1" ); is( $nodes[2]->root, $nodes[0], "The root is correct for level 2" ); is( $nodes[3]->root, $nodes[0], "The root is correct for level 3" ); $nodes[0]->remove_child( 0 ); is( $nodes[0]->root, $nodes[0], "The root is correct for level 0" ); is( $nodes[1]->root, $nodes[1], "The root is correct for level 1" ); is( $nodes[2]->root, $nodes[1], "The root is correct for level 2" ); is( $nodes[3]->root, $nodes[1], "The root is correct for level 3" ); Tree-1.07/t/Tree/013_width.t000444001750001750 1407512453731754 14347 0ustar00ronron000000000000#!/usr/bin/perl use strict; use warnings; use Test::More tests => 76; my $CLASS = 'Tree'; use_ok( $CLASS ) or Test::More->builder->BAILOUT( "Cannot load $CLASS" ); { # test height (with pictures) my $D = $CLASS->new('D'); isa_ok($D, 'Tree'); # | # cmp_ok($D->width(), '==', 1, '... D has a width of 1'); my $E = $CLASS->new('E'); isa_ok($E, 'Tree'); $D->add_child($E); # | # # \ # cmp_ok($D->width(), '==', 1, '... D has a width of 1'); cmp_ok($E->width(), '==', 1, '... E has a width of 1'); my $F = $CLASS->new('F'); isa_ok($F, 'Tree'); $E->add_child($F); # | # # \ # # \ # cmp_ok($D->width(), '==', 1, '... D has a width of 1'); cmp_ok($E->width(), '==', 1, '... E has a width of 1'); cmp_ok($F->width(), '==', 1, '... F has a width of 1'); my $C = $CLASS->new('C'); isa_ok($C, 'Tree'); $D->add_child($C); # | # # / \ # # \ # cmp_ok($D->width(), '==', 2, '... D has a width of 2'); cmp_ok($E->width(), '==', 1, '... E has a width of 1'); cmp_ok($F->width(), '==', 1, '... F has a width of 1'); cmp_ok($C->width(), '==', 1, '... C has a width of 1'); my $B = $CLASS->new('B'); isa_ok($B, 'Tree'); $D->add_child($B); # | # # / | \ # # \ # cmp_ok($D->width(), '==', 3, '... D has a width of 3'); cmp_ok($E->width(), '==', 1, '... E has a width of 1'); cmp_ok($F->width(), '==', 1, '... F has a width of 1'); cmp_ok($C->width(), '==', 1, '... C has a width of 1'); cmp_ok($B->width(), '==', 1, '... B has a width of 1'); my $A = $CLASS->new('A'); isa_ok($A, 'Tree'); $E->add_child($A); # | # # / | \ # # / \ # cmp_ok($D->width(), '==', 4, '... D has a width of 4'); cmp_ok($E->width(), '==', 2, '... E has a width of 2'); cmp_ok($F->width(), '==', 1, '... F has a width of 1'); cmp_ok($C->width(), '==', 1, '... C has a width of 1'); cmp_ok($B->width(), '==', 1, '... B has a width of 1'); cmp_ok($A->width(), '==', 1, '... A has a width of 1'); my $G = $CLASS->new('G'); isa_ok($G, 'Tree'); $E->add_child( { at => 1 }, $G); # | # # / | \ # # / | \ # cmp_ok($D->width(), '==', 5, '... D has a width of 5'); cmp_ok($E->width(), '==', 3, '... E has a width of 3'); cmp_ok($F->width(), '==', 1, '... F has a width of 1'); cmp_ok($G->width(), '==', 1, '... G has a width of 1'); cmp_ok($C->width(), '==', 1, '... C has a width of 1'); cmp_ok($B->width(), '==', 1, '... B has a width of 1'); cmp_ok($A->width(), '==', 1, '... A has a width of 1'); my $H = $CLASS->new('H'); isa_ok($H, 'Tree'); $G->add_child($H); # | # # / | \ # # / | \ # # | # cmp_ok($D->width(), '==', 5, '... D has a width of 5'); cmp_ok($E->width(), '==', 3, '... E has a width of 3'); cmp_ok($F->width(), '==', 1, '... F has a width of 1'); cmp_ok($G->width(), '==', 1, '... G has a width of 1'); cmp_ok($H->width(), '==', 1, '... H has a width of 1'); cmp_ok($C->width(), '==', 1, '... C has a width of 1'); cmp_ok($B->width(), '==', 1, '... B has a width of 1'); cmp_ok($A->width(), '==', 1, '... A has a width of 1'); my $I = $CLASS->new('I'); isa_ok($I, 'Tree'); $G->add_child($I); # | # # / | \ # # / | \ # # | \ # cmp_ok($D->width(), '==', 6, '... D has a width of 6'); cmp_ok($E->width(), '==', 4, '... E has a width of 4'); cmp_ok($F->width(), '==', 1, '... F has a width of 1'); cmp_ok($G->width(), '==', 2, '... G has a width of 2'); cmp_ok($H->width(), '==', 1, '... H has a width of 1'); cmp_ok($I->width(), '==', 1, '... I has a width of 1'); cmp_ok($C->width(), '==', 1, '... C has a width of 1'); cmp_ok($B->width(), '==', 1, '... B has a width of 1'); cmp_ok($A->width(), '==', 1, '... A has a width of 1'); ok($E->remove_child($A), '... removed A subtree from B tree'); # | # # / | \ # # | \ # # | \ # cmp_ok($D->width(), '==', 5, '... D has a width of 5'); cmp_ok($E->width(), '==', 3, '... E has a width of 3'); cmp_ok($F->width(), '==', 1, '... F has a width of 1'); cmp_ok($G->width(), '==', 2, '... G has a width of 2'); cmp_ok($H->width(), '==', 1, '... H has a width of 1'); cmp_ok($C->width(), '==', 1, '... C has a width of 2'); cmp_ok($B->width(), '==', 1, '... B has a width of 1'); # and the removed tree is ok cmp_ok($A->width(), '==', 1, '... A has a width of 1'); ok($D->remove_child($E), '... removed E subtree from D tree'); # | # # / | # cmp_ok($D->width(), '==', 2, '... D has a width of 2'); cmp_ok($C->width(), '==', 1, '... C has a width of 1'); cmp_ok($B->width(), '==', 1, '... B has a width of 1'); # and the removed trees are ok cmp_ok($E->width(), '==', 3, '... E has a width of 3'); cmp_ok($F->width(), '==', 1, '... F has a width of 1'); cmp_ok($G->width(), '==', 2, '... G has a width of 2'); cmp_ok($H->width(), '==', 1, '... H has a width of 1'); ok($D->remove_child($C), '... removed C subtree from D tree'); # | # # / # cmp_ok($D->width(), '==', 1, '... D has a width of 1'); cmp_ok($B->width(), '==', 1, '... B has a width of 1'); # and the removed tree is ok cmp_ok($C->width(), '==', 1, '... C has a width of 1'); } Tree-1.07/t/Tree/015_traverse.t000444001750001750 1254112453731754 15061 0ustar00ronron000000000000use strict; use warnings; use Test::More tests => 35; my $CLASS = 'Tree'; use_ok( $CLASS ) or Test::More->builder->BAILOUT( "Cannot load $CLASS" ); my @list; my @nodes; push @nodes, $CLASS->new('A'); @list = $nodes[0]->traverse; is_deeply( \@list, [$nodes[0]], "A preorder traversal of a single-node tree is itself" ); @list = $nodes[0]->traverse( $nodes[0]->PRE_ORDER ); is_deeply( \@list, [$nodes[0]], "A preorder traversal of a single-node tree is itself" ); @list = $nodes[0]->traverse( $nodes[0]->POST_ORDER ); is_deeply( \@list, [$nodes[0]], "A postorder traversal of a single-node tree is itself" ); @list = $nodes[0]->traverse( $nodes[0]->LEVEL_ORDER ); is_deeply( \@list, [$nodes[0]], "A levelorder traversal of a single-node tree is itself" ); is( $nodes[0]->traverse( 'floober' ), undef, "traverse(): An illegal traversal order is an error" ); is( $nodes[0]->last_error, "traverse(): 'floober' is an illegal traversal order", "... and the error is good" ); push @nodes, $CLASS->new('B'); $nodes[0]->add_child( $nodes[-1] ); @list = $nodes[0]->traverse; is_deeply( \@list, [ @nodes[0,1] ], "A preorder traversal of this tree is A-B" ); @list = $nodes[0]->traverse( $nodes[0]->PRE_ORDER ); is_deeply( \@list, [ @nodes[0,1] ], "A preorder traversal of this tree is A-B" ); @list = $nodes[0]->traverse( $nodes[0]->POST_ORDER ); is_deeply( \@list, [ @nodes[1,0] ], "A postorder traversal of this tree is B-A" ); @list = $nodes[0]->traverse( $nodes[0]->LEVEL_ORDER ); is_deeply( \@list, [ @nodes[0,1] ], "A levelorder traversal of this tree is A-B" ); push @nodes, $CLASS->new('C'); $nodes[0]->add_child( $nodes[-1] ); @list = $nodes[0]->traverse; is_deeply( \@list, [ @nodes[0,1,2] ], "A preorder traversal of this tree is A-B-C" ); @list = $nodes[0]->traverse( $nodes[0]->PRE_ORDER ); is_deeply( \@list, [ @nodes[0,1,2] ], "A preorder traversal of this tree is A-B-C" ); @list = $nodes[0]->traverse( $nodes[0]->POST_ORDER ); is_deeply( \@list, [ @nodes[1,2,0] ], "A postorder traversal of this tree is B-C-A" ); @list = $nodes[0]->traverse( $nodes[0]->LEVEL_ORDER ); is_deeply( \@list, [ @nodes[0,1,2] ], "A levelorder traversal of this tree is A-B-C" ); push @nodes, $CLASS->new('D'); $nodes[1]->add_child( $nodes[-1] ); @list = $nodes[0]->traverse; is_deeply( \@list, [ @nodes[0,1,3,2] ], "A preorder traversal of this tree is A-B-D-C" ); @list = $nodes[0]->traverse( $nodes[0]->PRE_ORDER ); is_deeply( \@list, [ @nodes[0,1,3,2] ], "A preorder traversal of this tree is A-B-D-C" ); @list = $nodes[0]->traverse( $nodes[0]->POST_ORDER ); is_deeply( \@list, [ @nodes[3,1,2,0] ], "A postorder traversal of this tree is D-B-C-A" ); @list = $nodes[0]->traverse( $nodes[0]->LEVEL_ORDER ); is_deeply( \@list, [ @nodes[0,1,2,3] ], "A levelorder traversal of this tree is A-B-C-D" ); push @nodes, $CLASS->new('E'); $nodes[1]->add_child( $nodes[-1] ); @list = $nodes[0]->traverse; is_deeply( \@list, [ @nodes[0,1,3,4,2] ], "A preorder traversal of this tree is A-B-D-E-C" ); @list = $nodes[0]->traverse( $nodes[0]->PRE_ORDER ); is_deeply( \@list, [ @nodes[0,1,3,4,2] ], "A preorder traversal of this tree is A-B-D-E-C" ); @list = $nodes[0]->traverse( $nodes[0]->POST_ORDER ); is_deeply( \@list, [ @nodes[3,4,1,2,0] ], "A postorder traversal of this tree is D-E-B-C-A" ); @list = $nodes[0]->traverse( $nodes[0]->LEVEL_ORDER ); is_deeply( \@list, [ @nodes[0,1,2,3,4] ], "A levelorder traversal of this tree is A-B-C-D" ); push @nodes, $CLASS->new('F'); $nodes[1]->add_child( $nodes[-1] ); @list = $nodes[0]->traverse; is_deeply( \@list, [ @nodes[0,1,3,4,5,2] ], "A preorder traversal of this tree is A-B-D-E-F-C" ); @list = $nodes[0]->traverse( $nodes[0]->PRE_ORDER ); is_deeply( \@list, [ @nodes[0,1,3,4,5,2] ], "A preorder traversal of this tree is A-B-D-E-F-C" ); @list = $nodes[0]->traverse( $nodes[0]->POST_ORDER ); is_deeply( \@list, [ @nodes[3,4,5,1,2,0] ], "A postorder traversal of this tree is A-B-D-E-F-C" ); @list = $nodes[0]->traverse( $nodes[0]->LEVEL_ORDER ); is_deeply( \@list, [ @nodes[0,1,2,3,4,5] ], "A levelorder traversal of this tree is A-B-D-E-F-C" ); push @nodes, $CLASS->new('G'); $nodes[4]->add_child( $nodes[-1] ); @list = $nodes[0]->traverse; is_deeply( \@list, [ @nodes[0,1,3,4,6,5,2] ], "A preorder traversal of this tree is A-B-D-E-G-F-C" ); @list = $nodes[0]->traverse( $nodes[0]->PRE_ORDER ); is_deeply( \@list, [ @nodes[0,1,3,4,6,5,2] ], "A preorder traversal of this tree is A-B-D-E-G-F-C" ); @list = $nodes[0]->traverse( $nodes[0]->POST_ORDER ); is_deeply( \@list, [ @nodes[3,6,4,5,1,2,0] ], "A postorder traversal of this tree is D-G-E-F-B-C-A" ); @list = $nodes[0]->traverse( $nodes[0]->LEVEL_ORDER ); is_deeply( \@list, [ @nodes[0,1,2,3,4,5,6] ], "A levelorder traversal of this tree is A-B-C-D-E-F-G" ); push @nodes, $CLASS->new('H'); $nodes[2]->add_child( $nodes[-1] ); @list = $nodes[0]->traverse; is_deeply( \@list, [ @nodes[0,1,3,4,6,5,2,7] ], "A preorder traversal of this tree is A-B-D-E-G-F-C-H" ); @list = $nodes[0]->traverse( $nodes[0]->PRE_ORDER ); is_deeply( \@list, [ @nodes[0,1,3,4,6,5,2,7] ], "A preorder traversal of this tree is A-B-D-E-G-F-C-H" ); @list = $nodes[0]->traverse( $nodes[0]->POST_ORDER ); is_deeply( \@list, [ @nodes[3,6,4,5,1,7,2,0] ], "A postorder traversal of this tree is D-G-E-F-B-H-C-A" ); @list = $nodes[0]->traverse( $nodes[0]->LEVEL_ORDER ); is_deeply( \@list, [ @nodes[0,1,2,3,4,5,7,6] ], "A levelorder traversal of this tree is A-B-C-D-E-F-H-G" ); Tree-1.07/t/Tree/016_events.t000444001750001750 263712453731754 14520 0ustar00ronron000000000000use lib 't/lib'; use strict; use warnings; use Test::More; #use Tests qw( %runs ); plan tests => 8; my $CLASS = 'Tree'; use_ok( $CLASS ) or Test::More->builder->BAILOUT( "Cannot load $CLASS" ); my $tree = $CLASS->new( 'root' ); my @stack; is( $tree->add_event_handler({ add_child => sub { my ($node, @args) = @_; push @stack, "Added @args to $node"; }, value => sub { my ($node, $old, $new) = @_; push @stack, "Value changed: $old -> $new from $node"; }, }), $tree, "add_event_handler() chains and handles multiple entries" ); my $child = $CLASS->new; $tree->add_child( $child ); is( $stack[0], "Added $child to $tree", "Event triggered handler" ); my $child2 = $CLASS->new; $child->add_child( $child2 ); is( $stack[1], "Added $child2 to $child", "Events bubble upwards to the parent" ); $child->add_event_handler({ remove_child => sub { my ($node, @args) = @_; push @stack, "Removed @args from $node"; }, }); $child->remove_child( $child2 ); is( $stack[2], "Removed $child2 from $child", "remove_child event" ); $tree->remove_child( $child ); cmp_ok( @stack, '==', 3, "Events trigger on the actor, not the acted-upon" ); $tree->set_value( 'new value' ); is( $stack[3], "Value changed: root -> new value from $tree", "remove_child event" ); $tree->value(); cmp_ok( @stack, '==', 4, "The value event only triggers when it's set, not accessed" ); Tree-1.07/t/Tree/002_null_object.t000444001750001750 311412453731754 15476 0ustar00ronron000000000000use strict; use warnings; use Test::More tests => 15; use Scalar::Util qw( refaddr ); my $CLASS = 'Tree'; use_ok( $CLASS ) or Test::More->builder->BAILOUT( "Cannot load $CLASS" ); # Test plan: # 1) The null object should inherit from Tree::Simple # 2) It should be false in all respects # 3) It should report that it can perform any method # 4) Any method call on it should return back the null object my $NULL_CLASS = $CLASS . '::Null'; my $obj = $NULL_CLASS->new; isa_ok( $obj, $NULL_CLASS ); isa_ok( $obj, $CLASS ); ok( !$obj->isa( 'Floober' ), "Verify that isa() works in the negative case" ); TODO: { local $TODO = "Need to figure out a way to have an object evaluate as undef"; ok( !defined $obj, " ... and undefined" ); } ok( !$obj, "The null object is false" ); ok( $obj eq "", " .. and stringifies to the empty string" ); ok( $obj == 0, " ... and numifies to zero" ); can_ok( $obj, 'some_random_method' ); my $val = $obj->some_random_method; is( refaddr($val), refaddr($obj), "The return value of any method call on the null object is the null object" ); my $subref = $obj->can( 'some_random_method' ); my $val2 = $subref->($obj); is( refaddr($val2), refaddr($obj), "The return value of any method call on the null object is the null object" ); is( refaddr($obj->method1->method2), refaddr($obj), "Method chaining works" ); is( refaddr($CLASS->_null), refaddr($obj), "The _null method on $CLASS returns a null object" ); my $tree = $CLASS->new; isa_ok( $tree, $CLASS ); is( refaddr($tree->_null), refaddr($obj), "The _null method on an object of $CLASS returns a null object" ); Tree-1.07/t/Tree/000_interface.t000444001750001750 332412453731754 15137 0ustar00ronron000000000000use strict; use warnings; use Test::More tests => 7; my $CLASS = 'Tree'; use_ok( $CLASS ) or Test::More->builder->BAILOUT( "Cannot load $CLASS" ); # Test plan: # 1) Verify that the API is correct. This will serve as documentation for which methods # should be part of which kind of API. # 2) Verify that all methods in $CLASS have been classified appropriately my %existing_methods = do { no strict 'refs'; map { $_ => undef } grep { /^[a-zA-Z_]+$/ } grep { exists &{${ $CLASS . '::'}{$_}} } keys %{ $CLASS . '::'} }; my %methods = ( class => [ qw( new error_handler QUIET WARN DIE PRE_ORDER POST_ORDER LEVEL_ORDER )], public => [ qw( is_root is_leaf add_child remove_child has_child get_index_for root parent children height width depth size error_handler error last_error value set_value clone mirror traverse add_event_handler event tree2string node2string format_node hashref2string meta )], private => [ qw( _null _fix_width _fix_height _fix_depth _init _set_root _strip_options )], # book_keeping => [qw( # )], imported => [qw( blessed refaddr weaken )], ); # These are the class methods can_ok( $CLASS, @{ $methods{class} } ); delete @existing_methods{@{$methods{class}}}; my $tree = $CLASS->new(); isa_ok( $tree, $CLASS ); for my $type ( qw( public private imported ) ) { can_ok( $tree, @{ $methods{ $type } } ); delete @existing_methods{@{$methods{ $type }}}; } if ( my @k = keys %existing_methods ) { ok( 0, "We need to account for '" . join ("','", @k) . "'" ); } else { ok( 1, "We've accounted for everything." ); } Tree-1.07/t/Tree/011_errors_removechild.t000444001750001750 214712453731754 17100 0ustar00ronron000000000000use lib 't/lib'; use strict; use warnings; use Test::More; use Tests qw( %runs ); plan tests => 1 + 6 * $runs{error}{plan}; my $CLASS = 'Tree'; use_ok( $CLASS ) or Test::More->builder->BAILOUT( "Cannot load $CLASS" ); my $root = $CLASS->new; my $child1 = $CLASS->new; my $child2 = $CLASS->new; $root->add_child( $child1 ); my %defaults = ( func => 'remove_child', validator => 'children', value => 1, ); $runs{error}{func}->( $root, %defaults, args => [], error => "remove_child(): Nothing to remove", ); $runs{error}{func}->( $root, %defaults, args => [ undef ], error => "remove_child(): 'undef' is out-of-bounds", ); $runs{error}{func}->( $root, %defaults, args => [ 'foo' ], error => "remove_child(): 'foo' is not a legal index", ); $runs{error}{func}->( $root, %defaults, args => [ 1 ], error => "remove_child(): '1' is out-of-bounds", ); $runs{error}{func}->( $root, %defaults, args => [ -1 ], error => "remove_child(): '-1' is out-of-bounds", ); $runs{error}{func}->( $root, %defaults, args => [ $child2 ], error => "remove_child(): '$child2' not found", ); Tree-1.07/t/Tree/012_height.t000444001750001750 1447612453731754 14504 0ustar00ronron000000000000#!/usr/bin/perl use strict; use warnings; use Test::More tests => 82; my $CLASS = 'Tree'; use_ok( $CLASS ) or Test::More->builder->BAILOUT( "Cannot load $CLASS" ); { # test height (with pictures) my $D = $CLASS->new('D'); isa_ok($D, 'Tree'); # | # cmp_ok($D->height(), '==', 1, '... D has a height of 1'); my $E = $CLASS->new('E'); isa_ok($E, 'Tree'); $D->add_child($E); # | # # \ # cmp_ok($D->height(), '==', 2, '... D has a height of 2'); cmp_ok($E->height(), '==', 1, '... E has a height of 1'); my $F = $CLASS->new('F'); isa_ok($F, 'Tree'); $E->add_child($F); # | # # \ # # \ # cmp_ok($D->height(), '==', 3, '... D has a height of 3'); cmp_ok($E->height(), '==', 2, '... E has a height of 2'); cmp_ok($F->height(), '==', 1, '... F has a height of 1'); my $C = $CLASS->new('C'); isa_ok($C, 'Tree'); $D->add_child($C); # | # # / \ # # \ # cmp_ok($D->height(), '==', 3, '... D has a height of 3'); cmp_ok($E->height(), '==', 2, '... E has a height of 2'); cmp_ok($F->height(), '==', 1, '... F has a height of 1'); cmp_ok($C->height(), '==', 1, '... C has a height of 1'); my $B = $CLASS->new('B'); isa_ok($B, 'Tree'); $C->add_child($B); # | # # / \ # # / \ # cmp_ok($D->height(), '==', 3, '... D has a height of 3'); cmp_ok($E->height(), '==', 2, '... E has a height of 2'); cmp_ok($F->height(), '==', 1, '... F has a height of 1'); cmp_ok($C->height(), '==', 2, '... C has a height of 2'); cmp_ok($B->height(), '==', 1, '... B has a height of 1'); my $A = $CLASS->new('A'); isa_ok($A, 'Tree'); $B->add_child($A); # | # # / \ # # / \ # # / # cmp_ok($D->height(), '==', 4, '... D has a height of 4'); cmp_ok($E->height(), '==', 2, '... E has a height of 2'); cmp_ok($F->height(), '==', 1, '... F has a height of 1'); cmp_ok($C->height(), '==', 3, '... C has a height of 3'); cmp_ok($B->height(), '==', 2, '... B has a height of 2'); cmp_ok($A->height(), '==', 1, '... A has a height of 1'); my $G = $CLASS->new('G'); isa_ok($G, 'Tree'); $E->add_child( { at => 0 }, $G); # | # # / \ # # / / \ # # / # cmp_ok($D->height(), '==', 4, '... D has a height of 4'); cmp_ok($E->height(), '==', 2, '... E has a height of 2'); cmp_ok($F->height(), '==', 1, '... F has a height of 1'); cmp_ok($G->height(), '==', 1, '... G has a height of 1'); cmp_ok($C->height(), '==', 3, '... C has a height of 3'); cmp_ok($B->height(), '==', 2, '... B has a height of 2'); cmp_ok($A->height(), '==', 1, '... A has a height of 1'); my $H = $CLASS->new('H'); isa_ok($H, 'Tree'); $G->add_child($H); # | # # / \ # # / / \ # # / \ # cmp_ok($D->height(), '==', 4, '... D has a height of 4'); cmp_ok($E->height(), '==', 3, '... E has a height of 3'); cmp_ok($F->height(), '==', 1, '... F has a height of 1'); cmp_ok($G->height(), '==', 2, '... G has a height of 2'); cmp_ok($H->height(), '==', 1, '... H has a height of 1'); cmp_ok($C->height(), '==', 3, '... C has a height of 3'); cmp_ok($B->height(), '==', 2, '... B has a height of 2'); cmp_ok($A->height(), '==', 1, '... A has a height of 1'); cmp_ok($D->depth(), '==', 0, '... D has a depth of 0'); cmp_ok($E->depth(), '==', 1, '... E has a depth of 1'); cmp_ok($F->depth(), '==', 2, '... F has a depth of 2'); cmp_ok($G->depth(), '==', 2, '... G has a depth of 2'); cmp_ok($H->depth(), '==', 3, '... H has a depth of 3'); cmp_ok($C->depth(), '==', 1, '... C has a depth of 1'); cmp_ok($B->depth(), '==', 2, '... B has a depth of 2'); cmp_ok($A->depth(), '==', 3, '... A has a depth of 3'); cmp_ok($D->size(), '==', 8, '... D has a size of 8'); cmp_ok($E->size(), '==', 4, '... E has a size of 4'); cmp_ok($F->size(), '==', 1, '... F has a size of 1'); cmp_ok($G->size(), '==', 2, '... G has a size of 2'); cmp_ok($H->size(), '==', 1, '... H has a size of 1'); cmp_ok($C->size(), '==', 3, '... C has a size of 3'); cmp_ok($B->size(), '==', 2, '... B has a size of 2'); cmp_ok($A->size(), '==', 1, '... A has a size of 1'); ok($B->remove_child($A), '... removed A subtree from B tree'); # | # # / \ # # / / \ # # \ # cmp_ok($D->height(), '==', 4, '... D has a height of 4'); cmp_ok($E->height(), '==', 3, '... E has a height of 3'); cmp_ok($F->height(), '==', 1, '... F has a height of 1'); cmp_ok($G->height(), '==', 2, '... G has a height of 2'); cmp_ok($H->height(), '==', 1, '... H has a height of 1'); cmp_ok($C->height(), '==', 2, '... C has a height of 2'); cmp_ok($B->height(), '==', 1, '... B has a height of 1'); # and the removed tree is ok cmp_ok($A->height(), '==', 1, '... A has a height of 1'); ok($D->remove_child($E), '... removed E subtree from D tree'); # | # # / # # / # cmp_ok($D->height(), '==', 3, '... D has a height of 3'); cmp_ok($C->height(), '==', 2, '... C has a height of 2'); cmp_ok($B->height(), '==', 1, '... B has a height of 1'); # and the removed trees are ok cmp_ok($E->height(), '==', 3, '... E has a height of 3'); cmp_ok($F->height(), '==', 1, '... F has a height of 1'); cmp_ok($G->height(), '==', 2, '... G has a height of 2'); cmp_ok($H->height(), '==', 1, '... H has a height of 1'); ok($D->remove_child($C), '... removed C subtree from D tree'); # | # cmp_ok($D->height(), '==', 1, '... D has a height of 1'); # and the removed tree is ok cmp_ok($C->height(), '==', 2, '... C has a height of 2'); cmp_ok($B->height(), '==', 1, '... B has a height of 1'); } Tree-1.07/t/Tree/009_error_handling.t000444001750001750 544012453731754 16206 0ustar00ronron000000000000use strict; use warnings; use Test::More tests => 27; use Test::Warn; use Test::Exception; my $CLASS = 'Tree'; use_ok( $CLASS ) or Test::More->builder->BAILOUT( "Cannot load $CLASS" ); is( $CLASS->error_handler, $CLASS->QUIET, "The initial default error_handler is quiet." ); my $tree = $CLASS->new; is( $tree->error_handler, $CLASS->QUIET, "The default error-handler is quiet." ); is( $tree->error_handler( $tree->DIE ), $CLASS->QUIET, "Setting the error_handler returns the old one" ); is( $tree->error_handler, $CLASS->DIE, "The new error-handler is die." ); is( $CLASS->error_handler( $CLASS->WARN ), $CLASS->QUIET, "Setting the error_handler as a class method returns the old default error handler" ); my $tree2 = $CLASS->new; is( $tree2->error_handler, $CLASS->WARN, "A new tree picks up the new default error handler" ); is( $tree->error_handler, $CLASS->DIE, "... but it doesn't change current trees" ); $tree->add_child( $tree2 ); is( $tree2->error_handler, $tree->error_handler, "A child picks up its parent's error handler" ); my $err; my $handler = sub { no warnings; $err = join "", @_; return; }; $tree->error_handler( $handler ); is( $tree->error_handler, $handler, "We have set a custom error handler" ); is( $tree->error, undef, "Calling the custom error handler returns undef" ); is( $err, "". $tree, "... and with no arguments only passes the node in" ); is( $tree->error( 'Some error, huh?' ), undef, "Calling the custom error handler returns undef" ); is( $err, "". join("",$tree, 'Some error, huh?'), "... and with one argument passes the node and the argument in" ); is( $tree->error( 1, 2 ), undef, "Calling the custom error handler returns undef" ); is( $err, "". join("",$tree, 1, 2), "... and with two arguments passes the node and all arguments in" ); $tree->error_handler( $tree->QUIET ); is( $tree->last_error, undef, "There's currently no error queued up" ); is( $tree->error( 1, 2), undef, "Calling the QUIET handler returns undef" ); is( $tree->last_error, "1\n2", "The QUIET handler concatenates all strings with \\n" ); my $x = $tree->parent; is( $tree->last_error, "1\n2", "A state query doesn't reset last_error()" ); $tree->add_child( $CLASS->new ); is( $tree->last_error, undef, "add_child() resets last_error()" ); $tree->error( 1, 2); $tree->remove_child( 0 ); is( $tree->last_error, undef, "remove_child() resets last_error()" ); $tree->error_handler( $tree->WARN ); my $rv; warning_is { $rv = $tree->error( 1, 2); } '12', "Calling the WARN handler warns"; is( $rv, undef, "The WARN handler returns undef" ); is( $tree->last_error, "1\n2", "The WARN handler sets last_error()" ); $tree->error_handler( $tree->DIE ); throws_ok { $tree->error( 1, 2); } qr/12/, "Calling the DIE handler dies"; is( $tree->last_error, "1\n2", "The DIE handler sets last_error()" ); Tree-1.07/t/Tree/014_clone.t000444001750001750 417012453731754 14304 0ustar00ronron000000000000use strict; use warnings; use Test::More tests => 20; use Test::Deep; use Scalar::Util qw( refaddr ); my $CLASS = 'Tree'; use_ok( $CLASS ) or Test::More->builder->BAILOUT( "Cannot load $CLASS" ); my $tree = $CLASS->new( 'foo' ); my $clone = $tree->clone; isa_ok( $clone, $CLASS ); isnt( refaddr($clone), refaddr($tree), "The clone is a different reference from the tree" ); cmp_deeply( $clone, $tree, "The clone has all the same info as the tree" ); $tree->set_value( 'bar' ); ok( !eq_deeply( $clone, $tree ), "The tree changed, but the clone didn't track" ); $tree->set_value( 'foo' ); cmp_deeply( $clone, $tree, "The tree changed back, so they're equivalent" ); my $child = $CLASS->new; $tree->add_child( $child ); ok( !eq_deeply( $clone, $tree ), "The tree added a child, but the clone didn't track" ); my $clone2 = $tree->clone; cmp_deeply( $clone2, $tree, "Cloning with children works" ); my $cloned_child = $clone->children(0); isnt( refaddr($cloned_child), refaddr($child), "The cloned child is a different reference from the child" ); my $grandchild = $CLASS->new; $child->add_child( $grandchild ); my $clone3 = $tree->clone; cmp_deeply( $clone3, $tree, "Cloning with grandchildren works" ); my $clone4 = $child->clone; ok( !eq_deeply( $clone4, $child ), "Even though the child is cloned, the parentage is not" ); ok( $clone4->is_root, "... all clones are roots" ); my $clone5 = $CLASS->clone; isa_ok( $clone5, $CLASS ); my $tree2 = $CLASS->new('foo'); my $clone6 = $tree2->clone('bar'); ok(!eq_deeply( $clone6, $tree2 ), "By passing a value into clone(), it sets the value of the clone" ); is( $clone6->value, 'bar', "The clone's value should be 'bar'" ); is( $tree2->value, 'foo', "... but the tree's value should still be 'foo'" ); my $clone7 = $tree2->new; cmp_deeply( $clone, $tree2, "Calling new() with an object wraps clone()" ); my $clone8 = $tree2->new( 'bar' ); ok(!eq_deeply( $clone8, $tree2 ), "By passing a value into an object calling new(), it sets the value of the clone" ); is( $clone8->value, 'bar', "The clone's value should be 'bar'" ); is( $tree2->value, 'foo', "... but the tree's value should still be 'foo'" ); Tree-1.07/t/lib000755001750001750 012453731754 12143 5ustar00ronron000000000000Tree-1.07/t/lib/Tests.pm000444001750001750 235612453731754 13746 0ustar00ronron000000000000package Tests; use strict; use warnings; use Test::More; my @stats = qw( height width depth size is_root is_leaf ); use base 'Exporter'; our @EXPORT_OK = qw( %runs ); our $VERSION = '1.07'; our %runs = ( stats => { plan => scalar @stats, func => \&stat_check, }, error => { plan => 3, func => \&error_check, }, ); sub stat_check { my $tree = shift; my %opts = @_; foreach my $stat (@stats) { if ( $stat =~ /^is_(.*)/ ) { if ( $opts{$stat} ) { ok( $tree->$stat, "The tree is a $1" ); } else { ok( !$tree->$stat, "The tree is not a $1" ); } } else { cmp_ok( $tree->$stat, '==', $opts{$stat}, "The tree has a $stat of $opts{$stat}", ); } } } sub error_check { my $tree = shift; my %opts = @_; my $func = $opts{func}; my $validator = $opts{validator}; is( $tree->$func(@{$opts{args} || []}), undef, "$func(): error testing ..." ); is( $tree->last_error, $opts{error}, "... and the error is good" ); cmp_ok( $tree->$validator, '==', $opts{value}, "... and there was no change" ); } 1; __END__ Tree-1.07/t/Tree_Fast000755001750001750 012453731754 13251 5ustar00ronron000000000000Tree-1.07/t/Tree_Fast/001_clone.t000444001750001750 65212453731754 15236 0ustar00ronron000000000000# This test and the corresponding fix was submitted by HDP use 5.006; use strict; use warnings FATAL => 'all'; use Test::More tests => 3; use_ok( 'Tree::Fast' ); my $tree = Tree::Fast->new('root'); $tree->add_child({}, map { Tree::Fast->new($_) } 1..3); is($tree->children, 3, 'tree has correct number of children'); my $clone = $tree->clone; is($clone->children, 3, 'clone has correct number of children'); __END__ Tree-1.07/scripts000755001750001750 012453731754 12621 5ustar00ronron000000000000Tree-1.07/scripts/print.tree.pl000444001750001750 330212453731754 15403 0ustar00ronron000000000000#!/usr/bin/env perl use strict; use warnings; use Tree; #use Tree::DAG_Node; # ------------------------------------------------ sub tree { my($tree) = Tree -> new('Root'); $tree -> meta({uid => 0}); my($count) = 0; my(%node); for (qw/H I J K L M N O P Q/) { $node{$_} = Tree -> new($_); $node{$_} -> meta({uid => ++$count}); } $tree -> add_child($node{H}); $node{H} -> add_child($node{I}); $node{I} -> add_child($node{J}); $node{H} -> add_child($node{K}); $node{H} -> add_child($node{L}); $tree -> add_child($node{M}); $tree -> add_child($node{N}); $node{N} -> add_child($node{O}); $node{O} -> add_child($node{P}); $node{P} -> add_child($node{Q}); print map("$_\n", @{$tree -> tree2string}); print map("$_\n", @{$tree -> tree2string({no_attributes => 1})}); } # End of tree. # ------------------------------------------------ =pod sub tree_dag_node { my($tree) = Tree::DAG_Node -> new({name => 'Root'}); $tree -> attributes({uid => 0}); my($count) = 0; my(%node); for (qw/H I J K L M N O P Q/) { $node{$_} = Tree::DAG_Node -> new({name => $_}); $node{$_} -> attributes({uid => ++$count}); } $tree -> add_daughter($node{H}); $node{H} -> add_daughter($node{I}); $node{I} -> add_daughter($node{J}); $node{H} -> add_daughter($node{K}); $node{H} -> add_daughter($node{L}); $tree -> add_daughter($node{M}); $tree -> add_daughter($node{N}); $node{N} -> add_daughter($node{O}); $node{O} -> add_daughter($node{P}); $node{P} -> add_daughter($node{Q}); print map("$_\n", @{$tree -> tree2string}); print map("$_\n", @{$tree -> tree2string({no_attributes => 1})}); } # End of tree_dag_node. =cut # ------------------------------------------------ tree; #tree_dag_node;