CHI-Memoize-0.07/0000775€ˆž«€q{Ì0000000000012372655464016067 5ustar jonswartANT\Domain UsersCHI-Memoize-0.07/Changes0000644€ˆž«€q{Ì0000000161312372655464017361 0ustar jonswartANT\Domain UsersRevision history for CHI-Memoize ** denotes an incompatible change 0.07 Aug 13, 2014 * Fixes - Fix unterminated link in main POD 0.06 Aug 13, 2014 * Fixes - Use Moo not Moose, and explicitly depend on it 0.05 Aug 24, 2012 * Documentation - Simplify synopsis and refer to blog (Anirvan Chatterjee) 0.04 May 6, 2012 * Documentation - Correct example demonstrating JSON key serialization, and add test to match - RT 77027 (Daniel B. Boorstein) 0.03 May 6, 2012 * Documentation - Mention that memoizing a function will affect its call stack and its prototype * Fixes - Preserve @_ in wrapped call - RT 77027 (Daniel B. Boorstein) 0.02 May 5, 2012 * Documentation - Document cloned vs raw references and using RawMemory * Improvements - Add NO_MEMOIZE flag that can be returned from key coderef * Fixes - Fix synopsis whitespace 0.01 May 2, 2012 - Initial version CHI-Memoize-0.07/INSTALL0000644€ˆž«€q{Ì0000000166312372655464017124 0ustar jonswartANT\Domain Users This is the Perl distribution CHI-Memoize. Installing CHI-Memoize is straightforward. ## Installation with cpanm If you have cpanm, you only need one line: % cpanm CHI::Memoize If you are installing into a system-wide directory, you may need to pass the "-S" flag to cpanm, which uses sudo to install the module: % cpanm -S CHI::Memoize ## Installing with the CPAN shell Alternatively, if your CPAN shell is set up, you should just be able to do: % cpan CHI::Memoize ## Manual installation As a last resort, you can manually install it. Download the tarball, untar it, then build it: % perl Makefile.PL % make && make test Then install it: % make install If you are installing into a system-wide directory, you may need to run: % sudo make install ## Documentation CHI-Memoize documentation is available as POD. You can run perldoc from a shell to read the documentation: % perldoc CHI::Memoize CHI-Memoize-0.07/lib/0000775€ˆž«€q{Ì0000000000012372655464016635 5ustar jonswartANT\Domain UsersCHI-Memoize-0.07/lib/CHI/0000775€ˆž«€q{Ì0000000000012372655464017240 5ustar jonswartANT\Domain UsersCHI-Memoize-0.07/lib/CHI/Memoize/0000775€ˆž«€q{Ì0000000000012372655464020645 5ustar jonswartANT\Domain UsersCHI-Memoize-0.07/lib/CHI/Memoize/Info.pm0000644€ˆž«€q{Ì0000000222512372655464022075 0ustar jonswartANT\Domain Userspackage CHI::Memoize::Info; $CHI::Memoize::Info::VERSION = '0.07'; use Moo; use strict; use warnings; has [ 'orig', 'wrapper', 'cache', 'key_prefix' ] => ( is => 'ro' ); 1; __END__ =pod =head1 NAME CHI::Memoize::Info - Information about a memoized function =head1 VERSION version 0.07 =head1 SYNOPSIS use CHI::Memoize qw(:all); memoize('func'); # then my $info = memoized('func'); # The CHI cache where memoize results are stored # my $cache = $info->cache; $cache->clear; # The original function, and the new wrapped function # my $orig = $info->orig; my $wrapped = $info->wrapped; =head1 METHODS =over =item cache The CHI cache where memoize results are stored for this function =item orig The original code reference when C was called =item wrapped The wrapped code reference that C created =back =head1 AUTHOR Jonathan Swartz =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2011 by Jonathan Swartz. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut CHI-Memoize-0.07/lib/CHI/Memoize/t/0000775€ˆž«€q{Ì0000000000012372655464021110 5ustar jonswartANT\Domain UsersCHI-Memoize-0.07/lib/CHI/Memoize/t/Memoize.pm0000644€ˆž«€q{Ì0000001552412372655464023060 0ustar jonswartANT\Domain Userspackage CHI::Memoize::t::Memoize; $CHI::Memoize::t::Memoize::VERSION = '0.07'; use Test::Class::Most parent => 'Test::Class'; use File::Temp qw(tempdir); use CHI::Memoize qw(memoize memoized unmemoize NO_MEMOIZE); my $unique_id = 0; sub unique_id { ++$unique_id } sub func { join( ",", unique_id(), @_ ) } # memoize('func'); # sub test_basic : Tests { isnt( func(), func(), "different values" ); my $orig = \&func; memoize('func'); is( func(), func(), "same values" ); my $info = memoized('func'); my $cache = $info->cache; isa_ok( $info, 'CHI::Memoize::Info' ); isa_ok( $cache, 'CHI::Driver::Memory' ); is( scalar( $cache->get_keys ), 1, "1 key" ); is( $info->orig, $orig ); is( $info->wrapper, \&func ); cmp_deeply( func(), re(qr/\d+/), 'no args' ); cmp_deeply( func( 'a', 'b' ), re(qr/\d+,a,b/), 'two args' ); unmemoize('func'); isnt( func(), func(), "different values" ); ok( !memoized('func'), 'not memoized' ); is( scalar( $cache->get_keys ), 0, "0 keys" ); } # memoize('Some::Package::func'); # sub test_full_name : Tests { my $full_name = join( "::", __PACKAGE__, 'func' ); my $orig = \&func; memoize($full_name); is( func(), func(), "same values" ); my $info = memoized('func'); is( $info->orig, $orig ); is( $info->wrapper, \&func ); unmemoize($full_name); ok( !memoized($full_name) ); } # $anon = memoize($anon); # sub test_anon : Tests { my $func = sub { unique_id() }; isnt( $func->(), $func->(), "different values" ); my $memo_func = memoize($func); is( $memo_func->(), $memo_func->(), "same values" ); my $info = memoized($func); isa_ok( $info, 'CHI::Memoize::Info' ); isa_ok( $info->cache, 'CHI::Driver::Memory' ); is( scalar( $info->cache->get_keys ), 1, "1 key" ); is( $info->orig, $func ); is( $info->wrapper, $memo_func ); } # memoize('func', key => sub { $_[0] }); # memoize('func', key => sub { $_[1], $_[2] }); # sub test_dynamic_key : Tests { memoize( 'func', key => sub { $_[0] } ); is( func(), func(), "empty=empty" ); is( func( 1, 2, 3 ), func( 1, 5 ), "123=15" ); isnt( func( 1, 2, 3 ), func( 2, 2, 3 ), "123=223" ); unmemoize('func'); memoize( 'func', key => sub { $_[1], $_[2] } ); is( func( 1, 2, 3 ), func( 1, 2, 3 ), "123=123" ); is( func( 1, 2, 3 ), func( 5, 2, 3 ), "123=523" ); is( func(1), func(5), "1=5" ); isnt( func( 1, 2, 3 ), func( 1, 2, 4 ), "123!=124" ); my $info = memoized('func'); my @keys = $info->cache->get_keys; my $prefix = join( ",", map { qq{"$_"} } ( $info->key_prefix, 'S' ) ); cmp_deeply( \@keys, bag( "[$prefix,null,null]", "[$prefix,2,4]", "[$prefix,2,3]" ) ); unmemoize('func'); } # memoized_function({a => 5, b => 6, c => { d => 7, e => 8 }}); # memoized_function({b => 6, c => { e => 8, d => 7 }, a => 5}); # memoize('func', key => sub { %@_ }); # sub test_normalization : Tests { memoize('func'); is( func( { a => 5, b => 6, c => { d => 7, e => 8 } } ), func( { b => 6, c => { e => 8, d => 7 }, a => 5 } ) ); isnt( func( a => 5, b => 6, c => { d => 7, e => 8 } ), func( b => 6, c => { e => 8, d => 7 }, a => 5 ) ); unmemoize('func'); memoize( 'func', key => sub { return {@_} } ); is( func( a => 5, b => 6, c => { d => 7, e => 8 } ), func( b => 6, c => { e => 8, d => 7 }, a => 5 ) ); unmemoize('func'); } # memoize('func', key => sub { NOCACHE }); # sub test_undef_or_empty_key : Tests { memoize( 'func', key => sub { defined( $_[0] ) && $_[0] eq 'nocache' ? NO_MEMOIZE : @_ } ); is( func(), func(), "no args" ); is( func('foo'), func('foo'), "regular arg" ); isnt( func( 'nocache', 'a', 'b' ), func( 'nocache', 'a', 'b' ), "nocache" ); cmp_deeply( func( 'nocache', 'a', 'b' ), re(qr/\d+,nocache,a,b/), 'two args' ); unmemoize('func'); } # memoize('func', expires_in => '2 sec'); # sub test_expires_in : Tests { memoize( 'func', expires_in => '2 sec' ); my @vals; push( @vals, func(), func() ); push( @vals, func(), func() ); sleep(2); push( @vals, func(), func() ); push( @vals, func(), func() ); foreach my $pair ( [ 0, 1 ], [ 2, 3 ], [ 4, 5 ], [ 6, 7 ], [ 0, 2 ], [ 4, 6 ] ) { my ( $x, $y ) = @$pair; is( $vals[$x], $vals[$y], "$x=$y" ); } isnt( $vals[0], $vals[4], "0!=4" ); unmemoize('func'); } # memoize('func', expire_if => $cond); # sub test_expire_if : Tests { my $cond = 0; memoize( 'func', expire_if => sub { $cond } ); my @vals; push( @vals, func(), func() ); $cond = 1; push( @vals, func(), func() ); $cond = 0; push( @vals, func(), func() ); foreach my $pair ( [ 0, 1 ], [ 3, 4 ], [ 4, 5 ] ) { my ( $x, $y ) = @$pair; is( $vals[$x], $vals[$y], "$x=$y" ); } foreach my $pair ( [ 2, 3 ], [ 1, 2 ] ) { my ( $x, $y ) = @$pair; isnt( $vals[$x], $vals[$y], "$x!=$y" ); } unmemoize('func'); } # memoize('func', driver => 'File'); # memoize('func', cache => $cache ); # sub test_file_driver : Tests { foreach my $iter ( 0, 1 ) { my $root_dir = tempdir( 'memoize-XXXX', TMPDIR => 1, CLEANUP => 1 ); my @options = ( $iter == 0 ? ( driver => 'File', root_dir => $root_dir ) : ( cache => CHI->new( driver => 'File', root_dir => $root_dir ) ) ); memoize( 'func', @options ); is( func(), func(), "same values" ); my $cache = memoized('func')->cache; isa_ok( $cache, 'CHI::Driver::File' ); is( $cache->root_dir, $root_dir ); is( scalar( $cache->get_keys ), 1, "1 key" ); my $val = func(); $cache->clear(); isnt( func(), $val, "after clear" ); unmemoize('func'); isnt( func(), func(), "different values" ); is( scalar( $cache->get_keys ), 0, "0 keys" ); } } # memoize('func') vs memoize('func', driver => 'RawMemory'); # sub test_cloned_versus_raw : Tests { my $base = sub { [ unique_id(), unique_id() ] }; { my $func = memoize($base); my $ref1 = $func->(); my $ref2 = $func->(); cmp_deeply( $ref1, $ref2, "same contents" ); isnt( $ref1, $ref2, "different refs" ); push( @$ref1, 'foo' ); my $ref3 = $func->(); cmp_deeply( $ref3, $ref2, "memoized value unaffected by changes to result" ); unmemoize($base); } { my $func = memoize( $base, driver => 'RawMemory' ); my $ref1 = $func->(); my $ref2 = $func->(); cmp_deeply( $ref1, $ref2, "same contents" ); is( $ref1, $ref2, "same refs" ); push( @$ref1, 'foo' ); my $ref3 = $func->(); cmp_deeply( $ref3, $ref1, "memoized value affected by changes to result" ); unmemoize($base); } } 1; CHI-Memoize-0.07/lib/CHI/Memoize.pm0000644€ˆž«€q{Ì0000003106212372655464021203 0ustar jonswartANT\Domain Userspackage CHI::Memoize; $CHI::Memoize::VERSION = '0.07'; use Carp; use CHI; use CHI::Memoize::Info; use CHI::Driver; use Hash::MoreUtils qw(slice_grep); use strict; use warnings; use base qw(Exporter); my $no_memoize = {}; sub NO_MEMOIZE { $no_memoize } our @EXPORT = qw(memoize); our @EXPORT_OK = qw(memoize memoized unmemoize NO_MEMOIZE); our %EXPORT_TAGS = ( all => \@EXPORT_OK ); my %memoized; my @get_set_options = qw( busy_lock expire_if expires_at expires_in expires_variance ); my %is_get_set_option = map { ( $_, 1 ) } @get_set_options; sub memoize { my ( $func, %options ) = @_; my ( $func_name, $func_ref, $func_id ) = _parse_func_arg( $func, scalar(caller) ); croak "'$func_id' is already memoized" if exists( $memoized{$func_id} ); my $passed_key = delete( $options{key} ); my $cache = delete( $options{cache} ); my %compute_options = slice_grep { $is_get_set_option{$_} } \%options; my $prefix = "memoize::$func_id"; if ( !$cache ) { my %cache_options = slice_grep { !$is_get_set_option{$_} } \%options; $cache_options{namespace} ||= $prefix; if ( !$cache_options{driver} && !$cache_options{driver_class} ) { $cache_options{driver} = "Memory"; } if ( $cache_options{driver} eq 'Memory' || $cache_options{driver} eq 'RawMemory' ) { $cache_options{global} = 1; } $cache = CHI->new(%cache_options); } my $wrapper = sub { my $wantarray = wantarray ? 'L' : 'S'; my @key_parts = defined($passed_key) ? ( ( ref($passed_key) eq 'CODE' ) ? $passed_key->(@_) : ($passed_key) ) : @_; if ( @key_parts == 1 && ( $key_parts[0] || 0 ) eq NO_MEMOIZE ) { return $func_ref->(@_); } else { my $key = [ $prefix, $wantarray, @key_parts ]; my $args = \@_; return $cache->compute( $key, {%compute_options}, sub { $func_ref->(@$args) } ); } }; $memoized{$func_id} = CHI::Memoize::Info->new( orig => $func_ref, wrapper => $wrapper, cache => $cache, key_prefix => $prefix ); no strict 'refs'; no warnings 'redefine'; *{$func_name} = $wrapper if $func_name; return $wrapper; } sub memoized { my ( $func_name, $func_ref, $func_id ) = _parse_func_arg( $_[0], scalar(caller) ); return $memoized{$func_id}; } sub unmemoize { my ( $func_name, $func_ref, $func_id ) = _parse_func_arg( $_[0], scalar(caller) ); my $info = $memoized{$func_id} or die "$func_id is not memoized"; eval { $info->cache->clear() }; no strict 'refs'; no warnings 'redefine'; *{$func_name} = $info->orig if $func_name; delete( $memoized{$func_id} ); return $info->orig; } sub _parse_func_arg { my ( $func, $caller ) = @_; my ( $func_name, $func_ref, $func_id ); if ( ref($func) eq 'CODE' ) { $func_ref = $func; $func_id = "$func_ref"; } else { $func_name = $func; $func_name = join( "::", $caller, $func_name ) if $func_name !~ /::/; $func_id = $func_name; no strict 'refs'; $func_ref = \&$func_name; die "no such function '$func_name'" if ref($func_ref) ne 'CODE'; } return ( $func_name, $func_ref, $func_id ); } 1; __END__ =pod =head1 NAME CHI::Memoize - Make functions faster with memoization, via CHI =head1 VERSION version 0.07 =head1 SYNOPSIS use CHI::Memoize qw(:all); # Straight memoization in memory memoize('func'); memoize('Some::Package::func'); # Memoize to a file or to memcached memoize( 'func', driver => 'File', root_dir => '/path/to/cache' ); memoize( 'func', driver => 'Memcached', servers => ["127.0.0.1:11211"] ); # Expire after one hour memoize('func', expires_in => '1h'); # Memoize based on the second and third argument to func memoize('func', key => sub { $_[1], $_[2] }); =head1 DESCRIPTION "`Memoizing' a function makes it faster by trading space for time. It does this by caching the return values of the function in a table. If you call the function again with the same arguments, C jumps in and gives you the value out of the table, instead of letting the function compute the value all over again." -- quoted from the original L For a bit of history and motivation, see http://www.openswartz.com/2012/05/06/memoize-revisiting-a-twelve-year-old-api/ C provides the same facility as L, but backed by L. This means, among other things, that you can =over =item * specify expiration times (L) and conditions (L) =item * memoize to different backends, e.g. L, L, L, or to L =item * handle arbitrarily complex function arguments (via CHI L) =back =head2 FUNCTIONS All of these are importable; only C is imported by default. C will import them all as well as the C constant. =for html =over =item memoize ($func, %options) Creates a new function wrapped around I<$func> that caches results based on passed arguments. I<$func> can be a function name (with or without a package prefix) or an anonymous function. In the former case, the name is rebound to the new function. In either case a code ref to the new wrapper function is returned. # Memoize a named function memoize('func'); memoize('Some::Package::func'); # Memoize an anonymous function $anon = memoize($anon); By default, the cache key is formed from combining the full function name, the calling context ("L" or "S"), and all the function arguments with canonical JSON (sorted hash keys). e.g. these calls will be memoized together: memoized_function({a => 5, b => 6, c => { d => 7, e => 8 }}); memoized_function({b => 6, c => { e => 8, d => 7 }, a => 5}); because the two hashes being passed are canonically the same. But these will be memoized separately because of context: my $scalar = memoized_function(5); my @list = memoized_function(5); By default, the cache L is formed from the full function name or the stringified code reference. This allows you to introspect and clear the memoized results for a particular function. C throws an error if I<$func> is already memoized. See L below for what can go in the options hash. =item memoized ($func) Returns a L object if I<$func> has been memoized, or undef if it has not been memoized. # The CHI cache where memoize results are stored # my $cache = memoized($func)->cache; $cache->clear; # Code references to the original function and to the new wrapped function # my $orig = memoized($func)->orig; my $wrapped = memoized($func)->wrapped; =item unmemoize ($func) Removes the wrapper around I<$func>, restoring it to its original unmemoized state. Also clears the memoize cache if possible (not supported by all drivers, particularly L). Throws an error if I<$func> has not been memoized. memoize('Some::Package::func'); ... unmemoize('Some::Package::func'); =back =head2 OPTIONS The following options can be passed to L. =over =item key Specifies a code reference that takes arguments passed to the function and returns a cache key. The key may be returned as a list, list reference or hash reference; it will automatically be serialized to JSON in canonical mode (sorted hash keys). For example, this uses the second and third argument to the function as a key: memoize('func', key => sub { @_[1..2] }); and this is useful for functions that accept a list of key/value pairs: # Ignore order of key/value pairs memoize('func', key => sub { %@_ }); Regardless of what key you specify, it will automatically be prefixed with the full function name and the calling context ("L" or "S"). If the coderef returns C (or C if you import it), this call won't be memoized. This is useful if you have a cache of limited size or if you know certain arguments will yield nondeterministic results. e.g. memoize('func', key => sub { $is_worth_caching ? @_ : NO_MEMOIZE }); =item set and get options You can pass any of CHI's L options (e.g. L, L) or L options (e.g. L, L). e.g. # Expire after one hour memoize('func', expires_in => '1h'); # Expire when a particular condition occurs memoize('func', expire_if => sub { ... }); =item cache options Any remaining options will be passed to the L to generate the cache: # Store in file instead of memory memoize( 'func', driver => 'File', root_dir => '/path/to/cache' ); # Store in memcached instead of memory memoize('func', driver => 'Memcached', servers => ["127.0.0.1:11211"]); Unless specified, the L is generated from the full name of the function being memoized. You can also specify an existing cache object: # Store in memcached instead of memory my $cache = CHI->new(driver => 'Memcached', servers => ["127.0.0.1:11211"]); memoize('func', cache => $cache); =back =head1 CLONED VS RAW REFERENCES By default C, and thus C, returns a deep clone of the stored value I when caching in memory. e.g. in this code # func returns a list reference memoize('func'); my $ref1 = func(); my $ref2 = func(); C<$ref1> and C<$ref2> will be references to two completely different lists which have the same contained values. More specifically, the value is L by L on C and deserialized (hence cloned) on C. The advantage here is that it is safe to modify a reference returned from a memoized function; your modifications won't affect the cached value. my $ref1 = func(); push(@$ref1, 3, 4, 5); my $ref2 = func(); # $ref2 does not have 3, 4, 5 The disadvantage is that it takes extra time to serialize and deserialize the value, and that some values like code references may be more difficult to store. And cloning may not be what you want at all, e.g. if you are returning objects. Alternatively you can use L, which will store raw references the way C does. Now, however, any modifications to the contents of a returned reference will affect the cached value. memoize('func', driver => 'RawMemory'); my $ref1 = func(); push(@$ref1, 3, 4, 5); my $ref2 = func(); # $ref1 eq $ref2 # $ref2 has 3, 4, 5 =head1 CAVEATS The L apply here as well. To summarize: =over =item * Do not memoize a function whose behavior depends on program state other than its own arguments, unless you explicitly capture that state in your computed key. =item * Do not memoize a function with side effects, as the side effects won't happen on a cache hit. =item * Do not memoize a very simple function, as the costs of caching will outweigh the costs of the function itself. =back =head1 KNOWN BUGS =over =item * Memoizing a function will affect its call stack and its prototype. =back =head1 RELATED MODULES A number of modules address a subset of the problems addressed by this module, including: =over =item * L - pluggable expiration of memoized values =item * L - provides LRU expiration for Memoize =item * L - use a memcached cache to memoize functions =back =head1 SUPPORT Questions and feedback are welcome, and should be directed to the perl-cache mailing list: http://groups.google.com/group/perl-cache-discuss Bugs and feature requests will be tracked at RT: http://rt.cpan.org/NoAuth/Bugs.html?Dist=CHI-Memoize bug-chi-memoize@rt.cpan.org The latest source code can be browsed and fetched at: http://github.com/jonswar/perl-chi-memoize git clone git://github.com/jonswar/perl-chi-memoize.git =head1 SEE ALSO L, L =head1 AUTHOR Jonathan Swartz =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2011 by Jonathan Swartz. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut CHI-Memoize-0.07/LICENSE0000644€ˆž«€q{Ì0000004366612372655464017111 0ustar jonswartANT\Domain UsersThis software is copyright (c) 2011 by Jonathan Swartz. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2011 by Jonathan Swartz. This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2011 by Jonathan Swartz. This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End CHI-Memoize-0.07/Makefile.PL0000644€ˆž«€q{Ì0000000214612372655464020042 0ustar jonswartANT\Domain Users # This file was automatically generated by Dist::Zilla::Plugin::MakeMaker v5.020. use strict; use warnings; use ExtUtils::MakeMaker ; my %WriteMakefileArgs = ( "ABSTRACT" => "Make functions faster with memoization via CHI", "AUTHOR" => "Jonathan Swartz ", "CONFIGURE_REQUIRES" => { "ExtUtils::MakeMaker" => 0 }, "DISTNAME" => "CHI-Memoize", "EXE_FILES" => [], "LICENSE" => "perl", "NAME" => "CHI::Memoize", "PREREQ_PM" => { "CHI" => "0.47", "Hash::MoreUtils" => 0, "Moo" => 0 }, "TEST_REQUIRES" => { "Test::Class::Most" => 0 }, "VERSION" => "0.07", "test" => { "TESTS" => "t/*.t" } ); my %FallbackPrereqs = ( "CHI" => "0.47", "Hash::MoreUtils" => 0, "Moo" => 0, "Test::Class::Most" => 0 ); unless ( eval { ExtUtils::MakeMaker->VERSION(6.63_03) } ) { delete $WriteMakefileArgs{TEST_REQUIRES}; delete $WriteMakefileArgs{BUILD_REQUIRES}; $WriteMakefileArgs{PREREQ_PM} = \%FallbackPrereqs; } delete $WriteMakefileArgs{CONFIGURE_REQUIRES} unless eval { ExtUtils::MakeMaker->VERSION(6.52) }; WriteMakefile(%WriteMakefileArgs); CHI-Memoize-0.07/MANIFEST0000644€ˆž«€q{Ì0000000036112372655464017216 0ustar jonswartANT\Domain Users# This file was automatically generated by Dist::Zilla::Plugin::Manifest v5.020. Changes INSTALL LICENSE MANIFEST META.json META.yml Makefile.PL lib/CHI/Memoize.pm lib/CHI/Memoize/Info.pm lib/CHI/Memoize/t/Memoize.pm t/Memoize.t tidyall.ini CHI-Memoize-0.07/META.json0000644€ˆž«€q{Ì0000000257312372655464017515 0ustar jonswartANT\Domain Users{ "abstract" : "Make functions faster with memoization via CHI", "author" : [ "Jonathan Swartz " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 5.020, CPAN::Meta::Converter version 2.120921", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "CHI-Memoize", "no_index" : { "directory" : [ "lib/CHI/Memoize/t", "lib/CHI/Memoize/Test" ], "file" : [ "lib/CHI/Memoize/Util.pm" ] }, "prereqs" : { "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "CHI" : "0.47", "Hash::MoreUtils" : "0", "Moo" : "0" } }, "test" : { "requires" : { "Test::Class::Most" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "mailto" : "bug-chi-memoize@rt.cpan.org", "web" : "http://rt.cpan.org/NoAuth/Bugs.html?Dist=CHI-Memoize" }, "repository" : { "type" : "git", "url" : "git://github.com/jonswar/perl-chi-memoize.git", "web" : "https://github.com/jonswar/perl-chi-memoize" } }, "version" : "0.07" } CHI-Memoize-0.07/META.yml0000644€ˆž«€q{Ì0000000135312372655464017340 0ustar jonswartANT\Domain Users--- abstract: 'Make functions faster with memoization via CHI' author: - 'Jonathan Swartz ' build_requires: Test::Class::Most: '0' configure_requires: ExtUtils::MakeMaker: '0' dynamic_config: 0 generated_by: 'Dist::Zilla version 5.020, CPAN::Meta::Converter version 2.120921' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: CHI-Memoize no_index: directory: - lib/CHI/Memoize/t - lib/CHI/Memoize/Test file: - lib/CHI/Memoize/Util.pm requires: CHI: '0.47' Hash::MoreUtils: '0' Moo: '0' resources: bugtracker: http://rt.cpan.org/NoAuth/Bugs.html?Dist=CHI-Memoize repository: git://github.com/jonswar/perl-chi-memoize.git version: '0.07' CHI-Memoize-0.07/README0000664€ˆž«€q{Ì0000002271212372655464016753 0ustar jonswartANT\Domain UsersNAME CHI::Memoize - Make functions faster with memoization, via CHI VERSION version 0.07 SYNOPSIS use CHI::Memoize qw(:all); # Straight memoization in memory memoize('func'); memoize('Some::Package::func'); # Memoize to a file or to memcached memoize( 'func', driver => 'File', root_dir => '/path/to/cache' ); memoize( 'func', driver => 'Memcached', servers => ["127.0.0.1:11211"] ); # Expire after one hour memoize('func', expires_in => '1h'); # Memoize based on the second and third argument to func memoize('func', key => sub { $_[1], $_[2] }); DESCRIPTION "`Memoizing' a function makes it faster by trading space for time. It does this by caching the return values of the function in a table. If you call the function again with the same arguments, `memoize' jumps in and gives you the value out of the table, instead of letting the function compute the value all over again." -- quoted from the original Memoize For a bit of history and motivation, see http://www.openswartz.com/2012/05/06/memoize-revisiting-a-twelve-year-old-api/ `CHI::Memoize' provides the same facility as Memoize, but backed by CHI. This means, among other things, that you can * specify expiration times (expires_in) and conditions (expire_if) * memoize to different backends, e.g. File, Memcached, DBI, or to multilevel caches * handle arbitrarily complex function arguments (via CHI key serialization) FUNCTIONS All of these are importable; only `memoize' is imported by default. `use Memoize qw(:all)' will import them all as well as the `NO_MEMOIZE' constant. memoize ($func, %options) Creates a new function wrapped around *$func* that caches results based on passed arguments. *$func* can be a function name (with or without a package prefix) or an anonymous function. In the former case, the name is rebound to the new function. In either case a code ref to the new wrapper function is returned. # Memoize a named function memoize('func'); memoize('Some::Package::func'); # Memoize an anonymous function $anon = memoize($anon); By default, the cache key is formed from combining the full function name, the calling context ("L" or "S"), and all the function arguments with canonical JSON (sorted hash keys). e.g. these calls will be memoized together: memoized_function({a => 5, b => 6, c => { d => 7, e => 8 }}); memoized_function({b => 6, c => { e => 8, d => 7 }, a => 5}); because the two hashes being passed are canonically the same. But these will be memoized separately because of context: my $scalar = memoized_function(5); my @list = memoized_function(5); By default, the cache namespace is formed from the full function name or the stringified code reference. This allows you to introspect and clear the memoized results for a particular function. `memoize' throws an error if *$func* is already memoized. See OPTIONS below for what can go in the options hash. memoized ($func) Returns a CHI::Memoize::Info object if *$func* has been memoized, or undef if it has not been memoized. # The CHI cache where memoize results are stored # my $cache = memoized($func)->cache; $cache->clear; # Code references to the original function and to the new wrapped function # my $orig = memoized($func)->orig; my $wrapped = memoized($func)->wrapped; unmemoize ($func) Removes the wrapper around *$func*, restoring it to its original unmemoized state. Also clears the memoize cache if possible (not supported by all drivers, particularly memcached). Throws an error if *$func* has not been memoized. memoize('Some::Package::func'); ... unmemoize('Some::Package::func'); OPTIONS The following options can be passed to memoize. key Specifies a code reference that takes arguments passed to the function and returns a cache key. The key may be returned as a list, list reference or hash reference; it will automatically be serialized to JSON in canonical mode (sorted hash keys). For example, this uses the second and third argument to the function as a key: memoize('func', key => sub { @_[1..2] }); and this is useful for functions that accept a list of key/value pairs: # Ignore order of key/value pairs memoize('func', key => sub { %@_ }); Regardless of what key you specify, it will automatically be prefixed with the full function name and the calling context ("L" or "S"). If the coderef returns `CHI::Memoize::NO_MEMOIZE' (or `NO_MEMOIZE' if you import it), this call won't be memoized. This is useful if you have a cache of limited size or if you know certain arguments will yield nondeterministic results. e.g. memoize('func', key => sub { $is_worth_caching ? @_ : NO_MEMOIZE }); set and get options You can pass any of CHI's set options (e.g. expires_in, expires_variance) or get options (e.g. expire_if, busy_lock). e.g. # Expire after one hour memoize('func', expires_in => '1h'); # Expire when a particular condition occurs memoize('func', expire_if => sub { ... }); cache options Any remaining options will be passed to the CHI constructor to generate the cache: # Store in file instead of memory memoize( 'func', driver => 'File', root_dir => '/path/to/cache' ); # Store in memcached instead of memory memoize('func', driver => 'Memcached', servers => ["127.0.0.1:11211"]); Unless specified, the namespace is generated from the full name of the function being memoized. You can also specify an existing cache object: # Store in memcached instead of memory my $cache = CHI->new(driver => 'Memcached', servers => ["127.0.0.1:11211"]); memoize('func', cache => $cache); CLONED VS RAW REFERENCES By default `CHI', and thus `CHI::Memoize', returns a deep clone of the stored value *even* when caching in memory. e.g. in this code # func returns a list reference memoize('func'); my $ref1 = func(); my $ref2 = func(); `$ref1' and `$ref2' will be references to two completely different lists which have the same contained values. More specifically, the value is serialized by Storable on `set' and deserialized (hence cloned) on `get'. The advantage here is that it is safe to modify a reference returned from a memoized function; your modifications won't affect the cached value. my $ref1 = func(); push(@$ref1, 3, 4, 5); my $ref2 = func(); # $ref2 does not have 3, 4, 5 The disadvantage is that it takes extra time to serialize and deserialize the value, and that some values like code references may be more difficult to store. And cloning may not be what you want at all, e.g. if you are returning objects. Alternatively you can use CHI::Driver::RawMemory, which will store raw references the way `Memoize' does. Now, however, any modifications to the contents of a returned reference will affect the cached value. memoize('func', driver => 'RawMemory'); my $ref1 = func(); push(@$ref1, 3, 4, 5); my $ref2 = func(); # $ref1 eq $ref2 # $ref2 has 3, 4, 5 CAVEATS The caveats of Memoize apply here as well. To summarize: * Do not memoize a function whose behavior depends on program state other than its own arguments, unless you explicitly capture that state in your computed key. * Do not memoize a function with side effects, as the side effects won't happen on a cache hit. * Do not memoize a very simple function, as the costs of caching will outweigh the costs of the function itself. KNOWN BUGS * Memoizing a function will affect its call stack and its prototype. RELATED MODULES A number of modules address a subset of the problems addressed by this module, including: * Memoize::Expire - pluggable expiration of memoized values * Memoize::ExpireLRU - provides LRU expiration for Memoize * Memoize::Memcached - use a memcached cache to memoize functions SUPPORT Questions and feedback are welcome, and should be directed to the perl-cache mailing list: http://groups.google.com/group/perl-cache-discuss Bugs and feature requests will be tracked at RT: http://rt.cpan.org/NoAuth/Bugs.html?Dist=CHI-Memoize bug-chi-memoize@rt.cpan.org The latest source code can be browsed and fetched at: http://github.com/jonswar/perl-chi-memoize git clone git://github.com/jonswar/perl-chi-memoize.git SEE ALSO CHI, Memoize AUTHOR Jonathan Swartz COPYRIGHT AND LICENSE This software is copyright (c) 2011 by Jonathan Swartz. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. CHI-Memoize-0.07/t/0000775€ˆž«€q{Ì0000000000012372655464016332 5ustar jonswartANT\Domain UsersCHI-Memoize-0.07/t/Memoize.t0000644€ˆž«€q{Ì0000000011412372655464020116 0ustar jonswartANT\Domain Users#!perl -w use CHI::Memoize::t::Memoize; CHI::Memoize::t::Memoize->runtests; CHI-Memoize-0.07/tidyall.ini0000644€ˆž«€q{Ì0000000031012372655464020222 0ustar jonswartANT\Domain Users[PerlTidy] argv = -noll -l=100 select = {bin,lib,t}/**/{tidyall,*.{pl,pm,t}} [PodTidy] select = {bin,lib}/**/{tidyall,*.{pl,pm,pod}} [Perl::AlignMooseAttributes] select = {bin,lib,t}/**/*.{pl,pm,t}