Iterator-Flex

 view release on metacpan or  search on metacpan

lib/Iterator/Flex/Cache.pm  view on Meta::CPAN

package Iterator::Flex::Cache;

# ABSTRACT: Cache Iterator Class

use v5.28;
use strict;
use warnings;
use experimental qw( signatures postderef );

our $VERSION = '0.34';

use parent 'Iterator::Flex::Base';
use Iterator::Flex::Utils qw( STATE :IterAttrs :IterStates throw_failure );
use Iterator::Flex::Factory 'to_iterator';
use Scalar::Util;
use Ref::Util;

use namespace::clean;










































sub new ( $class, $iterable, $pars = {} ) {

    throw_failure( parameter => 'q{pars} argument must be a hash' )
      unless Ref::Util::is_hashref( $pars );

    my %pars = $pars->%*;

    my $capacity = delete $pars{capacity} // 2;
    Scalar::Util::looks_like_number( $capacity ) && int( $capacity ) == $capacity && $capacity > 0
      or throw_failure( parameter => "parameter 'capacity' ($capacity) is not a positive integer" );

    $class->SUPER::new( {
            capacity => $capacity,
            depends  => [ to_iterator( $iterable ) ],
        },
        \%pars,
    );
}










sub construct ( $class, $state ) {

    throw_failure( parameter => q{state must be a HASH reference} )
      unless Ref::Util::is_hashref( $state );

    my ( $src, $capacity, $idx, $cache ) = @{$state}{qw[ depends capacity idx cache ]};
    $src = $src->[0];
    $idx   //= -1;
    $cache //= [];

    my $self;
    my $is_exhausted = $src->can( 'is_exhausted' );
    my $iterator_state;

    return {

        ( +_SELF ) => \$self,

        ( +STATE ) => \$iterator_state,

        ( +RESET ) => sub {
            $idx = -1;
            @{$cache} = ();
        },

        ( +REWIND ) => sub {
        },

        ( +PREV ) => sub {
            return defined $idx ? $cache->[ ( $idx - 1 ) % $capacity ] : undef;
        },

        ( +CURRENT ) => sub {
            return defined $idx ? $cache->[ $idx % $capacity ] : undef;
        },

        ( +NEXT ) => sub {

            return $self->signal_exhaustion
              if $iterator_state == IterState_EXHAUSTED;

            $idx = ++$idx % $capacity;
            my $current = $cache->[$idx] = $src->();

            return $self->signal_exhaustion
              if $src->$is_exhausted;

            return $current;
        },

        ( +METHODS ) => {
            at => sub ( $, $at ) {
                $cache->[ ( $idx - $at ) % $capacity ];
            },
        },

        ( +FREEZE ) => sub {
            return [ $class, { idx => $idx, capacity => $capacity, cache => $cache } ];
        },

        ( +_DEPENDS ) => $src,
    };
}



( run in 0.576 second using v1.01-cache-2.11-cpan-6aa56a78535 )