Skip to content

Instantly share code, notes, and snippets.

@moritz
Created September 21, 2011 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moritz/1233070 to your computer and use it in GitHub Desktop.
Save moritz/1233070 to your computer and use it in GitHub Desktop.
Fake Buf (Buf8) class, should be quite memory efficient
class Buf8 {
has Mu $!buffer;
method BUILD() {
$!buffer := pir::new__PS('ByteBuffer');
1;
}
method new(*@codes) {
my $new := self.bless(*);
$new.set_codes(@codes);
$new;
}
method set_codes(*@codes) {
pir::set__vPI($!buffer, nqp::unbox_i(@codes.elems));
for @codes.keys -> $k {
pir::set__1Qii($!buffer, nqp::unbox_i($k), nqp::unbox_i(@codes[$k]));
}
self;
}
method list() {
my @l;
for ^nqp::p6box_i(nqp::elems($!buffer)) -> $k {
@l.push: nqp::p6box_i(pir::set__IQi($!buffer, nqp::unbox_i($k)));
}
@l;
}
method decode(Str:D $encoding = 'utf8') {
nqp::p6box_s $!buffer.get_string(
nqp::unbox_s pir::perl6_decontainerize__PP($encoding)
);
}
}
use MONKEY_TYPING;
augment class Str {
method encode(Str:D $encoding = 'utf8') {
my $buf := Buf8.new;
pir::set__vPs(nqp::getattr($buf, Buf8, '$!buffer'),
pir::trans_encoding__ssi(
nqp::unbox_s(self),
pir::find_encoding__is(nqp::unbox_s(pir::perl6_decontainerize__PP($encoding)))
)
);
$buf;
}
}
my $x = 'foo'.encode('utf8');
say $x.list;
say 'bar'.encode.decode;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment