Skip to content

Commit

Permalink
Fix non-simple integer initialization
Browse files Browse the repository at this point in the history
  • Loading branch information
Altai-man committed Feb 8, 2021
1 parent dc724ee commit 2078519
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 12 deletions.
32 changes: 21 additions & 11 deletions lib/ASN/Serializer.pm6
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,29 @@ class ASN::Serializer {
# INTEGER
multi method serialize(Int $int is copy where $int.HOW ~~ Metamodel::ClassHOW, Int $index = 2, :$debug, :$mode) {
my $int-encoded = Buf.new;
my $bit-shift-value = 0;
my $bit-shift-mask = 0xff;
loop {
my $byte = $int +& $bit-shift-mask +> $bit-shift-value;
if $byte == 0 {
$int-encoded.append(0) if $int-encoded.elems == 0;
last;
my ($is-neg, $limit);
if $is-neg = $int < 0 {
$int = -$int;
$limit = 0x80;
} else {
$limit = 0x7F;
}

while $int > $limit {
$int-encoded.append($int +& 0xFF);
$int +>= 8;
}
$int-encoded.append($int +& 0xFF);

if $is-neg {
$int-encoded = Buf.new($int-encoded.map(0xFF - *));
for $int-encoded.kv -> $i, $v {
$int-encoded[$i] += 1;
last if $int-encoded[$i] <= 0xFF;
$int-encoded[$i] = 0x0;
}
$int-encoded.append($byte);
# Update operands
$bit-shift-value += 8;
$bit-shift-mask +<= 8;
}
$int-encoded.append(0xFF) if $is-neg && $int-encoded[* - 1] == 0x7F;

say "Encoding Int ($int) with index $index, resulting in $int-encoded.reverse().perl()" if $debug;
self!pack($index, $int-encoded.reverse);
Expand Down
11 changes: 10 additions & 1 deletion t/03-long-integers.t
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@ is ASN::Parser.parse($buf, Int), -128, 'Parsing of a padded negative value works

use ASN::Serializer;

say ASN::Serializer.serialize(127);
my @nums = 0, 127, 128, 256, -128, -129;
my @results = (Buf.new(0x02, 0x01, 0x00), Buf.new(0x02, 0x01, 0x7F),
Buf.new(0x02, 0x02, 0x00, 0x80),
Buf.new(0x02, 0x02, 0x01, 0x00),
Buf.new(0x02, 0x01, 0x80),
Buf.new(0x02, 0x02, 0xFF, 0x7F));

for @nums Z @results {
is-deeply $_[1], ASN::Serializer.serialize($_[0]), "Can serialize $_[0].raku() into $_[1].raku()";
}

done-testing;

0 comments on commit 2078519

Please sign in to comment.