Created
December 3, 2012 20:08
-
-
Save benvanstaveren/4197629 to your computer and use it in GitHub Desktop.
perl implementation of mc3p's Stream class (well, most of it)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Halcyon::Buffer; | |
use Mojo::Base '-base'; | |
# a reimplementation of mc3p's Stream class, of sorts | |
has 'raw' => ''; | |
has 'i' => 0; | |
has 'tot_bytes' => 0; | |
has 'wasted_bytes' => 0; | |
sub append { | |
my $self = shift; | |
my $data = shift; | |
if(defined($self->raw)) { | |
$self->raw($self->raw . $data); | |
} else { | |
$self->raw($data); | |
} | |
} | |
sub length { | |
my $self = shift; | |
return CORE::length($self->raw); | |
} | |
sub read { | |
my $self = shift; | |
my $n = shift; | |
if($self->i + $n > $self->length) { | |
$self->wasted_bytes($self->wasted_bytes + $self->i); | |
$self->i(0); | |
die 'PartialPacketException', "\n"; | |
} | |
my $str = substr($self->raw, $self->i, $n); | |
$self->i($self->i + $n); | |
return $str; | |
} | |
sub reset { shift->i(0) } | |
sub packet_finished { | |
my $self = shift; | |
my $data = ''; | |
if($self->i > 0) { | |
$data = substr($self->raw, 0, $self->i); | |
$self->raw(substr($self->raw, $self->i)); | |
$self->tot_bytes($self->tot_bytes + $self->i); | |
$self->i(0); | |
} | |
return $data; | |
} | |
1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment