[Encode] 1.88 Released
[p5sagit/p5-mst-13.2.git] / ext / Encode / Unicode / Unicode.pm
CommitLineData
f2a2953c 1package Encode::Unicode;
2
df1df145 3use strict;
f2a2953c 4use warnings;
5
151b5d36 6our $VERSION = do { my @r = (q$Revision: 1.38 $ =~ /\d+/g); sprintf "%d."."%02d" x $#r, @r };
f2a2953c 7
85982a32 8use XSLoader;
9XSLoader::load(__PACKAGE__,$VERSION);
df1df145 10
f2a2953c 11#
12# Object Generator 8 transcoders all at once!
13#
df1df145 14
f2a2953c 15require Encode;
10c5ecbb 16
f2a2953c 17for my $name (qw(UTF-16 UTF-16BE UTF-16LE
18 UTF-32 UTF-32BE UTF-32LE
19 UCS-2BE UCS-2LE))
df1df145 20{
f2a2953c 21 my ($size, $endian, $ucs2, $mask);
22 $name =~ /^(\w+)-(\d+)(\w*)$/o;
23 if ($ucs2 = ($1 eq 'UCS')){
24 $size = 2;
25 }else{
26 $size = $2/8;
df1df145 27 }
f2a2953c 28 $endian = ($3 eq 'BE') ? 'n' : ($3 eq 'LE') ? 'v' : '' ;
29 $size == 4 and $endian = uc($endian);
30
31 $Encode::Encoding{$name} =
32 bless {
33 Name => $name,
34 size => $size,
35 endian => $endian,
36 ucs2 => $ucs2,
c731e18e 37 } => __PACKAGE__;
f2a2953c 38
df1df145 39}
40
10c5ecbb 41use base qw(Encode::Encoding);
f2a2953c 42
43#
0ab8f81e 44# three implementations of (en|de)code exist. The XS version is the
45# fastest. *_modern uses an array and *_classic sticks with substr.
46# *_classic is much slower but more memory conservative.
47# *_xs is the default.
f2a2953c 48
49sub set_transcoder{
50 no warnings qw(redefine);
51 my $type = shift;
aae85ceb 52 if ($type eq "xs"){
53 *decode = \&decode_xs;
54 *encode = \&encode_xs;
55 }elsif($type eq "modern"){
f2a2953c 56 *decode = \&decode_modern;
57 *encode = \&encode_modern;
58 }elsif($type eq "classic"){
59 *decode = \&decode_classic;
60 *encode = \&encode_classic;
61 }else{
fcb875d4 62 require Carp;
4b291ae6 63 Carp::croak __PACKAGE__, "::set_transcoder(modern|classic|xs)";
f2a2953c 64 }
65}
66
aae85ceb 67set_transcoder("xs");
f2a2953c 68
69#
85982a32 70# Aux. subs & constants
71#
72
73sub FBCHAR(){ 0xFFFd }
74sub BOM_BE(){ 0xFeFF }
75sub BOM16LE(){ 0xFFFe }
76sub BOM32LE(){ 0xFFFe0000 }
77
78sub valid_ucs2($){
79 return
80 (0 <= $_[0] && $_[0] < 0xD800)
81 || ( 0xDFFF < $_[0] && $_[0] <= 0xFFFF);
82}
83
84sub issurrogate($){ 0xD800 <= $_[0] && $_[0] <= 0xDFFF }
85sub isHiSurrogate($){ 0xD800 <= $_[0] && $_[0] < 0xDC00 }
86sub isLoSurrogate($){ 0xDC00 <= $_[0] && $_[0] <= 0xDFFF }
87
88sub ensurrogate($){
89 use integer; # we have divisions
90 my $uni = shift;
91 my $hi = ($uni - 0x10000) / 0x400 + 0xD800;
92 my $lo = ($uni - 0x10000) % 0x400 + 0xDC00;
93 return ($hi, $lo);
94}
95
96sub desurrogate($$){
97 my ($hi, $lo) = @_;
98 return 0x10000 + ($hi - 0xD800)*0x400 + ($lo - 0xDC00);
99}
100
101sub Mask { {2 => 0xffff, 4 => 0xffffffff} }
102
103#
f2a2953c 104# *_modern are much faster but guzzle more memory
105#
106
aae85ceb 107sub decode_modern($$;$)
df1df145 108{
f2a2953c 109 my ($obj, $str, $chk ) = @_;
110 my ($size, $endian, $ucs2) = @$obj{qw(size endian ucs2)};
111
112 # warn "$size, $endian, $ucs2";
113 $endian ||= BOMB($size, substr($str, 0, $size, ''))
114 or poisoned2death($obj, "Where's the BOM?");
115 my $mask = Mask->{$size};
116 my $utf8 = '';
117 my @ord = unpack("$endian*", $str);
118 undef $str; # to conserve memory
119 while (@ord){
120 my $ord = shift @ord;
121 unless ($size == 4 or valid_ucs2($ord &= $mask)){
122 if ($ucs2){
fcb875d4 123 $chk and
f2a2953c 124 poisoned2death($obj, "no surrogates allowed", $ord);
125 shift @ord; # skip the next one as well
126 $ord = FBCHAR;
127 }else{
128 unless (isHiSurrogate($ord)){
129 poisoned2death($obj, "Malformed HI surrogate", $ord);
130 }
131 my $lo = shift @ord;
132 unless (isLoSurrogate($lo &= $mask)){
133 poisoned2death($obj, "Malformed LO surrogate", $ord, $lo);
134 }
135 $ord = desurrogate($ord, $lo);
136 }
137 }
138 $utf8 .= chr($ord);
df1df145 139 }
f2a2953c 140 utf8::upgrade($utf8);
141 return $utf8;
142}
143
aae85ceb 144sub encode_modern($$;$)
f2a2953c 145{
146 my ($obj, $utf8, $chk) = @_;
147 my ($size, $endian, $ucs2) = @$obj{qw(size endian ucs2)};
148 my @str = ();
149 unless ($endian){
150 $endian = ($size == 4) ? 'N' : 'n';
151 push @str, BOM_BE;
152 }
153 my @ord = unpack("U*", $utf8);
154 undef $utf8; # to conserve memory
155 for my $ord (@ord){
156 unless ($size == 4 or valid_ucs2($ord)) {
157 unless(issurrogate($ord)){
158 if ($ucs2){
fcb875d4 159 $chk and
f2a2953c 160 poisoned2death($obj, "code point too high", $ord);
161
162 push @str, FBCHAR;
163 }else{
fcb875d4 164
f2a2953c 165 push @str, ensurrogate($ord);
166 }
167 }else{ # not supposed to happen
168 push @str, FBCHAR;
169 }
170 }else{
171 push @str, $ord;
172 }
173 }
174 return pack("$endian*", @str);
175}
176
177#
178# *_classic are slower but more memory conservative
179#
180
aae85ceb 181sub decode_classic($$;$)
f2a2953c 182{
183 my ($obj, $str, $chk ) = @_;
184 my ($size, $endian, $ucs2) = @$obj{qw(size endian ucs2)};
185
186 # warn "$size, $endian, $ucs2";
187 $endian ||= BOMB($size, substr($str, 0, $size, ''))
188 or poisoned2death($obj, "Where's the BOM?");
189 my $mask = Mask->{$size};
190 my $utf8 = '';
191 my @ord = unpack("$endian*", $str);
192 while (length($str)){
193 my $ord = unpack($endian, substr($str, 0, $size, ''));
194 unless ($size == 4 or valid_ucs2($ord &= $mask)){
195 if ($ucs2){
fcb875d4 196 $chk and
f2a2953c 197 poisoned2death($obj, "no surrogates allowed", $ord);
198 substr($str,0,$size,''); # skip the next one as well
199 $ord = FBCHAR;
200 }else{
201 unless (isHiSurrogate($ord)){
202 poisoned2death($obj, "Malformed HI surrogate", $ord);
203 }
204 my $lo = unpack($endian ,substr($str,0,$size,''));
205 unless (isLoSurrogate($lo &= $mask)){
206 poisoned2death($obj, "Malformed LO surrogate", $ord, $lo);
207 }
208 $ord = desurrogate($ord, $lo);
209 }
210 }
211 $utf8 .= chr($ord);
212 }
213 utf8::upgrade($utf8);
214 return $utf8;
215}
216
aae85ceb 217sub encode_classic($$;$)
f2a2953c 218{
219 my ($obj, $utf8, $chk) = @_;
220 my ($size, $endian, $ucs2) = @$obj{qw(size endian ucs2)};
221 # warn join ", ", $size, $ucs2, $endian, $mask;
222 my $str = '';
223 unless ($endian){
224 $endian = ($size == 4) ? 'N' : 'n';
225 $str .= pack($endian, BOM_BE);
226 }
227 while (length($utf8)){
228 my $ord = ord(substr($utf8,0,1,''));
229 unless ($size == 4 or valid_ucs2($ord)) {
230 unless(issurrogate($ord)){
231 if ($ucs2){
fcb875d4 232 $chk and
f2a2953c 233 poisoned2death($obj, "code point too high", $ord);
234 $str .= pack($endian, FBCHAR);
235 }else{
236 $str .= pack($endian.2, ensurrogate($ord));
237 }
238 }else{ # not supposed to happen
239 $str .= pack($endian, FBCHAR);
240 }
241 }else{
242 $str .= pack($endian, $ord);
243 }
244 }
245 return $str;
246}
247
248sub BOMB {
249 my ($size, $bom) = @_;
250 my $N = $size == 2 ? 'n' : 'N';
251 my $ord = unpack($N, $bom);
fcb875d4 252 return ($ord eq BOM_BE) ? $N :
f2a2953c 253 ($ord eq BOM16LE) ? 'v' : ($ord eq BOM32LE) ? 'V' : undef;
254}
255
256sub poisoned2death{
257 my $obj = shift;
258 my $msg = shift;
259 my $pair = join(", ", map {sprintf "\\x%x", $_} @_);
260 require Carp;
4b291ae6 261 Carp::croak $obj->name, ":", $msg, "<$pair>.", caller;
df1df145 262}
263
2641;
265__END__
67d7b5ef 266
267=head1 NAME
268
0ab8f81e 269Encode::Unicode -- Various Unicode Transformation Formats
67d7b5ef 270
271=cut
f2a2953c 272
273=head1 SYNOPSIS
274
fcb875d4 275 use Encode qw/encode decode/;
f2a2953c 276 $ucs2 = encode("UCS-2BE", $utf8);
277 $utf8 = decode("UCS-2BE", $ucs2);
278
279=head1 ABSTRACT
280
281This module implements all Character Encoding Schemes of Unicode that
282are officially documented by Unicode Consortium (except, of course,
283for UTF-8, which is a native format in perl).
284
285=over 4
286
287=item L<http://www.unicode.org/glossary/> says:
288
289I<Character Encoding Scheme> A character encoding form plus byte
290serialization. There are seven character encoding schemes in Unicode:
11067275 291UTF-8, UTF-16, UTF-16BE, UTF-16LE, UTF-32 (UCS-4), UTF-32BE (UCS-4BE) and
292UTF-32LE (UCS-4LE).
f2a2953c 293
294=item Quick Reference
295
296 Decodes from ord(N) Encodes chr(N) to...
297 octet/char BOM S.P d800-dfff ord > 0xffff \x{1abcd} ==
298 ---------------+-----------------+------------------------------
299 UCS-2BE 2 N N is bogus Not Available
300 UCS-2LE 2 N N bogus Not Available
301 UTF-16 2/4 Y Y is S.P S.P BE/LE
302 UTF-16BE 2/4 N Y S.P S.P 0xd82a,0xdfcd
303 UTF-16LE 2 N Y S.P S.P 0x2ad8,0xcddf
304 UTF-32 4 Y - is bogus As is BE/LE
0ab8f81e 305 UTF-32BE 4 N - bogus As is 0x0001abcd
306 UTF-32LE 4 N - bogus As is 0xcdab0100
f2a2953c 307 UTF-8 1-4 - - bogus >= 4 octets \xf0\x9a\af\8d
308 ---------------+-----------------+------------------------------
309
310=back
311
312=head1 Size, Endianness, and BOM
313
0ab8f81e 314You can categorize these CES by 3 criteria: size of each character,
315endianness, and Byte Order Mark.
f2a2953c 316
0ab8f81e 317=head2 by size
f2a2953c 318
319UCS-2 is a fixed-length encoding with each character taking 16 bits.
0ab8f81e 320It B<does not> support I<surrogate pairs>. When a surrogate pair
321is encountered during decode(), its place is filled with \x{FFFD}
322if I<CHECK> is 0, or the routine croaks if I<CHECK> is 1. When a
323character whose ord value is larger than 0xFFFF is encountered,
324its place is filled with \x{FFFD} if I<CHECK> is 0, or the routine
325croaks if I<CHECK> is 1.
326
327UTF-16 is almost the same as UCS-2 but it supports I<surrogate pairs>.
f2a2953c 328When it encounters a high surrogate (0xD800-0xDBFF), it fetches the
0ab8f81e 329following low surrogate (0xDC00-0xDFFF) and C<desurrogate>s them to
330form a character. Bogus surrogates result in death. When \x{10000}
331or above is encountered during encode(), it C<ensurrogate>s them and
332pushes the surrogate pair to the output stream.
f2a2953c 333
11067275 334UTF-32 (UCS-4) is a fixed-length encoding with each character taking 32 bits.
0ab8f81e 335Since it is 32-bit, there is no need for I<surrogate pairs>.
f2a2953c 336
0ab8f81e 337=head2 by endianness
f2a2953c 338
0ab8f81e 339The first (and now failed) goal of Unicode was to map all character
340repertoires into a fixed-length integer so that programmers are happy.
341Since each character is either a I<short> or I<long> in C, you have to
342pay attention to the endianness of each platform when you pass data
343to one another.
f2a2953c 344
345Anything marked as BE is Big Endian (or network byte order) and LE is
0ab8f81e 346Little Endian (aka VAX byte order). For anything not marked either
347BE or LE, a character called Byte Order Mark (BOM) indicating the
348endianness is prepended to the string.
f2a2953c 349
350=over 4
351
fcb875d4 352=item BOM as integer when fetched in network byte order
f2a2953c 353
fcb875d4 354 16 32 bits/char
355 -------------------------
356 BE 0xFeFF 0x0000FeFF
357 LE 0xFFeF 0xFFFe0000
358 -------------------------
f2a2953c 359
360=back
151b5d36 361
0ab8f81e 362This modules handles the BOM as follows.
f2a2953c 363
364=over 4
365
366=item *
367
368When BE or LE is explicitly stated as the name of encoding, BOM is
0ab8f81e 369simply treated as a normal character (ZERO WIDTH NO-BREAK SPACE).
f2a2953c 370
371=item *
372
0ab8f81e 373When BE or LE is omitted during decode(), it checks if BOM is at the
374beginning of the string; if one is found, the endianness is set to
375what the BOM says. If no BOM is found, the routine dies.
f2a2953c 376
377=item *
378
379When BE or LE is omitted during encode(), it returns a BE-encoded
380string with BOM prepended. So when you want to encode a whole text
0ab8f81e 381file, make sure you encode() the whole text at once, not line by line
382or each line, not file, will have a BOM prepended.
f2a2953c 383
384=item *
385
0ab8f81e 386C<UCS-2> is an exception. Unlike others, this is an alias of UCS-2BE.
f2a2953c 387UCS-2 is already registered by IANA and others that way.
388
fdd579e2 389=back
f2a2953c 390
fcb875d4 391=head1 Surrogate Pairs
f2a2953c 392
fcb875d4 393To say the least, surrogate pairs were the biggest mistake of the
394Unicode Consortium. But according to the late Douglas Adams in I<The
395Hitchhiker's Guide to the Galaxy> Trilogy, C<In the beginning the
396Universe was created. This has made a lot of people very angry and
397been widely regarded as a bad move>. Their mistake was not of this
398magnitude so let's forgive them.
f2a2953c 399
400(I don't dare make any comparison with Unicode Consortium and the
c731e18e 401Vogons here ;) Or, comparing Encode to Babel Fish is completely
402appropriate -- if you can only stick this into your ear :)
f2a2953c 403
0ab8f81e 404Surrogate pairs were born when the Unicode Consortium finally
fcb875d4 405admitted that 16 bits were not big enough to hold all the world's
0ab8f81e 406character repertoires. But they already made UCS-2 16-bit. What
f2a2953c 407do we do?
408
0ab8f81e 409Back then, the range 0xD800-0xDFFF was not allocated. Let's split
410that range in half and use the first half to represent the C<upper
411half of a character> and the second half to represent the C<lower
412half of a character>. That way, you can represent 1024 * 1024 =
4131048576 more characters. Now we can store character ranges up to
414\x{10ffff} even with 16-bit encodings. This pair of half-character is
415now called a I<surrogate pair> and UTF-16 is the name of the encoding
416that embraces them.
f2a2953c 417
448e90bb 418Here is a formula to ensurrogate a Unicode character \x{10000} and
f2a2953c 419above;
420
421 $hi = ($uni - 0x10000) / 0x400 + 0xD800;
422 $lo = ($uni - 0x10000) % 0x400 + 0xDC00;
423
424And to desurrogate;
425
426 $uni = 0x10000 + ($hi - 0xD800) * 0x400 + ($lo - 0xDC00);
427
fcb875d4 428Note this move has made \x{D800}-\x{DFFF} into a forbidden zone but
429perl does not prohibit the use of characters within this range. To perl,
430every one of \x{0000_0000} up to \x{ffff_ffff} (*) is I<a character>.
431
432 (*) or \x{ffff_ffff_ffff_ffff} if your perl is compiled with 64-bit
0ab8f81e 433 integer support!
f2a2953c 434
435=head1 SEE ALSO
436
fdd579e2 437L<Encode>, L<http://www.unicode.org/glossary/>,
11067275 438L<http://www.unicode.org/unicode/faq/utf_bom.html>,
f2a2953c 439
fdd579e2 440RFC 2781 L<http://rfc.net/rfc2781.html>,
441
11067275 442The whole Unicode standard L<http://www.unicode.org/unicode/uni2book/u2.html>
fdd579e2 443
fcb875d4 444Ch. 15, pp. 403 of C<Programming Perl (3rd Edition)>
445by Larry Wall, Tom Christiansen, Jon Orwant;
446O'Reilly & Associates; ISBN 0-596-00027-8
447
fdd579e2 448=cut