Showing off long ears
In the previous post, we have encountered some kind of special elves’ magic:
enum Fuel <Solid Liquid Gas>;
class SpeedChoice does ASNChoice {
method ASN-choice { { mph => (1 => Int), kmph => (0 => Int) } }
}
class Rocket does ASNSequence {
has Str $.name is UTF8String;
has Str $.message is default-value("Hello World") is UTF8String;
has Fuel $.fuel;
has SpeedChoice $.speed is optional;
has Str @.payload is UTF8String;
method ASN-order { <$!name $!message $!fuel $!speed @!payload> }
}
my $rocket = Rocket.new(
name => 'Falcon',
fuel => Solid,
speed => SpeedChoice.new((mph => 18000)),
payload => [ "Car", "GPS" ]);
my $rocket-bytes = ASN::Serializer.serialize($rocket, :mode(Implicit));
#`[ Result:
Blob.new(
0x30, 0x1B, # Outermost SEQUENCE
0x0C, 0x06, 0x46, 0x61, 0x6C, 0x63, 0x6F, 0x6E, # NAME, MESSAGE is missing
0x0A, 0x01, 0x00, # ENUMERATED
0x81, 0x02, 0x46, 0x50, # CHOICE
0x30, 0x0A, # SEQUENCE OF UTF8String
0x0C, 0x03, 0x43, 0x61, 0x72, # UTF8String
0x0C, 0x03, 0x47, 0x50, 0x53); # UTF8String
]
say ASN::Parser.new(:type(Rocket)).parse($rocket-bytes) eqv $rocket; # Certainly true!
However, as an elf I know once quoted, ‘It’s hard to tell the difference between mastered technique and magic’. So the mystery can be resolved? Let’s glance over the way it all works.
Continue reading “Day 15 – Building a (little) Spacecraft with Perl 6”