| 1 | #======================================================================== | ||
| 2 | # | ||
| 3 | # Badger::Codec::Encoding | ||
| 4 | # | ||
| 5 | # DESCRIPTION | ||
| 6 | # A codec wrapper for Encode that binds a specific encoding with it. | ||
| 7 | # | ||
| 8 | # AUTHOR | ||
| 9 | # Andy Wardley <abw@wardley.org> | ||
| 10 | # | ||
| 11 | #======================================================================== | ||
| 12 | |||
| 13 | package Badger::Codec::Encoding; | ||
| 14 | |||
| 15 | use Badger::Class | ||
| 16 | version => 0.01, | ||
| 17 | debug => 0, | ||
| 18 | base => 'Badger::Codec', | ||
| 19 | import => 'class', | ||
| 20 | constants => 'PKG', | ||
| 21 | constant => { | ||
| 22 | encoding => 'ASCII', | ||
| 23 | }; | ||
| 24 | |||
| 25 | use Encode qw(); | ||
| 26 | use bytes; | ||
| 27 | |||
| 28 | sub encode { | ||
| 29 | # replace $self with $self->encoding | ||
| 30 | unshift(@_, shift->encoding); | ||
| 31 | # you don't need to turn away, this isn't your average GOTO - it's a | ||
| 32 | # special kind of subroutine call that Larry called goto for a laugh | ||
| 33 | goto &Encode::encode; | ||
| 34 | } | ||
| 35 | |||
| 36 | sub decode { | ||
| 37 | # as above: monkey with the args so the goto works as expected | ||
| 38 | unshift(@_, shift->encoding); | ||
| 39 | goto &Encode::decode; | ||
| 40 | } | ||
| 41 | |||
| 42 | sub encoder { | ||
| 43 | my $self = shift; | ||
| 44 | my $enc = $self->encoding; | ||
| 45 | return sub { | ||
| 46 | unshift(@_, $enc); | ||
| 47 | goto &Encode::encode | ||
| 48 | }; | ||
| 49 | } | ||
| 50 | |||
| 51 | sub decoder { | ||
| 52 | my $self = shift; | ||
| 53 | my $enc = $self->encoding; | ||
| 54 | return sub { | ||
| 55 | unshift(@_, $enc); | ||
| 56 | goto &Encode::decode | ||
| 57 | }; | ||
| 58 | } | ||
| 59 | |||
| 60 | |||
| 61 | #----------------------------------------------------------------------- | ||
| 62 | # generate subclasses for various UTF encodings | ||
| 63 | #----------------------------------------------------------------------- | ||
| 64 | |||
| 65 | my $base = __PACKAGE__; | ||
| 66 | my @encs = qw( utf8 UTF-8 UTF-16BE UTF-16LE UTF-32BE UTF-32LE ); | ||
| 67 | |||
| 68 | for my $enc (@encs) { | ||
| 69 | my $name = $enc; | ||
| 70 | $name =~ s/\W//g; | ||
| 71 | |||
| 72 | # fetch a Badger::Class object for the subclass so we can define | ||
| 73 | # a base class and set the constant encoding() method | ||
| 74 | my $subclass = class($base.PKG.$name); | ||
| 75 | $subclass->base($base); | ||
| 76 | $subclass->constant( encoding => $enc ); | ||
| 77 | |||
| 78 | $base->debug("$name => $enc => ", $subclass->name->encoding, "\n") if $DEBUG; | ||
| 79 | } | ||
| 80 | 1; | ||
| 81 | |||
| 82 | |||
| 83 | __END__ |