Absolute hinky bare-bones implementation of multiformats in Perl
at main 121 lines 2.7 kB view raw
1package 2 Multiformats::Multicodec { 3 use strict; 4 use warnings; 5 use feature 'signatures'; 6 use Multiformats::Varint qw/varint_decode_raw varint_encode/; 7 8 use Exporter 'import'; 9 our @EXPORT_OK = qw/multicodec_wrap multicodec_unwrap multicodec_get_codec/; 10 11 use constant MULTICODEC_MAP => [ 12 [ 'raw', 0x55 ], 13 [ 'dag-cbor', 0x71 ], 14 ]; 15 16 sub wrap($self, $as, $value) { 17 return multihash_wrap($as, $value); 18 } 19 20 sub unwrap($self, $value) { 21 return multihash_unwrap($value); 22 } 23 24 sub get_codec($self, $value) { 25 return multihash_codec($value); 26 } 27 28 sub new($pkg) { 29 return bless({}, $pkg); 30 } 31 32 sub _get_by_name($as) { 33 foreach my $entry (@{__PACKAGE__->MULTICODEC_MAP}) { 34 return $entry if($entry->[0] eq $as); 35 } 36 return _get_by_tag($as); 37 } 38 39 sub _get_by_tag($tag) { 40 foreach my $entry (@{__PACKAGE__->MULTICODEC_MAP}) { 41 return $entry if($entry->[1] == $tag); 42 } 43 return undef; 44 } 45 46 sub multicodec_wrap($as, $value) { 47 utf8::downgrade($value, 1); 48 if(my $e = _get_by_name($as)) { 49 my $id = varint_encode($e->[1]); 50 return $id . $value; 51 } else { 52 die 'Unsupported multicodec type ', $as, ', '; 53 } 54 } 55 56 sub multicodec_unwrap($value) { 57 utf8::downgrade($value, 1); 58 my ($id, $bytes) = varint_decode_raw($value); 59 return substr($value, $bytes); 60 61 } 62 63 sub multicodec_get_codec($value) { 64 utf8::downgrade($value, 1); 65 my ($id, $bytes) = varint_decode_raw($value); 66 if(my $e = _get_by_tag($id)) { 67 return $e; 68 } else { 69 die 'Unsupported multicodec type ', $id, ', '; 70 } 71 } 72} 73 74=pod 75 76=head1 NAME 77 78Multiformats::Multicodec - Multicodec encoding/decoding/wrapping 79 80=head1 SYNOPSIS 81 82 use Multiformats::Multicodec qw/multicodec_get_codec multicodec_unwrap multicodec_wrap/; 83 84 my $data = '...'; 85 86 my $encoded = multicodec_wrap('dag-cbor', $data); 87 my $decoded = multicodec_unwrap($encoded); 88 89 my $codec = multicodec_get_codec($encoded); 90 91 $codec->[0]; # dag-cbor 92 $codec->[1]; # 0x71 93 94 95=head1 FUNCTIONS 96 97=head2 multicodec_wrap($codec, $data); 98 99Wraps the given data with the proper multicodec tag 100 101=head2 multicodec_unwrap($data) 102 103Unwraps the given data and returns the original raw data 104 105=head2 multicodec_get_codec($data) 106 107Returns an arrayref containing the codec information that the data is encoded with. First item in the arrayref is the codec name, second item is the codec tag value. 108 109=head1 SUPPORTED CODECS 110 111=over 112 113=item * raw 114 115=item * dag-cbor 116 117=back 118 119=cut 120 1211;