| 1 | # | ||
| 2 | # $Id$ | ||
| 3 | # | ||
| 4 | # string::hexa Brik | ||
| 5 | # | ||
| 6 | package Metabrik::String::Hexa; | ||
| 7 | 1 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 8 | 1 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 9 | |||
| 10 | 1 | ▶ | use base qw(Metabrik); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 11 | |||
| 12 | sub brik_properties { | ||
| 13 | return { | ||
| 14 | revision => '$Revision$', | ||
| 15 | tags => [ qw(unstable encode decode hex) ], | ||
| 16 | author => 'GomoR <GomoR[at]metabrik.org>', | ||
| 17 | license => 'http://opensource.org/licenses/BSD-3-Clause', | ||
| 18 | attributes => { | ||
| 19 | with_x => [ ], | ||
| 20 | }, | ||
| 21 | attributes_default => { | ||
| 22 | with_x => 1, | ||
| 23 | }, | ||
| 24 | commands => { | ||
| 25 | encode => [ qw($data) ], | ||
| 26 | decode => [ qw($data) ], | ||
| 27 | is_hexa => [ qw($data) ], | ||
| 28 | }, | ||
| 29 | require_modules => { | ||
| 30 | 'MIME::Base64' => [ ], | ||
| 31 | }, | ||
| 32 | }; | ||
| 33 | } | ||
| 34 | |||
| 35 | sub encode { | ||
| 36 | my $self = shift; | ||
| 37 | my ($data) = @_; | ||
| 38 | |||
| 39 | $self->brik_help_run_undef_arg('encode', $data) or return; | ||
| 40 | |||
| 41 | my $encoded = unpack('H*', $data); | ||
| 42 | |||
| 43 | if ($self->with_x) { | ||
| 44 | $encoded =~ s/(..)/\\x$1/g; | ||
| 45 | } | ||
| 46 | |||
| 47 | return $encoded; | ||
| 48 | } | ||
| 49 | |||
| 50 | sub decode { | ||
| 51 | my $self = shift; | ||
| 52 | my ($data) = @_; | ||
| 53 | |||
| 54 | $self->brik_help_run_undef_arg('decode', $data) or return; | ||
| 55 | |||
| 56 | # Keep only hex-compliant characters | ||
| 57 | $data =~ s/[^a-fA-F0-9]//g; | ||
| 58 | |||
| 59 | my $decoded = pack('H*', $data); | ||
| 60 | |||
| 61 | return $decoded; | ||
| 62 | } | ||
| 63 | |||
| 64 | sub is_hexa { | ||
| 65 | my $self = shift; | ||
| 66 | my ($data) = @_; | ||
| 67 | |||
| 68 | my $this = lc($data); | ||
| 69 | $this =~ s/\\x//g; | ||
| 70 | |||
| 71 | if ($this =~ /^[a-f0-9]+$/) { | ||
| 72 | return 1; | ||
| 73 | } | ||
| 74 | |||
| 75 | return 0; | ||
| 76 | } | ||
| 77 | |||
| 78 | 1; | ||
| 79 | |||
| 80 | __END__ | ||