Skip to content

Instantly share code, notes, and snippets.

@baragona
Created December 16, 2014 02:59
Show Gist options
  • Save baragona/3c9c937df00d058e065a to your computer and use it in GitHub Desktop.
Save baragona/3c9c937df00d058e065a to your computer and use it in GitHub Desktop.
Stream Cache - Flexible moving window buffer any objects
package stream_cache;
use strict;
use warnings;
sub new{
my $get_next_chunk_data = shift;
my $next_chunk_id = shift;
$next_chunk_id = 0 unless $next_chunk_id;
return {
stored_chunks=>{},
oldest_stored_chunk=>undef,
next_chunk_id => 0,
get_next_chunk_data=>$get_next_chunk_data,
};
}
sub get_chunk {
my $self=shift;
my $chunk_id =shift;
if($chunk_id == $self->{next_chunk_id}){
my $chunk_data = $self->{get_next_chunk_data}->();
$self->{next_chunk_id}++;
$self->{stored_chunks}{$chunk_id}=$chunk_data;
$self->{oldest_stored_chunk}=$chunk_id if !defined($self->{oldest_stored_chunk});
return $chunk_data;
}
if(exists $self->{stored_chunks}{$chunk_id}){
return $self->{stored_chunks}{$chunk_id};
}
if($chunk_id > $self->{next_chunk_id}){
warn "uhh, are you asking me to skip a chunk???";
return undef;
}
if($chunk_id < $self->{oldest_stored_chunk}){
warn "uhh you are asking for a chunk I already deleted, wtf?";
return undef;
}
warn "I have no explaination for why I can't provide you with the chunk. I just can't";
return undef;
}
sub calc_oldest_stored_chunk{
my $self=shift;
$self->{oldest_stored_chunk} = undef;
my @chunkids = keys %{$self->{stored_chunks}};
if(@chunkids){
@chunkids = sort {$a <=> $b} @chunkids;
$self->{oldest_stored_chunk} = $chunkids[0];
}
}
sub delete_chunks_older_than {
my $self = shift;
my $chunk_id = shift;
for my $old_id( keys %{$self->{stored_chunks}}){
delete $self->{stored_chunks}{$old_id} if $old_id < $chunk_id;
}
calc_oldest_stored_chunk();
}
sub rewind{
my $self=shift;
my $new_next_id=shift;
for my $old_id( keys %{$self->{stored_chunks}}){
delete $self->{stored_chunks}{$old_id} if $old_id >= $new_next_id;
}
calc_oldest_stored_chunk();
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment