65ef50b0689224da674eab6119f723c86d613d4f
[p5sagit/p5-mst-13.2.git] / ext / Encode / Encode.pm
1 package Encode;
2 use strict;
3 our $VERSION = do { my @r = (q$Revision: 1.60 $ =~ /\d+/g); sprintf "%d."."%02d" x $#r, @r };
4 our $DEBUG = 0;
5 use XSLoader ();
6 XSLoader::load 'Encode';
7
8 require Exporter;
9 our @ISA = qw(Exporter);
10
11 # Public, encouraged API is exported by default
12
13 our @EXPORT = qw(
14   decode  decode_utf8  encode  encode_utf8
15   encodings  find_encoding
16 );
17
18 our @FB_FLAGS  = qw(DIE_ON_ERR WARN_ON_ERR RETURN_ON_ERR LEAVE_SRC 
19                     PERLQQ HTMLCREF XMLCREF);
20 our @FB_CONSTS = qw(FB_DEFAULT FB_CROAK FB_QUIET FB_WARN 
21                     FB_PERLQQ FB_HTMLCREF FB_XMLCREF);
22
23 our @EXPORT_OK =
24     (
25      qw(
26        _utf8_off _utf8_on define_encoding from_to is_16bit is_8bit
27        is_utf8 perlio_ok resolve_alias utf8_downgrade utf8_upgrade
28       ),
29      @FB_FLAGS, @FB_CONSTS,
30     );
31
32 our %EXPORT_TAGS =
33     (
34      all          =>  [ @EXPORT, @EXPORT_OK ],
35      fallbacks    =>  [ @FB_CONSTS ],
36      fallback_all =>  [ @FB_CONSTS, @FB_FLAGS ],
37     );
38
39 # Documentation moved after __END__ for speed - NI-S
40
41 use Carp;
42
43 our $ON_EBCDIC = (ord("A") == 193);
44
45 use Encode::Alias;
46
47 # Make a %Encoding package variable to allow a certain amount of cheating
48 our %Encoding;
49 our %ExtModule;
50 require Encode::Config;
51 eval { require Encode::ConfigLocal };
52
53 sub encodings
54 {
55     my $class = shift;
56     my @modules = (@_ and $_[0] eq ":all") ? values %ExtModule : @_;
57     for my $mod (@modules){
58         $mod =~ s,::,/,g or $mod = "Encode/$mod";
59         $mod .= '.pm';
60         $DEBUG and warn "about to require $mod;";
61         eval { require $mod; };
62     }
63     my %modules = map {$_ => 1} @modules;
64     return
65         sort { lc $a cmp lc $b }
66              grep {!/^(?:Internal|Unicode)$/o} keys %Encoding;
67 }
68
69 sub perlio_ok{
70     my $obj = ref($_[0]) ? $_[0] : find_encoding($_[0]);
71     $obj->can("perlio_ok") and return $obj->perlio_ok();
72     return 0; # safety net
73 }
74
75 sub define_encoding
76 {
77     my $obj  = shift;
78     my $name = shift;
79     $Encoding{$name} = $obj;
80     my $lc = lc($name);
81     define_alias($lc => $obj) unless $lc eq $name;
82     while (@_)
83     {
84         my $alias = shift;
85         define_alias($alias,$obj);
86     }
87     return $obj;
88 }
89
90 sub getEncoding
91 {
92     my ($class,$name,$skip_external) = @_;
93     my $enc;
94     if (ref($name) && $name->can('new_sequence'))
95     {
96         return $name;
97     }
98     my $lc = lc $name;
99     if (exists $Encoding{$name})
100     {
101         return $Encoding{$name};
102     }
103     if (exists $Encoding{$lc})
104     {
105         return $Encoding{$lc};
106     }
107
108     my $oc = $class->find_alias($name);
109     return $oc if defined $oc;
110
111     $oc = $class->find_alias($lc) if $lc ne $name;
112     return $oc if defined $oc;
113
114     unless ($skip_external)
115     {
116         if (my $mod = $ExtModule{$name} || $ExtModule{$lc}){
117             $mod =~ s,::,/,g ; $mod .= '.pm';
118             eval{ require $mod; };
119             return $Encoding{$name} if exists $Encoding{$name};
120         }
121     }
122     return;
123 }
124
125 sub find_encoding
126 {
127     my ($name,$skip_external) = @_;
128     return __PACKAGE__->getEncoding($name,$skip_external);
129 }
130
131 sub resolve_alias {
132     my $obj = find_encoding(shift);
133     defined $obj and return $obj->name;
134     return;
135 }
136
137 sub encode($$;$)
138 {
139     my ($name,$string,$check) = @_;
140     $check ||=0;
141     my $enc = find_encoding($name);
142     croak("Unknown encoding '$name'") unless defined $enc;
143     my $octets = $enc->encode($string,$check);
144     return undef if ($check && length($string));
145     return $octets;
146 }
147
148 sub decode($$;$)
149 {
150     my ($name,$octets,$check) = @_;
151     $check ||=0;
152     my $enc = find_encoding($name);
153     croak("Unknown encoding '$name'") unless defined $enc;
154     my $string = $enc->decode($octets,$check);
155     $_[1] = $octets if $check;
156     return $string;
157 }
158
159 sub from_to($$$;$)
160 {
161     my ($string,$from,$to,$check) = @_;
162     $check ||=0;
163     my $f = find_encoding($from);
164     croak("Unknown encoding '$from'") unless defined $f;
165     my $t = find_encoding($to);
166     croak("Unknown encoding '$to'") unless defined $t;
167     my $uni = $f->decode($string,$check);
168     return undef if ($check && length($string));
169     $string =  $t->encode($uni,$check);
170     return undef if ($check && length($uni));
171     return defined($_[0] = $string) ? length($string) : undef ;
172 }
173
174 sub encode_utf8($)
175 {
176     my ($str) = @_;
177     utf8::encode($str);
178     return $str;
179 }
180
181 sub decode_utf8($)
182 {
183     my ($str) = @_;
184     return undef unless utf8::decode($str);
185     return $str;
186 }
187
188 predefine_encodings();
189
190 #
191 # This is to restore %Encoding if really needed;
192 #
193 sub predefine_encodings{
194     if ($ON_EBCDIC) {
195         # was in Encode::UTF_EBCDIC
196         package Encode::UTF_EBCDIC;
197         *name         = sub{ shift->{'Name'} };
198         *new_sequence = sub{ return $_[0] };
199         *needs_lines = sub{ 0 };
200         *perlio_ok = sub { 
201             eval{ require PerlIO::encoding };
202             return $@ ? 0 : 1;
203         };
204         *decode = sub{
205             my ($obj,$str,$chk) = @_;
206             my $res = '';
207             for (my $i = 0; $i < length($str); $i++) {
208                 $res .=
209                     chr(utf8::unicode_to_native(ord(substr($str,$i,1))));
210             }
211             $_[1] = '' if $chk;
212             return $res;
213         };
214         *encode = sub{
215             my ($obj,$str,$chk) = @_;
216             my $res = '';
217             for (my $i = 0; $i < length($str); $i++) {
218                 $res .=
219                     chr(utf8::native_to_unicode(ord(substr($str,$i,1))));
220             }
221             $_[1] = '' if $chk;
222             return $res;
223         };
224         $Encode::Encoding{Unicode} =
225             bless {Name => "UTF_EBCDIC"} => "Encode::UTF_EBCDIC";
226     } else {
227         # was in Encode::UTF_EBCDIC
228         package Encode::Internal;
229         *name         = sub{ shift->{'Name'} };
230         *new_sequence = sub{ return $_[0] };
231         *needs_lines = sub{ 0 };
232         *perlio_ok = sub { 
233             eval{ require PerlIO::encoding };
234             return $@ ? 0 : 1;
235         };
236         *decode = sub{
237             my ($obj,$str,$chk) = @_;
238             utf8::upgrade($str);
239             $_[1] = '' if $chk;
240             return $str;
241         };
242         *encode = \&decode;
243         $Encode::Encoding{Unicode} =
244             bless {Name => "Internal"} => "Encode::Internal";
245     }
246
247     {
248         # was in Encode::utf8
249         package Encode::utf8;
250         *name         = sub{ shift->{'Name'} };
251         *new_sequence = sub{ return $_[0] };
252         *needs_lines = sub{ 0 };
253         *perlio_ok = sub { 
254             eval{ require PerlIO::encoding };
255             return $@ ? 0 : 1;
256         };
257         *decode = sub{
258             my ($obj,$octets,$chk) = @_;
259             my $str = Encode::decode_utf8($octets);
260             if (defined $str) {
261                 $_[1] = '' if $chk;
262                 return $str;
263             }
264             return undef;
265         };
266         *encode = sub {
267             my ($obj,$string,$chk) = @_;
268             my $octets = Encode::encode_utf8($string);
269             $_[1] = '' if $chk;
270             return $octets;
271         };
272         $Encode::Encoding{utf8} = 
273             bless {Name => "utf8"} => "Encode::utf8";
274     }
275 }
276
277 1;
278
279 __END__
280
281 =head1 NAME
282
283 Encode - character encodings
284
285 =head1 SYNOPSIS
286
287     use Encode;
288
289 =head2 Table of Contents
290
291 Encode consists of a collection of modules whose details are too big
292 to fit in one document.  This POD itself explains the top-level APIs
293 and general topics at a glance.  For other topics and more details,
294 see the PODs below:
295
296   Name                          Description
297   --------------------------------------------------------
298   Encode::Alias         Alias definitions to encodings
299   Encode::Encoding      Encode Implementation Base Class
300   Encode::Supported     List of Supported Encodings
301   Encode::CN            Simplified Chinese Encodings
302   Encode::JP            Japanese Encodings
303   Encode::KR            Korean Encodings
304   Encode::TW            Traditional Chinese Encodings
305   --------------------------------------------------------
306
307 =head1 DESCRIPTION
308
309 The C<Encode> module provides the interfaces between Perl's strings
310 and the rest of the system.  Perl strings are sequences of
311 B<characters>.
312
313 The repertoire of characters that Perl can represent is at least that
314 defined by the Unicode Consortium. On most platforms the ordinal
315 values of the characters (as returned by C<ord(ch)>) is the "Unicode
316 codepoint" for the character (the exceptions are those platforms where
317 the legacy encoding is some variant of EBCDIC rather than a super-set
318 of ASCII - see L<perlebcdic>).
319
320 Traditionally, computer data has been moved around in 8-bit chunks
321 often called "bytes". These chunks are also known as "octets" in
322 networking standards. Perl is widely used to manipulate data of many
323 types - not only strings of characters representing human or computer
324 languages but also "binary" data being the machine's representation of
325 numbers, pixels in an image - or just about anything.
326
327 When Perl is processing "binary data", the programmer wants Perl to
328 process "sequences of bytes". This is not a problem for Perl - as a
329 byte has 256 possible values, it easily fits in Perl's much larger
330 "logical character".
331
332 =head2 TERMINOLOGY
333
334 =over 4
335
336 =item *
337
338 I<character>: a character in the range 0..(2**32-1) (or more).
339 (What Perl's strings are made of.)
340
341 =item *
342
343 I<byte>: a character in the range 0..255
344 (A special case of a Perl character.)
345
346 =item *
347
348 I<octet>: 8 bits of data, with ordinal values 0..255
349 (Term for bytes passed to or from a non-Perl context, e.g. a disk file.)
350
351 =back
352
353 The marker [INTERNAL] marks Internal Implementation Details, in
354 general meant only for those who think they know what they are doing,
355 and such details may change in future releases.
356
357 =head1 PERL ENCODING API
358
359 =over 4
360
361 =item $octets  = encode(ENCODING, $string[, CHECK])
362
363 Encodes a string from Perl's internal form into I<ENCODING> and returns
364 a sequence of octets.  ENCODING can be either a canonical name or
365 an alias.  For encoding names and aliases, see L</"Defining Aliases">.
366 For CHECK, see L</"Handling Malformed Data">.
367
368 For example, to convert (internally UTF-8 encoded) Unicode string to
369 iso-8859-1 (also known as Latin1),
370
371   $octets = encode("iso-8859-1", $unicode);
372
373 =item $string = decode(ENCODING, $octets[, CHECK])
374
375 Decodes a sequence of octets assumed to be in I<ENCODING> into Perl's
376 internal form and returns the resulting string.  As in encode(),
377 ENCODING can be either a canonical name or an alias. For encoding names
378 and aliases, see L</"Defining Aliases">.  For CHECK, see
379 L</"Handling Malformed Data">.
380
381 For example, to convert ISO-8859-1 data to UTF-8:
382
383   $utf8 = decode("iso-8859-1", $latin1);
384
385 =item [$length =] from_to($string, FROM_ENCODING, TO_ENCODING [,CHECK])
386
387 Converts B<in-place> data between two encodings.
388 For example, to convert ISO-8859-1 data to UTF-8:
389
390         from_to($data, "iso-8859-1", "utf-8");
391
392 and to convert it back:
393
394         from_to($data, "utf-8", "iso-8859-1");
395
396 Note that because the conversion happens in place, the data to be
397 converted cannot be a string constant; it must be a scalar variable.
398
399 from_to() returns the length of the converted string on success, undef
400 otherwise.
401
402 =back
403
404 =head2 UTF-8 / utf8
405
406 The Unicode Consortium defines the UTF-8 transformation format as a
407 way of encoding the entire Unicode repertoire as sequences of octets.
408 This encoding is expected to become very widespread. Perl can use this
409 form internally to represent strings, so conversions to and from this
410 form are particularly efficient (as octets in memory do not have to
411 change, just the meta-data that tells Perl how to treat them).
412
413 =over 4
414
415 =item $octets = encode_utf8($string);
416
417 The characters that comprise $string are encoded in Perl's superset of
418 UTF-8 and the resulting octets are returned as a sequence of bytes. All
419 possible characters have a UTF-8 representation so this function cannot
420 fail.
421
422 =item $string = decode_utf8($octets [, CHECK]);
423
424 The sequence of octets represented by $octets is decoded from UTF-8
425 into a sequence of logical characters. Not all sequences of octets
426 form valid UTF-8 encodings, so it is possible for this call to fail.
427 For CHECK, see L</"Handling Malformed Data">.
428
429 =back
430
431 =head2 Listing available encodings
432
433   use Encode;
434   @list = Encode->encodings();
435
436 Returns a list of the canonical names of the available encodings that
437 are loaded.  To get a list of all available encodings including the
438 ones that are not loaded yet, say
439
440   @all_encodings = Encode->encodings(":all");
441
442 Or you can give the name of a specific module.
443
444   @with_jp = Encode->encodings("Encode::JP");
445
446 When "::" is not in the name, "Encode::" is assumed.
447
448   @ebcdic = Encode->encodings("EBCDIC");
449
450 To find out in detail which encodings are supported by this package,
451 see L<Encode::Supported>.
452
453 =head2 Defining Aliases
454
455 To add a new alias to a given encoding, use:
456
457   use Encode;
458   use Encode::Alias;
459   define_alias(newName => ENCODING);
460
461 After that, newName can be used as an alias for ENCODING.
462 ENCODING may be either the name of an encoding or an
463 I<encoding object>
464
465 But before you do so, make sure the alias is nonexistent with
466 C<resolve_alias()>, which returns the canonical name thereof.
467 i.e.
468
469   Encode::resolve_alias("latin1") eq "iso-8859-1" # true
470   Encode::resolve_alias("iso-8859-12")   # false; nonexistent
471   Encode::resolve_alias($name) eq $name  # true if $name is canonical
472
473 resolve_alias() does not need C<use Encode::Alias>; it can be
474 exported via C<use Encode qw(resolve_alias)>.
475
476 See L<Encode::Alias> for details.
477
478 =head1 Encoding via PerlIO
479
480 If your perl supports I<PerlIO>, you can use a PerlIO layer to decode
481 and encode directly via a filehandle.  The following two examples
482 are totally identical in their functionality.
483
484   # via PerlIO
485   open my $in,  "<:encoding(shiftjis)", $infile  or die;
486   open my $out, ">:encoding(euc-jp)",   $outfile or die;
487   while(<>){ print; }
488
489   # via from_to
490   open my $in,  "<", $infile  or die;
491   open my $out, ">", $outfile or die;
492   while(<>){
493     from_to($_, "shiftjis", "euc-jp", 1);
494   }
495
496 Unfortunately, there may be encodings are PerlIO-savvy.  You can check
497 if your encoding is supported by PerlIO by calling the C<perlio_ok>
498 method.
499
500   Encode::perlio_ok("hz");             # False
501   find_encoding("euc-cn")->perlio_ok;  # True where PerlIO is available
502
503   use Encode qw(perlio_ok);            # exported upon request
504   perlio_ok("euc-jp")
505
506 Fortunately, all encodings that come with Encode core are PerlIO-savvy
507 except for hz and ISO-2022-kr.  See L<Encode::Encoding> for details.
508
509 For gory details, see L<Encode::PerlIO>.
510
511 =head1 Handling Malformed Data
512
513 =over 4
514
515 The I<CHECK> argument is used as follows.  When you omit it,
516 the behaviour is the same as if you had passed a value of 0 for
517 I<CHECK>.
518
519 =item I<CHECK> = Encode::FB_DEFAULT ( == 0)
520
521 If I<CHECK> is 0, (en|de)code will put a I<substitution character>
522 in place of a malformed character.  For UCM-based encodings,
523 E<lt>subcharE<gt> will be used.  For Unicode, "\x{FFFD}" is used.
524 If the data is supposed to be UTF-8, an optional lexical warning
525 (category utf8) is given.
526
527 =item I<CHECK> = Encode::DIE_ON_ERROR (== 1)
528
529 If I<CHECK> is 1, methods will die immediately with an error
530 message.  Therefore, when I<CHECK> is set to 1,  you should trap the
531 fatal error with eval{} unless you really want to let it die on error.
532
533 =item I<CHECK> = Encode::FB_QUIET
534
535 If I<CHECK> is set to Encode::FB_QUIET, (en|de)code will immediately
536 return the portion of the data that has been processed so far when
537 an error occurs. The data argument will be overwritten with
538 everything after that point (that is, the unprocessed part of data).
539 This is handy when you have to call decode repeatedly in the case
540 where your source data may contain partial multi-byte character
541 sequences, for example because you are reading with a fixed-width
542 buffer. Here is some sample code that does exactly this:
543
544   my $data = '';
545   while(defined(read $fh, $buffer, 256)){
546     # buffer may end in a partial character so we append
547     $data .= $buffer;
548     $utf8 .= decode($encoding, $data, ENCODE::FB_QUIET);
549     # $data now contains the unprocessed partial character
550   }
551
552 =item I<CHECK> = Encode::FB_WARN
553
554 This is the same as above, except that it warns on error.  Handy when
555 you are debugging the mode above.
556
557 =item perlqq mode (I<CHECK> = Encode::FB_PERLQQ)
558
559 =item HTML charref mode (I<CHECK> = Encode::FB_HTMLCREF)
560
561 =item XML charref mode (I<CHECK> = Encode::FB_XMLCREF)
562
563 For encodings that are implemented by Encode::XS, CHECK ==
564 Encode::FB_PERLQQ turns (en|de)code into C<perlqq> fallback mode.
565
566 When you decode, '\xI<XX>' will be inserted for a malformed character,
567 where I<XX> is the hex representation of the octet  that could not be
568 decoded to utf8.  And when you encode, '\x{I<xxxx>}' will be inserted,
569 where I<xxxx> is the Unicode ID of the character that cannot be found
570 in the character repertoire of the encoding.
571
572 HTML/XML character reference modes are about the same, in place of
573 \x{I<xxxx>}, HTML uses &#I<1234>; where I<1234> is a decimal digit and
574 XML uses &#xI<abcd>; where I<abcd> is the hexadecimal digit.
575
576 =item The bitmask
577
578 These modes are actually set via a bitmask.  Here is how the FB_XX
579 constants are laid out.  You can import the FB_XX constants via
580 C<use Encode qw(:fallbacks)>; you can import the generic bitmask
581 constants via C<use Encode qw(:fallback_all)>.
582
583                      FB_DEFAULT FB_CROAK FB_QUIET FB_WARN  FB_PERLQQ
584  DIE_ON_ERR    0x0001             X
585  WARN_ON_ER    0x0002                               X
586  RETURN_ON_ERR 0x0004                      X        X
587  LEAVE_SRC     0x0008
588  PERLQQ        0x0100                                        X
589  HTMLCREF      0x0200                                         
590  XMLCREF       0x0400                                          
591
592 =head2 Unimplemented fallback schemes
593
594 In the future, you will be able to use a code reference to a callback
595 function for the value of I<CHECK> but its API is still undecided.
596
597 =head1 Defining Encodings
598
599 To define a new encoding, use:
600
601     use Encode qw(define_alias);
602     define_encoding($object, 'canonicalName' [, alias...]);
603
604 I<canonicalName> will be associated with I<$object>.  The object
605 should provide the interface described in L<Encode::Encoding>.
606 If more than two arguments are provided then additional
607 arguments are taken as aliases for I<$object>, as for C<define_alias>.
608
609 See L<Encode::Encoding> for more details.
610
611 =head1 Messing with Perl's Internals
612
613 The following API uses parts of Perl's internals in the current
614 implementation.  As such, they are efficient but may change.
615
616 =over 4
617
618 =item is_utf8(STRING [, CHECK])
619
620 [INTERNAL] Tests whether the UTF-8 flag is turned on in the STRING.
621 If CHECK is true, also checks the data in STRING for being well-formed
622 UTF-8.  Returns true if successful, false otherwise.
623
624 =item _utf8_on(STRING)
625
626 [INTERNAL] Turns on the UTF-8 flag in STRING.  The data in STRING is
627 B<not> checked for being well-formed UTF-8.  Do not use unless you
628 B<know> that the STRING is well-formed UTF-8.  Returns the previous
629 state of the UTF-8 flag (so please don't treat the return value as
630 indicating success or failure), or C<undef> if STRING is not a string.
631
632 =item _utf8_off(STRING)
633
634 [INTERNAL] Turns off the UTF-8 flag in STRING.  Do not use frivolously.
635 Returns the previous state of the UTF-8 flag (so please don't treat the
636 return value as indicating success or failure), or C<undef> if STRING is
637 not a string.
638
639 =back
640
641 =head1 SEE ALSO
642
643 L<Encode::Encoding>,
644 L<Encode::Supported>,
645 L<Encode::PerlIO>,
646 L<encoding>,
647 L<perlebcdic>,
648 L<perlfunc/open>,
649 L<perlunicode>,
650 L<utf8>,
651 the Perl Unicode Mailing List E<lt>perl-unicode@perl.orgE<gt>
652
653 =head1 MAINTAINER
654
655 This project was originated by Nick Ing-Simmons and later maintained
656 by Dan Kogai E<lt>dankogai@dan.co.jpE<gt>.  See AUTHORS for a full list
657 of people involved.  For any questions, use
658 E<lt>perl-unicode@perl.orgE<gt> so others can share.
659
660 =cut