| 1 | #======================================================================== | ||
| 2 | # | ||
| 3 | # Badger::Codec::Unicode | ||
| 4 | # | ||
| 5 | # DESCRIPTION | ||
| 6 | # Codec module for encoding/decoding Unicode via Encode | ||
| 7 | # | ||
| 8 | # AUTHOR | ||
| 9 | # Andy Wardley <abw@wardley.org> | ||
| 10 | # | ||
| 11 | #======================================================================== | ||
| 12 | |||
| 13 | package Badger::Codec::Unicode; | ||
| 14 | |||
| 15 | use 5.008; # Unicode not fully supported prior to 5.8 | ||
| 16 | use Badger::Class | ||
| 17 | version => 0.01, | ||
| 18 | base => 'Badger::Codec::Encode'; | ||
| 19 | |||
| 20 | use Encode qw(); | ||
| 21 | use bytes; | ||
| 22 | |||
| 23 | # Default encoding | ||
| 24 | our $ENCODING = 'UTF-8'; | ||
| 25 | |||
| 26 | # Byte Order Markers for different UTF encodings | ||
| 27 | our $UTFBOMS = [ | ||
| 28 | 'UTF-8' => "\x{ef}\x{bb}\x{bf}", | ||
| 29 | 'UTF-32BE' => "\x{0}\x{0}\x{fe}\x{ff}", | ||
| 30 | 'UTF-32LE' => "\x{ff}\x{fe}\x{0}\x{0}", | ||
| 31 | 'UTF-16BE' => "\x{fe}\x{ff}", | ||
| 32 | 'UTF-16LE' => "\x{ff}\x{fe}", | ||
| 33 | ]; | ||
| 34 | |||
| 35 | sub encode { | ||
| 36 | my ($self, $enc, $data) = @_ == 3 ? @_ : (shift, $ENCODING, shift); | ||
| 37 | Encode::encode($enc, $data); | ||
| 38 | } | ||
| 39 | |||
| 40 | sub decode { | ||
| 41 | my $self = shift; | ||
| 42 | if (@_ >= 2) { | ||
| 43 | goto &Encode::decode; # not a real GOTO - more like a magic | ||
| 44 | } # subroutine call - see perldoc -f goto | ||
| 45 | else { | ||
| 46 | my $data = shift; | ||
| 47 | my $count = 0; | ||
| 48 | |||
| 49 | # try all the BOMs in order looking for one (order is important | ||
| 50 | # 32bit BOMs look like 16bit BOMs) | ||
| 51 | while ($count < @$UTFBOMS) { | ||
| 52 | my $enc = $UTFBOMS->[$count++]; | ||
| 53 | my $bom = $UTFBOMS->[$count++]; | ||
| 54 | |||
| 55 | # does the string start with the bom? | ||
| 56 | if ($bom eq substr($data, 0, length($bom))) { | ||
| 57 | # decode it and hand it back | ||
| 58 | # return Encode::decode($enc, $data); | ||
| 59 | return Encode::decode($enc, substr($data, length($bom)), 1); | ||
| 60 | } | ||
| 61 | } | ||
| 62 | return $data; | ||
| 63 | } | ||
| 64 | } | ||
| 65 | |||
| 66 | sub encoder { | ||
| 67 | my $self = shift; | ||
| 68 | return sub { $self->encode(@_) }; | ||
| 69 | } | ||
| 70 | |||
| 71 | sub decoder { | ||
| 72 | my $self = shift; | ||
| 73 | return sub { $self->decode(@_) }; | ||
| 74 | } | ||
| 75 | |||
| 76 | 1; | ||
| 77 | |||
| 78 | __END__ |