Skip to content

Instantly share code, notes, and snippets.

@dakkar
Created December 19, 2018 17:01
Show Gist options
  • Save dakkar/61d21407c898488e4d5daeb5cd1211f5 to your computer and use it in GitHub Desktop.
Save dakkar/61d21407c898488e4d5daeb5cd1211f5 to your computer and use it in GitHub Desktop.
vague idea to use nqp::serialize
use v6.d.PREVIEW;
# copied from https://github.com/FROGGS/p6-Ser/blob/master/lib/Ser.pm
sub serialize($obj is copy) {
use MONKEY-GUTS;
my Mu $sh := nqp::list_s();
my $name = 'Ser_' ~ nqp::time_n();
my Mu $sc := nqp::createsc(nqp::unbox_s($name));
nqp::setobjsc($obj, $sc);
nqp::scsetobj($sc, 0, $obj);
my $serialized := nqp::serialize($sc, $sh);
nqp::scdisclaim($sc);
nqp::shift_s($sh); # shift an initial null
nqp::unshift_s($sh,nqp::unbox_s($name));
nqp::push_s($sh,$serialized);
nqp::p6box_s(nqp::join("\0", $sh));
}
sub deserialize($b64) {
use MONKEY-GUTS;
my Mu $sh := nqp::list_s();
my @lines = $b64.split("\0");
my str $name = nqp::unbox_s(@lines.shift);
my str $serialized = nqp::unbox_s(@lines.pop);
nqp::push_s($sh, nqp::null_s());
nqp::push_s($sh, nqp::unbox_s($_)) for @lines;
my Mu $sc := nqp::createsc(nqp::unbox_s($name));
nqp::deserialize($serialized, $sc, $sh, nqp::list(), nqp::null());
my Mu $obj := nqp::scgetobj($sc, 0);
nqp::scdisclaim($sc);
$obj
}
my $x = %(
"a\nb" => "some\ndata",
foo => [1,2,3],
bar => %( :1x, :2y ),
);
dd $x;
my $serialized = serialize($x);
#say $serialized.indent(4);
my $y = deserialize($serialized);
dd $y;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment