dslinux/user/perl/ext/Encode AUTHORS Changes Encode.pm Encode.xs MANIFEST META.yml Makefile.PL README encengine.c encoding.pm

cayenne dslinux_cayenne at user.in-berlin.de
Tue Dec 5 05:26:36 CET 2006


Update of /cvsroot/dslinux/dslinux/user/perl/ext/Encode
In directory antilope:/tmp/cvs-serv7729/ext/Encode

Added Files:
	AUTHORS Changes Encode.pm Encode.xs MANIFEST META.yml 
	Makefile.PL README encengine.c encoding.pm 
Log Message:
Adding fresh perl source to HEAD to branch from

--- NEW FILE: Encode.pm ---
#
# $Id: Encode.pm,v 1.1 2006-12-05 04:26:33 dslinux_cayenne Exp $
#
package Encode;
use strict;
our $VERSION = sprintf "%d.%02d", q$Revision: 1.1 $ =~ /(\d+)/g;
sub DEBUG () { 0 }
use XSLoader ();
XSLoader::load(__PACKAGE__, $VERSION);

require Exporter;
use base qw/Exporter/;

# Public, encouraged API is exported by default

our @EXPORT = qw(
  decode  decode_utf8  encode  encode_utf8
  encodings  find_encoding clone_encoding
);

our @FB_FLAGS  = qw(DIE_ON_ERR WARN_ON_ERR RETURN_ON_ERR LEAVE_SRC
		    PERLQQ HTMLCREF XMLCREF STOP_AT_PARTIAL);
our @FB_CONSTS = qw(FB_DEFAULT FB_CROAK FB_QUIET FB_WARN
		    FB_PERLQQ FB_HTMLCREF FB_XMLCREF);

our @EXPORT_OK =
    (
     qw(
       _utf8_off _utf8_on define_encoding from_to is_16bit is_8bit
       is_utf8 perlio_ok resolve_alias utf8_downgrade utf8_upgrade
      ),
     @FB_FLAGS, @FB_CONSTS,
    );

our %EXPORT_TAGS =
    (
     all          =>  [ @EXPORT, @EXPORT_OK ],
     fallbacks    =>  [ @FB_CONSTS ],
     fallback_all =>  [ @FB_CONSTS, @FB_FLAGS ],
    );

# Documentation moved after __END__ for speed - NI-S

our $ON_EBCDIC = (ord("A") == 193);

use Encode::Alias;

# Make a %Encoding package variable to allow a certain amount of cheating
our %Encoding;
our %ExtModule;
require Encode::Config;
eval { require Encode::ConfigLocal };

sub encodings
{
    my $class = shift;
    my %enc;
    if (@_ and $_[0] eq ":all"){
	%enc = ( %Encoding, %ExtModule );
    }else{
	%enc = %Encoding;
	for my $mod (map {m/::/o ? $_ : "Encode::$_" } @_){
	    DEBUG and warn $mod;
	    for my $enc (keys %ExtModule){
		$ExtModule{$enc} eq $mod and $enc{$enc} = $mod;
	    }
	}
    }
    return
	sort { lc $a cmp lc $b }
             grep {!/^(?:Internal|Unicode|Guess)$/o} keys %enc;
}

sub perlio_ok{
    my $obj = ref($_[0]) ? $_[0] : find_encoding($_[0]);
    $obj->can("perlio_ok") and return $obj->perlio_ok();
    return 0; # safety net
}

sub define_encoding
{
    my $obj  = shift;
    my $name = shift;
    $Encoding{$name} = $obj;
    my $lc = lc($name);
    define_alias($lc => $obj) unless $lc eq $name;
    while (@_){
	my $alias = shift;
	define_alias($alias, $obj);
    }
    return $obj;
}

sub getEncoding
{
    my ($class, $name, $skip_external) = @_;

    ref($name) && $name->can('renew') and return $name;
    exists $Encoding{$name} and return $Encoding{$name};
    my $lc = lc $name;
    exists $Encoding{$lc} and return $Encoding{$lc};

    my $oc = $class->find_alias($name);
    defined($oc) and return $oc;
    $lc ne $name and $oc = $class->find_alias($lc);
    defined($oc) and return $oc;

    unless ($skip_external)
    {
	if (my $mod = $ExtModule{$name} || $ExtModule{$lc}){
	    $mod =~ s,::,/,g ; $mod .= '.pm';
	    eval{ require $mod; };
	    exists $Encoding{$name} and return $Encoding{$name};
	}
    }
    return;
}

sub find_encoding($;$)
{
    my ($name, $skip_external) = @_;
    return __PACKAGE__->getEncoding($name,$skip_external);
}

sub resolve_alias($){
    my $obj = find_encoding(shift);
    defined $obj and return $obj->name;
    return;
}

sub clone_encoding($){
    my $obj = find_encoding(shift);
    ref $obj or return;
    eval { require Storable };
    $@ and return;
    return Storable::dclone($obj);
}

sub encode($$;$)
{
    my ($name, $string, $check) = @_;
    return undef unless defined $string;
    $string .= '' if ref $string; # stringify;
    $check ||=0;
    my $enc = find_encoding($name);
    unless(defined $enc){
	require Carp;
	Carp::croak("Unknown encoding '$name'");
    }
    my $octets = $enc->encode($string,$check);
    $_[1] = $string if $check and !($check & LEAVE_SRC());
    return $octets;
}

sub decode($$;$)
{
    my ($name,$octets,$check) = @_;
    return undef unless defined $octets;
    $octets .= '' if ref $octets;
    $check ||=0;
    my $enc = find_encoding($name);
    unless(defined $enc){
	require Carp;
	Carp::croak("Unknown encoding '$name'");
    }
    my $string = $enc->decode($octets,$check);
    $_[1] = $octets if $check and !($check & LEAVE_SRC());
    return $string;
}

sub from_to($$$;$)
{
    my ($string,$from,$to,$check) = @_;
    return undef unless defined $string;
    $check ||=0;
    my $f = find_encoding($from);
    unless (defined $f){
	require Carp;
	Carp::croak("Unknown encoding '$from'");
    }
    my $t = find_encoding($to);
    unless (defined $t){
	require Carp;
	Carp::croak("Unknown encoding '$to'");
    }
    my $uni = $f->decode($string,$check);
    return undef if ($check && length($string));
    $string =  $t->encode($uni,$check);
    return undef if ($check && length($uni));
    return defined($_[0] = $string) ? length($string) : undef ;
}

sub encode_utf8($)
{
    my ($str) = @_;
    utf8::encode($str);
    return $str;
}

sub decode_utf8($;$)
{
    my ($str, $check) = @_;
    if ($check){
	return decode("utf8", $str, $check);
    }else{
	return decode("utf8", $str);
	return $str;
    }
}

predefine_encodings(1);

#
# This is to restore %Encoding if really needed;
#

sub predefine_encodings{
    use Encode::Encoding;
    no warnings 'redefine';
    my $use_xs = shift;
    if ($ON_EBCDIC) {
	# was in Encode::UTF_EBCDIC
	package Encode::UTF_EBCDIC;
	push @Encode::UTF_EBCDIC::ISA, 'Encode::Encoding';
	*decode = sub{
	    my ($obj,$str,$chk) = @_;
	    my $res = '';
	    for (my $i = 0; $i < length($str); $i++) {
		$res .=
		    chr(utf8::unicode_to_native(ord(substr($str,$i,1))));
	    }
	    $_[1] = '' if $chk;
	    return $res;
	};
	*encode = sub{
	    my ($obj,$str,$chk) = @_;
	    my $res = '';
	    for (my $i = 0; $i < length($str); $i++) {
		$res .=
		    chr(utf8::native_to_unicode(ord(substr($str,$i,1))));
	    }
	    $_[1] = '' if $chk;
	    return $res;
	};
	$Encode::Encoding{Unicode} =
	    bless {Name => "UTF_EBCDIC"} => "Encode::UTF_EBCDIC";
    } else {
	package Encode::Internal;
	push @Encode::Internal::ISA, 'Encode::Encoding';
	*decode = sub{
	    my ($obj,$str,$chk) = @_;
	    utf8::upgrade($str);
	    $_[1] = '' if $chk;
	    return $str;
	};
	*encode = \&decode;
	$Encode::Encoding{Unicode} =
	    bless {Name => "Internal"} => "Encode::Internal";
    }

    {
	# was in Encode::utf8
	package Encode::utf8;
	push @Encode::utf8::ISA, 'Encode::Encoding';
	# 
	if ($use_xs){
	    Encode::DEBUG and warn __PACKAGE__, " XS on";
	    *decode = \&decode_xs;
	    *encode = \&encode_xs;
	}else{
	    Encode::DEBUG and warn __PACKAGE__, " XS off";
	    *decode = sub{
		my ($obj,$octets,$chk) = @_;
		my $str = Encode::decode_utf8($octets);
		if (defined $str) {
		    $_[1] = '' if $chk;
		    return $str;
		}
		return undef;
	    };
	    *encode = sub {
		my ($obj,$string,$chk) = @_;
		my $octets = Encode::encode_utf8($string);
		$_[1] = '' if $chk;
		return $octets;
	    };
	}
	*cat_decode = sub{ # ($obj, $dst, $src, $pos, $trm, $chk)
	    my ($obj, undef, undef, $pos, $trm) = @_; # currently ignores $chk
	    my ($rdst, $rsrc, $rpos) = \@_[1,2,3];
	    use bytes;
	    if ((my $npos = index($$rsrc, $trm, $pos)) >= 0) {
		$$rdst .= substr($$rsrc, $pos, $npos - $pos + length($trm));
		$$rpos = $npos + length($trm);
		return 1;
	    }
	    $$rdst .= substr($$rsrc, $pos);
	    $$rpos = length($$rsrc);
	    return '';
	};
	$Encode::Encoding{utf8} =
	    bless {Name => "utf8"} => "Encode::utf8";
	$Encode::Encoding{"utf-8-strict"} =
	    bless {Name => "utf-8-strict", strict_utf8 => 1 } => "Encode::utf8";
    }
}

1;

__END__

=head1 NAME

Encode - character encodings

=head1 SYNOPSIS

    use Encode;

=head2 Table of Contents

Encode consists of a collection of modules whose details are too big
to fit in one document.  This POD itself explains the top-level APIs
and general topics at a glance.  For other topics and more details,
see the PODs below:

  Name			        Description
  --------------------------------------------------------
  Encode::Alias         Alias definitions to encodings
  Encode::Encoding      Encode Implementation Base Class
  Encode::Supported     List of Supported Encodings
  Encode::CN            Simplified Chinese Encodings
  Encode::JP            Japanese Encodings
  Encode::KR            Korean Encodings
  Encode::TW            Traditional Chinese Encodings
  --------------------------------------------------------

=head1 DESCRIPTION

The C<Encode> module provides the interfaces between Perl's strings
and the rest of the system.  Perl strings are sequences of
B<characters>.

The repertoire of characters that Perl can represent is at least that
defined by the Unicode Consortium. On most platforms the ordinal
values of the characters (as returned by C<ord(ch)>) is the "Unicode
codepoint" for the character (the exceptions are those platforms where
the legacy encoding is some variant of EBCDIC rather than a super-set
of ASCII - see L<perlebcdic>).

Traditionally, computer data has been moved around in 8-bit chunks
often called "bytes". These chunks are also known as "octets" in
networking standards. Perl is widely used to manipulate data of many
types - not only strings of characters representing human or computer
languages but also "binary" data being the machine's representation of
numbers, pixels in an image - or just about anything.

When Perl is processing "binary data", the programmer wants Perl to
process "sequences of bytes". This is not a problem for Perl - as a
byte has 256 possible values, it easily fits in Perl's much larger
"logical character".

=head2 TERMINOLOGY

=over 2

=item *

I<character>: a character in the range 0..(2**32-1) (or more).
(What Perl's strings are made of.)

=item *

I<byte>: a character in the range 0..255
(A special case of a Perl character.)

=item *

I<octet>: 8 bits of data, with ordinal values 0..255
(Term for bytes passed to or from a non-Perl context, e.g. a disk file.)

=back

=head1 PERL ENCODING API

=over 2

=item $octets  = encode(ENCODING, $string [, CHECK])

Encodes a string from Perl's internal form into I<ENCODING> and returns
a sequence of octets.  ENCODING can be either a canonical name or
an alias.  For encoding names and aliases, see L</"Defining Aliases">.
For CHECK, see L</"Handling Malformed Data">.

For example, to convert a string from Perl's internal format to
iso-8859-1 (also known as Latin1),

  $octets = encode("iso-8859-1", $string);

B<CAVEAT>: When you run C<$octets = encode("utf8", $string)>, then $octets
B<may not be equal to> $string.  Though they both contain the same data, the utf8 flag
for $octets is B<always> off.  When you encode anything, utf8 flag of
the result is always off, even when it contains completely valid utf8
string. See L</"The UTF-8 flag"> below.

If the $string is C<undef> then C<undef> is returned.

=item $string = decode(ENCODING, $octets [, CHECK])

Decodes a sequence of octets assumed to be in I<ENCODING> into Perl's
internal form and returns the resulting string.  As in encode(),
ENCODING can be either a canonical name or an alias. For encoding names
and aliases, see L</"Defining Aliases">.  For CHECK, see
L</"Handling Malformed Data">.

For example, to convert ISO-8859-1 data to a string in Perl's internal format:

  $string = decode("iso-8859-1", $octets);

B<CAVEAT>: When you run C<$string = decode("utf8", $octets)>, then $string
B<may not be equal to> $octets.  Though they both contain the same data,
the utf8 flag for $string is on unless $octets entirely consists of
ASCII data (or EBCDIC on EBCDIC machines).  See L</"The UTF-8 flag">
below.

If the $string is C<undef> then C<undef> is returned.

=item [$length =] from_to($octets, FROM_ENC, TO_ENC [, CHECK])

Converts B<in-place> data between two encodings. The data in $octets
must be encoded as octets and not as characters in Perl's internal
format. For example, to convert ISO-8859-1 data to Microsoft's CP1250
encoding:

  from_to($octets, "iso-8859-1", "cp1250");

and to convert it back:

  from_to($octets, "cp1250", "iso-8859-1");

Note that because the conversion happens in place, the data to be
converted cannot be a string constant; it must be a scalar variable.

from_to() returns the length of the converted string in octets on
success, I<undef> on error.

B<CAVEAT>: The following operations look the same but are not quite so;

  from_to($data, "iso-8859-1", "utf8"); #1
  $data = decode("iso-8859-1", $data);  #2

Both #1 and #2 make $data consist of a completely valid UTF-8 string
but only #2 turns utf8 flag on.  #1 is equivalent to

  $data = encode("utf8", decode("iso-8859-1", $data));

See L</"The UTF-8 flag"> below.

=item $octets = encode_utf8($string);

Equivalent to C<$octets = encode("utf8", $string);> The characters
that comprise $string are encoded in Perl's internal format and the
result is returned as a sequence of octets. All possible
characters have a UTF-8 representation so this function cannot fail.


=item $string = decode_utf8($octets [, CHECK]);

equivalent to C<$string = decode("utf8", $octets [, CHECK])>.
The sequence of octets represented by
$octets is decoded from UTF-8 into a sequence of logical
characters. Not all sequences of octets form valid UTF-8 encodings, so
it is possible for this call to fail.  For CHECK, see
L</"Handling Malformed Data">.

=back

=head2 Listing available encodings

  use Encode;
  @list = Encode->encodings();

Returns a list of the canonical names of the available encodings that
are loaded.  To get a list of all available encodings including the
ones that are not loaded yet, say

  @all_encodings = Encode->encodings(":all");

Or you can give the name of a specific module.

  @with_jp = Encode->encodings("Encode::JP");

When "::" is not in the name, "Encode::" is assumed.

  @ebcdic = Encode->encodings("EBCDIC");

To find out in detail which encodings are supported by this package,
see L<Encode::Supported>.

=head2 Defining Aliases

To add a new alias to a given encoding, use:

  use Encode;
  use Encode::Alias;
  define_alias(newName => ENCODING);

After that, newName can be used as an alias for ENCODING.
ENCODING may be either the name of an encoding or an
I<encoding object>

But before you do so, make sure the alias is nonexistent with
C<resolve_alias()>, which returns the canonical name thereof.
i.e.

  Encode::resolve_alias("latin1") eq "iso-8859-1" # true
  Encode::resolve_alias("iso-8859-12")   # false; nonexistent
  Encode::resolve_alias($name) eq $name  # true if $name is canonical

resolve_alias() does not need C<use Encode::Alias>; it can be
exported via C<use Encode qw(resolve_alias)>.

See L<Encode::Alias> for details.

=head1 Encoding via PerlIO

If your perl supports I<PerlIO> (which is the default), you can use a PerlIO layer to decode
and encode directly via a filehandle.  The following two examples
are totally identical in their functionality.

  # via PerlIO
  open my $in,  "<:encoding(shiftjis)", $infile  or die;
  open my $out, ">:encoding(euc-jp)",   $outfile or die;
  while(<$in>){ print $out $_; }

  # via from_to
  open my $in,  "<", $infile  or die;
  open my $out, ">", $outfile or die;
  while(<$in>){
    from_to($_, "shiftjis", "euc-jp", 1);
    print $out $_;
  }

Unfortunately, it may be that encodings are PerlIO-savvy.  You can check
if your encoding is supported by PerlIO by calling the C<perlio_ok>
method.

  Encode::perlio_ok("hz");             # False
  find_encoding("euc-cn")->perlio_ok;  # True where PerlIO is available

  use Encode qw(perlio_ok);            # exported upon request
  perlio_ok("euc-jp")

Fortunately, all encodings that come with Encode core are PerlIO-savvy
except for hz and ISO-2022-kr.  For gory details, see
L<Encode::Encoding> and L<Encode::PerlIO>.

=head1 Handling Malformed Data

The optional I<CHECK> argument tells Encode what to do when it
encounters malformed data.  Without CHECK, Encode::FB_DEFAULT ( == 0 )
is assumed.

As of version 2.12 Encode supports coderef values for CHECK.  See below.

=over 2

=item B<NOTE:> Not all encoding support this feature

Some encodings ignore I<CHECK> argument.  For example,
L<Encode::Unicode> ignores I<CHECK> and it always croaks on error.

=back

Now here is the list of I<CHECK> values available

=over 2

=item I<CHECK> = Encode::FB_DEFAULT ( == 0)

If I<CHECK> is 0, (en|de)code will put a I<substitution character> in
place of a malformed character.  When you encode, E<lt>subcharE<gt>
will be used.  When you decode the code point C<0xFFFD> is used.  If
the data is supposed to be UTF-8, an optional lexical warning
(category utf8) is given.

=item I<CHECK> = Encode::FB_CROAK ( == 1)

If I<CHECK> is 1, methods will die on error immediately with an error
message.  Therefore, when I<CHECK> is set to 1,  you should trap the
error with eval{} unless you really want to let it die.

=item I<CHECK> = Encode::FB_QUIET

If I<CHECK> is set to Encode::FB_QUIET, (en|de)code will immediately
return the portion of the data that has been processed so far when an
error occurs. The data argument will be overwritten with everything
after that point (that is, the unprocessed part of data).  This is
handy when you have to call decode repeatedly in the case where your
source data may contain partial multi-byte character sequences,
(i.e. you are reading with a fixed-width buffer). Here is a sample
code that does exactly this:

  my $buffer = ''; my $string = '';
  while(read $fh, $buffer, 256, length($buffer)){
    $string .= decode($encoding, $buffer, Encode::FB_QUIET);
    # $buffer now contains the unprocessed partial character
  }

=item I<CHECK> = Encode::FB_WARN

This is the same as above, except that it warns on error.  Handy when
you are debugging the mode above.

=item perlqq mode (I<CHECK> = Encode::FB_PERLQQ)

=item HTML charref mode (I<CHECK> = Encode::FB_HTMLCREF)

=item XML charref mode (I<CHECK> = Encode::FB_XMLCREF)

For encodings that are implemented by Encode::XS, CHECK ==
Encode::FB_PERLQQ turns (en|de)code into C<perlqq> fallback mode.

When you decode, C<\xI<HH>> will be inserted for a malformed character,
where I<HH> is the hex representation of the octet  that could not be
decoded to utf8.  And when you encode, C<\x{I<HHHH>}> will be inserted,
where I<HHHH> is the Unicode ID of the character that cannot be found
in the character repertoire of the encoding.

HTML/XML character reference modes are about the same, in place of
C<\x{I<HHHH>}>, HTML uses C<&#I<NNN>;> where I<NNN> is a decimal number and
XML uses C<&#xI<HHHH>;> where I<HHHH> is the hexadecimal number.

In Encode 2.10 or later, C<LEAVE_SRC> is also implied.

=item The bitmask

These modes are actually set via a bitmask.  Here is how the FB_XX
constants are laid out.  You can import the FB_XX constants via
C<use Encode qw(:fallbacks)>; you can import the generic bitmask
constants via C<use Encode qw(:fallback_all)>.

                     FB_DEFAULT FB_CROAK FB_QUIET FB_WARN  FB_PERLQQ
 DIE_ON_ERR    0x0001             X
 WARN_ON_ERR   0x0002                               X
 RETURN_ON_ERR 0x0004                      X        X
 LEAVE_SRC     0x0008                                        X
 PERLQQ        0x0100                                        X
 HTMLCREF      0x0200
 XMLCREF       0x0400

=back

=head2 coderef for CHECK

As of Encode 2.12 CHECK can also be a code reference which takes the
ord value of unmapped caharacter as an argument and returns a string
that represents the fallback character.  For instance,

  $ascii = encode("ascii", $utf8, sub{ sprintf "<U+%04X>", shift });

Acts like FB_PERLQQ but E<lt>U+I<XXXX>E<gt> is used instead of
\x{I<XXXX>}.

=head1 Defining Encodings

To define a new encoding, use:

    use Encode qw(define_encoding);
    define_encoding($object, 'canonicalName' [, alias...]);

I<canonicalName> will be associated with I<$object>.  The object
should provide the interface described in L<Encode::Encoding>.
If more than two arguments are provided then additional
arguments are taken as aliases for I<$object>.

See L<Encode::Encoding> for more details.

=head1 The UTF-8 flag

Before the introduction of utf8 support in perl, The C<eq> operator
just compared the strings represented by two scalars. Beginning with
perl 5.8, C<eq> compares two strings with simultaneous consideration
of I<the utf8 flag>. To explain why we made it so, I will quote page
402 of C<Programming Perl, 3rd ed.>

=over 2

=item Goal #1:

Old byte-oriented programs should not spontaneously break on the old
byte-oriented data they used to work on.

=item Goal #2:

Old byte-oriented programs should magically start working on the new
character-oriented data when appropriate.

=item Goal #3:

Programs should run just as fast in the new character-oriented mode
as in the old byte-oriented mode.

=item Goal #4:

Perl should remain one language, rather than forking into a
byte-oriented Perl and a character-oriented Perl.

=back

Back when C<Programming Perl, 3rd ed.> was written, not even Perl 5.6.0
was born and many features documented in the book remained
unimplemented for a long time.  Perl 5.8 corrected this and the introduction
of the UTF-8 flag is one of them.  You can think of this perl notion as of a
byte-oriented mode (utf8 flag off) and a character-oriented mode (utf8
flag on).

Here is how Encode takes care of the utf8 flag.

=over 2

=item *

When you encode, the resulting utf8 flag is always off.

=item *

When you decode, the resulting utf8 flag is on unless you can
unambiguously represent data.  Here is the definition of
dis-ambiguity.

After C<$utf8 = decode('foo', $octet);>,

  When $octet is...   The utf8 flag in $utf8 is
  ---------------------------------------------
  In ASCII only (or EBCDIC only)            OFF
  In ISO-8859-1                              ON
  In any other Encoding                      ON
  ---------------------------------------------

As you see, there is one exception, In ASCII.  That way you can assume
Goal #1.  And with Encode Goal #2 is assumed but you still have to be
careful in such cases mentioned in B<CAVEAT> paragraphs.

This utf8 flag is not visible in perl scripts, exactly for the same
reason you cannot (or you I<don't have to>) see if a scalar contains a
string, integer, or floating point number.   But you can still peek
and poke these if you will.  See the section below.

=back

=head2 Messing with Perl's Internals

The following API uses parts of Perl's internals in the current
implementation.  As such, they are efficient but may change.

=over 2

=item is_utf8(STRING [, CHECK])

[INTERNAL] Tests whether the UTF-8 flag is turned on in the STRING.
If CHECK is true, also checks the data in STRING for being well-formed
UTF-8.  Returns true if successful, false otherwise.

As of perl 5.8.1, L<utf8> also has utf8::is_utf8().

=item _utf8_on(STRING)

[INTERNAL] Turns on the UTF-8 flag in STRING.  The data in STRING is
B<not> checked for being well-formed UTF-8.  Do not use unless you
B<know> that the STRING is well-formed UTF-8.  Returns the previous
state of the UTF-8 flag (so please don't treat the return value as
indicating success or failure), or C<undef> if STRING is not a string.

=item _utf8_off(STRING)

[INTERNAL] Turns off the UTF-8 flag in STRING.  Do not use frivolously.
Returns the previous state of the UTF-8 flag (so please don't treat the
return value as indicating success or failure), or C<undef> if STRING is
not a string.

=back

=head1 UTF-8 vs. utf8

  ....We now view strings not as sequences of bytes, but as sequences
  of numbers in the range 0 .. 2**32-1 (or in the case of 64-bit
  computers, 0 .. 2**64-1) -- Programming Perl, 3rd ed.

That has been the perl's notion of UTF-8 but official UTF-8 is more
strict; Its ranges is much narrower (0 .. 10FFFF), some sequences are
not allowed (i.e. Those used in the surrogate pair, 0xFFFE, et al).

Now that is overruled by Larry Wall himself.

  From: Larry Wall <larry at wall.org>
  Date: December 04, 2004 11:51:58 JST
  To: perl-unicode at perl.org
  Subject: Re: Make Encode.pm support the real UTF-8
  Message-Id: <20041204025158.GA28754 at wall.org>
  
  On Fri, Dec 03, 2004 at 10:12:12PM +0000, Tim Bunce wrote:
  : I've no problem with 'utf8' being perl's unrestricted uft8 encoding,
  : but "UTF-8" is the name of the standard and should give the
  : corresponding behaviour.
  
  For what it's worth, that's how I've always kept them straight in my
  head.
  
  Also for what it's worth, Perl 6 will mostly default to strict but
  make it easy to switch back to lax.
  
  Larry

Do you copy?  As of Perl 5.8.7, B<UTF-8> means strict, official UTF-8
while B<utf8> means liberal, lax, version thereof.  And Encode version
2.10 or later thus groks the difference between C<UTF-8> and C"utf8".

  encode("utf8",  "\x{FFFF_FFFF}", 1); # okay
  encode("UTF-8", "\x{FFFF_FFFF}", 1); # croaks

C<UTF-8> in Encode is actually a canonical name for C<utf-8-strict>.
Yes, the hyphen between "UTF" and "8" is important.  Without it Encode
goes "liberal"

  find_encoding("UTF-8")->name # is 'utf-8-strict'
  find_encoding("utf-8")->name # ditto. names are case insensitive
  find_encoding("utf8")->name  # ditto. "_" are treated as "-"
  find_encoding("UTF8")->name  # is 'utf8'.


=head1 SEE ALSO

L<Encode::Encoding>,
L<Encode::Supported>,
L<Encode::PerlIO>,
L<encoding>,
L<perlebcdic>,
L<perlfunc/open>,
L<perlunicode>,
L<utf8>,
the Perl Unicode Mailing List E<lt>perl-unicode at perl.orgE<gt>

=head1 MAINTAINER

This project was originated by Nick Ing-Simmons and later maintained
by Dan Kogai E<lt>dankogai at dan.co.jpE<gt>.  See AUTHORS for a full
list of people involved.  For any questions, use
E<lt>perl-unicode at perl.orgE<gt> so we can all share.

=cut

--- NEW FILE: Makefile.PL ---
use 5.007003;
use ExtUtils::MakeMaker;

# Just for sure :)
my %ARGV = map { split /=/; defined $_[1] or $_[1]=1; @_ } @ARGV;
$ARGV{DEBUG} and warn "$_ => $ARGV{$_}\n" for keys  %ARGV;
$ENV{PERL_CORE} ||= $ARGV{PERL_CORE};

my %tables = 
    (
     def_t => ['ascii.ucm',
	       '8859-1.ucm',
	       'null.ucm',
	       'ctrl.ucm',
	       ]
     );

my @exe_files = qw(bin/enc2xs
		   bin/piconv
		   );
my @more_exe_files = qw(
			unidump
			);
my @pmlibdirs = qw(lib Encode);

$ARGV{MORE_SCRIOPTS} and push @exe_files, @more_exe_files;
$ARGV{INSTALL_UCM}   and push @pmlibdirs, "ucm";

WriteMakefile(
	      NAME		=> "Encode",
	      EXE_FILES         => \@exe_files,
	      VERSION_FROM	=> 'Encode.pm',
	      OBJECT		=> '$(O_FILES)',
	      'dist'		=> {
		  COMPRESS	=> 'gzip -9f',
		  SUFFIX	=> 'gz',
		  DIST_DEFAULT => 'all tardist',
	      },
	      MAN3PODS	=> {},
	      INC       => "-I./Encode",
	      PMLIBDIRS => \@pmlibdirs,
	      INSTALLDIRS => 'perl',
	      );

package MY;


sub post_initialize
{
    my ($self) = @_;
    my %o;
    # Find existing O_FILES
    foreach my $f (@{$self->{'O_FILES'}})
    {
	$o{$f} = 1;
    }
    my $x = $self->{'OBJ_EXT'};
    # Add the table O_FILES
    foreach my $e (keys %tables)
    {
	$o{$e.$x} = 1;
    }
    # Trick case-blind filesystems.
    delete $o{'encode'.$x};
    $o{'Encode'.$x} = 1;
    # Reset the variable
    $self->{'O_FILES'} = [sort keys %o];
    my @files;
    foreach my $table (keys %tables)
    {
	foreach my $ext (qw($(OBJ_EXT) .c .h .exh .fnm))
    {
	push (@files,$table.$ext);
    }
    $self->{SOURCE} .= " $table.c"
	if $^O eq 'MacOS' && $self->{SOURCE} !~ /\b$table\.c\b/;
}
$self->{'clean'}{'FILES'} .= join(' ', at files);
return '';
}

sub postamble
{
    my $self = shift;
    my $dir  = $self->catdir($self->curdir,'ucm');
    my $str  = "# Encode\$(OBJ_EXT) does not depend on .c files directly\n";
    $str  .= "# (except Encode.c), but on .h and .exh files written by enc2xs\n";
    $str  .= $^O eq 'MacOS' ? 'Encode.c.{$(MACPERL_BUILD_EXT_STATIC)}.o :' : 'Encode$(OBJ_EXT) :';
    $str  .= ' Encode.c';
    foreach my $table (keys %tables)
    {
	$str .= " $table.c";
    }
    $str .= "\n\n";
    foreach my $table (keys %tables)
    {
	my $numlines = 1;
	my $lengthsofar = length($str);
	my $continuator = '';
	my $enc2xs = $self->catfile('bin', 'enc2xs');
	$str .= "$table.c : $enc2xs Makefile.PL";
	foreach my $file (@{$tables{$table}})
	{
	    $str .= $continuator.' '.$self->catfile($dir,$file);
	    if ( length($str)-$lengthsofar > 128*$numlines )
	    {
		$continuator .= " \\\n\t";
		$numlines++;
	    } else {
		$continuator = '';
	    }
	}
	my $plib   = $self->{PERL_CORE} ? '"-I$(PERL_LIB)"' : '';
	$plib .= " -MCross=$::Cross::platform" if defined $::Cross::platform;
	my $ucopts = '-"Q" -"O"';
	$str .=
	    qq{\n\t\$(PERL) $plib $enc2xs $ucopts -o \$\@ -f $table.fnm\n\n};
	open (FILELIST, ">$table.fnm")
	    || die "Could not open $table.fnm: $!";
	foreach my $file (@{$tables{$table}})
	{
	    print FILELIST $self->catfile($dir,$file) . "\n";
	}
	close(FILELIST);
    }
    return $str;
}

--- NEW FILE: Changes ---
# Revision history for Perl extension Encode.
#
# $Id: Changes,v 1.1 2006-12-05 04:26:33 dslinux_cayenne Exp $
#
$Revision: 1.1 $ $Date: 2006-12-05 04:26:33 $
! Encode.xs Encode.pm t/fallback.t
  Now accepts coderef for CHECK!
! ucm/8859-7.ucm
  Updated to newer version at unicode.org
  http://rt.cpan.org/NoAuth/Bug.html?id=14222
! lib/Encode/Supported.pod
  More POD typo fixed.
  <42F5E243.80500 at gmail.com>
! encoding.pm
  More POD typo leftover fixed.
  Message-Id: <b77c1dce05080615487f95314 at mail.gmail.com>

2.11  2005/08/05 10:58:25
! AUTHORS CHANGES
[...1748 lines suppressed...]
  perl-unicode at perl.org archive, available at:
  http://archive.develooper.com/perl-unicode@perl.org/

  Changes Since 0.92 includes;
+ Changes
+ AUTHORS
! Encode.pm
! README
  + Mention to perl-unicode at perl.org added
! JP/JP.pm
  + Encoding aliases added so you can feed locale names
    and MIME Charset="" directly.
  - Mention to JISX0212 removed because it's fixed
! CN/CN.pm
! KR/KR.pm
  + Encoding aliases added.  Note TW is left untouched because
    euc-tw is not implemented in TW but in Encode::HanExtra.
    Autrijus, you may fix Encode::HanExtra.
+ t/CJKalias.t
  + to test encode aliases added

--- NEW FILE: META.yml ---
# http://module-build.sourceforge.net/META-spec.html
#XXXXXXX This is a prototype!!!  It will change in the future!!! XXXXX#
name:         Encode
version:      2.12
version_from: Encode.pm
installdirs:  perl
requires:

distribution_type: module
generated_by: ExtUtils::MakeMaker version 6.17

--- NEW FILE: encoding.pm ---
# $Id: encoding.pm,v 1.1 2006-12-05 04:26:33 dslinux_cayenne Exp $
package encoding;
our $VERSION = do { my @r = (q$Revision: 1.1 $ =~ /\d+/g); sprintf "%d."."%02d" x $#r, @r };

use Encode;
use strict;

sub DEBUG () { 0 }

BEGIN {
    if (ord("A") == 193) {
	require Carp;
	Carp::croak("encoding: pragma does not support EBCDIC platforms");
    }
}

our $HAS_PERLIO = 0;
eval { require PerlIO::encoding };
unless ($@){
    $HAS_PERLIO = (PerlIO::encoding->VERSION >= 0.02);
}

sub _exception{
    my $name = shift;
    $] > 5.008 and return 0;               # 5.8.1 or higher then no
    my %utfs = map {$_=>1}
	qw(utf8 UCS-2BE UCS-2LE UTF-16 UTF-16BE UTF-16LE
	   UTF-32 UTF-32BE UTF-32LE);
    $utfs{$name} or return 0;               # UTFs or no
    require Config; Config->import(); our %Config;
    return $Config{perl_patchlevel} ? 0 : 1 # maintperl then no
}

sub in_locale { $^H & ($locale::hint_bits || 0)}

sub _get_locale_encoding {
    my $locale_encoding;

    # I18N::Langinfo isn't available everywhere
    eval {
	require I18N::Langinfo;
	I18N::Langinfo->import(qw(langinfo CODESET));
	$locale_encoding = langinfo(CODESET());
    };
    
    my $country_language;

    no warnings 'uninitialized';

    if (not $locale_encoding && in_locale()) {
	if ($ENV{LC_ALL} =~ /^([^.]+)\.([^.]+)$/) {
	    ($country_language, $locale_encoding) = ($1, $2);
	} elsif ($ENV{LANG} =~ /^([^.]+)\.([^.]+)$/) {
	    ($country_language, $locale_encoding) = ($1, $2);
	}
	# LANGUAGE affects only LC_MESSAGES only on glibc
    } elsif (not $locale_encoding) {
	if ($ENV{LC_ALL} =~ /\butf-?8\b/i ||
	    $ENV{LANG}   =~ /\butf-?8\b/i) {
	    $locale_encoding = 'utf8';
	}
	# Could do more heuristics based on the country and language
	# parts of LC_ALL and LANG (the parts before the dot (if any)),
	# since we have Locale::Country and Locale::Language available.
	# TODO: get a database of Language -> Encoding mappings
	# (the Estonian database at http://www.eki.ee/letter/
	# would be excellent!) --jhi
    }
    if (defined $locale_encoding &&
	lc($locale_encoding) eq 'euc' &&
	defined $country_language) {
	if ($country_language =~ /^ja_JP|japan(?:ese)?$/i) {
	    $locale_encoding = 'euc-jp';
	} elsif ($country_language =~ /^ko_KR|korean?$/i) {
	    $locale_encoding = 'euc-kr';
	} elsif ($country_language =~ /^zh_CN|chin(?:a|ese)?$/i) {
	    $locale_encoding = 'euc-cn';
	} elsif ($country_language =~ /^zh_TW|taiwan(?:ese)?$/i) {
	    $locale_encoding = 'euc-tw';
	} else {
	    require Carp;
	    Carp::croak("encoding: Locale encoding '$locale_encoding' too ambiguous");
	}
    }

    return $locale_encoding;
}

sub import {
    my $class = shift;
    my $name  = shift;
    if ($name eq ':_get_locale_encoding') { # used by lib/open.pm
	my $caller = caller();
        {
	    no strict 'refs';
	    *{"${caller}::_get_locale_encoding"} = \&_get_locale_encoding;
	}
	return;
    }
    $name = _get_locale_encoding() if $name eq ':locale';
    my %arg = @_;
    $name = $ENV{PERL_ENCODING} unless defined $name;
    my $enc = find_encoding($name);
    unless (defined $enc) {
	require Carp;
	Carp::croak("encoding: Unknown encoding '$name'");
    }
    $name = $enc->name; # canonize
    unless ($arg{Filter}) {
	DEBUG and warn "_exception($name) = ", _exception($name);
	_exception($name) or ${^ENCODING} = $enc;
	$HAS_PERLIO or return 1;
    }else{
	defined(${^ENCODING}) and undef ${^ENCODING};
	# implicitly 'use utf8'
	require utf8; # to fetch $utf8::hint_bits;
	$^H |= $utf8::hint_bits;
	eval {
	    require Filter::Util::Call ;
	    Filter::Util::Call->import ;
	    filter_add(sub{
			   my $status = filter_read();
                           if ($status > 0){
			       $_ = $enc->decode($_, 1);
			       DEBUG and warn $_;
			   }
			   $status ;
		       });
	};
        $@ eq '' and DEBUG and warn "Filter installed";
    }
    defined ${^UNICODE} and ${^UNICODE} != 0 and return 1;
    for my $h (qw(STDIN STDOUT)){
	if ($arg{$h}){
	    unless (defined find_encoding($arg{$h})) {
		require Carp;
		Carp::croak("encoding: Unknown encoding for $h, '$arg{$h}'");
	    }
	    eval { binmode($h, ":raw :encoding($arg{$h})") };
	}else{
	    unless (exists $arg{$h}){
		eval { 
		    no warnings 'uninitialized';
		    binmode($h, ":raw :encoding($name)");
		};
	    }
	}
	if ($@){
	    require Carp;
	    Carp::croak($@);
	}
    }
    return 1; # I doubt if we need it, though
}

sub unimport{
    no warnings;
    undef ${^ENCODING};
    if ($HAS_PERLIO){
	binmode(STDIN,  ":raw");
	binmode(STDOUT, ":raw");
    }else{
	binmode(STDIN);
	binmode(STDOUT);
    }
    if ($INC{"Filter/Util/Call.pm"}){
	eval { filter_del() };
    }
}

1;
__END__

=pod

=head1 NAME

encoding - allows you to write your script in non-ascii or non-utf8

=head1 SYNOPSIS

  use encoding "greek";  # Perl like Greek to you?
  use encoding "euc-jp"; # Jperl!

  # or you can even do this if your shell supports your native encoding

  perl -Mencoding=latin2 -e '...' # Feeling centrally European?
  perl -Mencoding=euc-kr -e '...' # Or Korean?

  # more control

  # A simple euc-cn => utf-8 converter
  use encoding "euc-cn", STDOUT => "utf8";  while(<>){print};

  # "no encoding;" supported (but not scoped!)
  no encoding;

  # an alternate way, Filter
  use encoding "euc-jp", Filter=>1;
  # now you can use kanji identifiers -- in euc-jp!

  # switch on locale -
  # note that this probably means that unless you have a complete control
  # over the environments the application is ever going to be run, you should
  # NOT use the feature of encoding pragma allowing you to write your script
  # in any recognized encoding because changing locale settings will wreck
  # the script; you can of course still use the other features of the pragma.
  use encoding ':locale';

=head1 ABSTRACT

Let's start with a bit of history: Perl 5.6.0 introduced Unicode
support.  You could apply C<substr()> and regexes even to complex CJK
characters -- so long as the script was written in UTF-8.  But back
then, text editors that supported UTF-8 were still rare and many users
instead chose to write scripts in legacy encodings, giving up a whole
new feature of Perl 5.6.

Rewind to the future: starting from perl 5.8.0 with the B<encoding>
pragma, you can write your script in any encoding you like (so long
as the C<Encode> module supports it) and still enjoy Unicode support.
This pragma achieves that by doing the following:

=over

=item *

Internally converts all literals (C<q//,qq//,qr//,qw///, qx//>) from
the encoding specified to utf8.  In Perl 5.8.1 and later, literals in
C<tr///> and C<DATA> pseudo-filehandle are also converted.

=item *

Changing PerlIO layers of C<STDIN> and C<STDOUT> to the encoding
 specified.

=back

=head2 Literal Conversions

You can write code in EUC-JP as follows:

  my $Rakuda = "\xF1\xD1\xF1\xCC"; # Camel in Kanji
               #<-char-><-char->   # 4 octets
  s/\bCamel\b/$Rakuda/;

And with C<use encoding "euc-jp"> in effect, it is the same thing as
the code in UTF-8:

  my $Rakuda = "\x{99F1}\x{99DD}"; # two Unicode Characters
  s/\bCamel\b/$Rakuda/;

=head2 PerlIO layers for C<STD(IN|OUT)>

The B<encoding> pragma also modifies the filehandle layers of
STDIN and STDOUT to the specified encoding.  Therefore,

  use encoding "euc-jp";
  my $message = "Camel is the symbol of perl.\n";
  my $Rakuda = "\xF1\xD1\xF1\xCC"; # Camel in Kanji
  $message =~ s/\bCamel\b/$Rakuda/;
  print $message;

Will print "\xF1\xD1\xF1\xCC is the symbol of perl.\n",
not "\x{99F1}\x{99DD} is the symbol of perl.\n".

You can override this by giving extra arguments; see below.

=head2 Implicit upgrading for byte strings

By default, if strings operating under byte semantics and strings
with Unicode character data are concatenated, the new string will
be created by decoding the byte strings as I<ISO 8859-1 (Latin-1)>.

The B<encoding> pragma changes this to use the specified encoding
instead.  For example:

    use encoding 'utf8';
    my $string = chr(20000); # a Unicode string
    utf8::encode($string);   # now it's a UTF-8 encoded byte string
    # concatenate with another Unicode string
    print length($string . chr(20000));

Will print C<2>, because C<$string> is upgraded as UTF-8.  Without
C<use encoding 'utf8';>, it will print C<4> instead, since C<$string>
is three octets when interpreted as Latin-1.

=head1 FEATURES THAT REQUIRE 5.8.1

Some of the features offered by this pragma requires perl 5.8.1.  Most
of these are done by Inaba Hiroto.  Any other features and changes
are good for 5.8.0.

=over

=item "NON-EUC" doublebyte encodings

Because perl needs to parse script before applying this pragma, such
encodings as Shift_JIS and Big-5 that may contain '\' (BACKSLASH;
\x5c) in the second byte fails because the second byte may
accidentally escape the quoting character that follows.  Perl 5.8.1
or later fixes this problem.

=item tr// 

C<tr//> was overlooked by Perl 5 porters when they released perl 5.8.0
See the section below for details.

=item DATA pseudo-filehandle

Another feature that was overlooked was C<DATA>. 

=back

=head1 USAGE

=over 4

=item use encoding [I<ENCNAME>] ;

Sets the script encoding to I<ENCNAME>.  And unless ${^UNICODE} 
exists and non-zero, PerlIO layers of STDIN and STDOUT are set to
":encoding(I<ENCNAME>)".

Note that STDERR WILL NOT be changed.

Also note that non-STD file handles remain unaffected.  Use C<use
open> or C<binmode> to change layers of those.

If no encoding is specified, the environment variable L<PERL_ENCODING>
is consulted.  If no encoding can be found, the error C<Unknown encoding
'I<ENCNAME>'> will be thrown.

=item use encoding I<ENCNAME> [ STDIN =E<gt> I<ENCNAME_IN> ...] ;

You can also individually set encodings of STDIN and STDOUT via the
C<< STDIN => I<ENCNAME> >> form.  In this case, you cannot omit the
first I<ENCNAME>.  C<< STDIN => undef >> turns the IO transcoding
completely off.

When ${^UNICODE} exists and non-zero, these options will completely
ignored.  ${^UNICODE} is a variable introduced in perl 5.8.1.  See
L<perlrun> see L<perlvar/"${^UNICODE}"> and L<perlrun/"-C"> for
details (perl 5.8.1 and later).

=item use encoding I<ENCNAME> Filter=E<gt>1;

This turns the encoding pragma into a source filter.  While the
default approach just decodes interpolated literals (in qq() and
qr()), this will apply a source filter to the entire source code.  See
L</"The Filter Option"> below for details.

=item no encoding;

Unsets the script encoding. The layers of STDIN, STDOUT are
reset to ":raw" (the default unprocessed raw stream of bytes).

=back

=head1 The Filter Option

The magic of C<use encoding> is not applied to the names of
identifiers.  In order to make C<${"\x{4eba}"}++> ($human++, where human
is a single Han ideograph) work, you still need to write your script
in UTF-8 -- or use a source filter.  That's what 'Filter=>1' does.

What does this mean?  Your source code behaves as if it is written in
UTF-8 with 'use utf8' in effect.  So even if your editor only supports
Shift_JIS, for example, you can still try examples in Chapter 15 of
C<Programming Perl, 3rd Ed.>.  For instance, you can use UTF-8
identifiers.

This option is significantly slower and (as of this writing) non-ASCII
identifiers are not very stable WITHOUT this option and with the
source code written in UTF-8.

=head2 Filter-related changes at Encode version 1.87

=over

=item *

The Filter option now sets STDIN and STDOUT like non-filter options.
And C<< STDIN=>I<ENCODING> >> and C<< STDOUT=>I<ENCODING> >> work like
non-filter version.

=item *

C<use utf8> is implicitly declared so you no longer have to C<use
utf8> to C<${"\x{4eba}"}++>.

=back

=head1 CAVEATS

=head2 NOT SCOPED

The pragma is a per script, not a per block lexical.  Only the last
C<use encoding> or C<no encoding> matters, and it affects 
B<the whole script>.  However, the <no encoding> pragma is supported and 
B<use encoding> can appear as many times as you want in a given script. 
The multiple use of this pragma is discouraged.

By the same reason, the use this pragma inside modules is also
discouraged (though not as strongly discouraged as the case above.  
See below).

If you still have to write a module with this pragma, be very careful
of the load order.  See the codes below;

  # called module
  package Module_IN_BAR;
  use encoding "bar";
  # stuff in "bar" encoding here
  1;

  # caller script
  use encoding "foo"
  use Module_IN_BAR;
  # surprise! use encoding "bar" is in effect.

The best way to avoid this oddity is to use this pragma RIGHT AFTER
other modules are loaded.  i.e.

  use Module_IN_BAR;
  use encoding "foo";

=head2 DO NOT MIX MULTIPLE ENCODINGS

Notice that only literals (string or regular expression) having only
legacy code points are affected: if you mix data like this

	\xDF\x{100}

the data is assumed to be in (Latin 1 and) Unicode, not in your native
encoding.  In other words, this will match in "greek":

	"\xDF" =~ /\x{3af}/

but this will not

	"\xDF\x{100}" =~ /\x{3af}\x{100}/

since the C<\xDF> (ISO 8859-7 GREEK SMALL LETTER IOTA WITH TONOS) on
the left will B<not> be upgraded to C<\x{3af}> (Unicode GREEK SMALL
LETTER IOTA WITH TONOS) because of the C<\x{100}> on the left.  You
should not be mixing your legacy data and Unicode in the same string.

This pragma also affects encoding of the 0x80..0xFF code point range:
normally characters in that range are left as eight-bit bytes (unless
they are combined with characters with code points 0x100 or larger,
in which case all characters need to become UTF-8 encoded), but if
the C<encoding> pragma is present, even the 0x80..0xFF range always
gets UTF-8 encoded.

After all, the best thing about this pragma is that you don't have to
resort to \x{....} just to spell your name in a native encoding.
So feel free to put your strings in your encoding in quotes and
regexes.

=head2 tr/// with ranges

The B<encoding> pragma works by decoding string literals in
C<q//,qq//,qr//,qw///, qx//> and so forth.  In perl 5.8.0, this
does not apply to C<tr///>.  Therefore,

  use encoding 'euc-jp';
  #....
  $kana =~ tr/\xA4\xA1-\xA4\xF3/\xA5\xA1-\xA5\xF3/;
  #           -------- -------- -------- --------

Does not work as

  $kana =~ tr/\x{3041}-\x{3093}/\x{30a1}-\x{30f3}/;

=over

=item Legend of characters above

  utf8     euc-jp   charnames::viacode()
  -----------------------------------------
  \x{3041} \xA4\xA1 HIRAGANA LETTER SMALL A
  \x{3093} \xA4\xF3 HIRAGANA LETTER N
  \x{30a1} \xA5\xA1 KATAKANA LETTER SMALL A
  \x{30f3} \xA5\xF3 KATAKANA LETTER N

=back

This counterintuitive behavior has been fixed in perl 5.8.1.

=head3 workaround to tr///;

In perl 5.8.0, you can work around as follows;

  use encoding 'euc-jp';
  #  ....
  eval qq{ \$kana =~ tr/\xA4\xA1-\xA4\xF3/\xA5\xA1-\xA5\xF3/ };

Note the C<tr//> expression is surrounded by C<qq{}>.  The idea behind
is the same as classic idiom that makes C<tr///> 'interpolate'.

   tr/$from/$to/;            # wrong!
   eval qq{ tr/$from/$to/ }; # workaround.

Nevertheless, in case of B<encoding> pragma even C<q//> is affected so
C<tr///> not being decoded was obviously against the will of Perl5
Porters so it has been fixed in Perl 5.8.1 or later.

=head1 EXAMPLE - Greekperl

    use encoding "iso 8859-7";

    # \xDF in ISO 8859-7 (Greek) is \x{3af} in Unicode.

    $a = "\xDF";
    $b = "\x{100}";

    printf "%#x\n", ord($a); # will print 0x3af, not 0xdf

    $c = $a . $b;

    # $c will be "\x{3af}\x{100}", not "\x{df}\x{100}".

    # chr() is affected, and ...

    print "mega\n"  if ord(chr(0xdf)) == 0x3af;

    # ... ord() is affected by the encoding pragma ...

    print "tera\n" if ord(pack("C", 0xdf)) == 0x3af;

    # ... as are eq and cmp ...

    print "peta\n" if "\x{3af}" eq  pack("C", 0xdf);
    print "exa\n"  if "\x{3af}" cmp pack("C", 0xdf) == 0;

    # ... but pack/unpack C are not affected, in case you still
    # want to go back to your native encoding

    print "zetta\n" if unpack("C", (pack("C", 0xdf))) == 0xdf;

=head1 KNOWN PROBLEMS

=over

=item literals in regex that are longer than 127 bytes

For native multibyte encodings (either fixed or variable length),
the current implementation of the regular expressions may introduce
recoding errors for regular expression literals longer than 127 bytes.

=item EBCDIC

The encoding pragma is not supported on EBCDIC platforms.
(Porters who are willing and able to remove this limitation are
welcome.)

=item format

This pragma doesn't work well with format because PerlIO does not
get along very well with it.  When format contains non-ascii
characters it prints funny or gets "wide character warnings".
To understand it, try the code below.

  # Save this one in utf8
  # replace *non-ascii* with a non-ascii string
  my $camel;
  format STDOUT =
  *non-ascii*@>>>>>>>
  $camel
  .
  $camel = "*non-ascii*";
  binmode(STDOUT=>':encoding(utf8)'); # bang!
  write;              # funny 
  print $camel, "\n"; # fine

Without binmode this happens to work but without binmode, print()
fails instead of write().

At any rate, the very use of format is questionable when it comes to
unicode characters since you have to consider such things as character
width (i.e. double-width for ideographs) and directions (i.e. BIDI for
Arabic and Hebrew).

=back

=head2 The Logic of :locale

The logic of C<:locale> is as follows:

=over 4

=item 1.

If the platform supports the langinfo(CODESET) interface, the codeset
returned is used as the default encoding for the open pragma.

=item 2.

If 1. didn't work but we are under the locale pragma, the environment
variables LC_ALL and LANG (in that order) are matched for encodings
(the part after C<.>, if any), and if any found, that is used 
as the default encoding for the open pragma.

=item 3.

If 1. and 2. didn't work, the environment variables LC_ALL and LANG
(in that order) are matched for anything looking like UTF-8, and if
any found, C<:utf8> is used as the default encoding for the open
pragma.

=back

If your locale environment variables (LC_ALL, LC_CTYPE, LANG)
contain the strings 'UTF-8' or 'UTF8' (case-insensitive matching),
the default encoding of your STDIN, STDOUT, and STDERR, and of
B<any subsequent file open>, is UTF-8.

=head1 HISTORY

This pragma first appeared in Perl 5.8.0.  For features that require 
5.8.1 and better, see above.

The C<:locale> subpragma was implemented in 2.01, or Perl 5.8.6.

=head1 SEE ALSO

L<perlunicode>, L<Encode>, L<open>, L<Filter::Util::Call>,

Ch. 15 of C<Programming Perl (3rd Edition)>
by Larry Wall, Tom Christiansen, Jon Orwant;
O'Reilly & Associates; ISBN 0-596-00027-8

=cut

--- NEW FILE: MANIFEST ---
AUTHORS		List of authors
Byte/Byte.pm	Encode extension
Byte/Makefile.PL       Encode extension
CN/CN.pm		Encode extension
CN/Makefile.PL	Encode extension
Changes		Change Log
EBCDIC/EBCDIC.pm       Encode extension
EBCDIC/Makefile.PL     Encode extension
Encode.pm	       Mother of all Encode extensions
Encode.xs		Encode extension
Encode/Changes.e2x		Skeleton file for enc2xs
Encode/ConfigLocal_PM.e2x	Skeleton file for enc2xs
Encode/Makefile_PL.e2x	Skeleton file for enc2xs
Encode/README.e2x		Skeleton file for enc2xs
Encode/_PM.e2x		Skeleton file for enc2xs
Encode/_T.e2x		Skeleton file for enc2xs
Encode/encode.h		Encode extension header file
JP/JP.pm		Encode extension
JP/Makefile.PL	Encode extension
KR/KR.pm		Encode extension
KR/Makefile.PL		Encode extension
MANIFEST		Encode extension
META.yml                                Module meta-data in YAML
Makefile.PL		Encode extension makefile writer
README		Encode extension
Symbol/Makefile.PL     Encode extension
Symbol/Symbol.pm       Encode extension
TW/Makefile.PL	Encode extension
TW/TW.pm		Encode extension
Unicode/Makefile.PL	Encode extension
Unicode/Unicode.pm	Encode extension
Unicode/Unicode.xs	Encode extension
bin/enc2xs	Encode module generator
bin/piconv	iconv by perl
bin/ucm2table	Table Generator for testing
bin/ucmlint	A UCM Lint utility
bin/ucmsort	Sorts UCM lines
bin/unidump	Unicode Dump like hexdump(1)
encengine.c		Encode extension
encoding.pm	Perl Pragmactic Module
lib/Encode/Alias.pm	        Encode extension
lib/Encode/CJKConstants.pm	Encode extension
lib/Encode/CN/HZ.pm		Encode extension
lib/Encode/Config.pm	        Encode configuration module
lib/Encode/Encoder.pm	       OO Encoder
lib/Encode/Encoding.pm	Encode extension
lib/Encode/Guess.pm	Encode Extension
lib/Encode/JP/H2Z.pm		Encode extension
lib/Encode/JP/JIS7.pm	Encode extension
lib/Encode/KR/2022_KR.pm	 Encode extension
lib/Encode/MIME/Header.pm	Encode extension
lib/Encode/MIME/Header/ISO_2022_JP.pm  Encode extension
lib/Encode/PerlIO.pod	Documents for Encode & PerlIO
lib/Encode/Supported.pod	Documents for supported encodings
lib/Encode/Unicode/UTF7.pm Encode Extension
t/Aliases.t	test script
t/CJKT.t	test script
t/Encode.t	test script
t/Encoder.t	test script
t/Mod_EUCJP.pm	module that t/enc_module.enc uses
t/Unicode.t	test script
t/at-cn.t	test script
t/at-tw.t	test script
t/big5-eten.enc	test data
t/big5-eten.utf	test data
t/big5-hkscs.enc	test data
t/big5-hkscs.utf	test data
t/enc_data.t		test script for encoding.pm vs. DATA fh
t/enc_eucjp.t	test script
t/enc_module.enc test data for t/enc_module.t
t/enc_module.t	test script
t/enc_utf8.t	test script
t/encoding.t	test script
t/fallback.t	test script
t/gb2312.enc	test data
t/gb2312.utf	test data
t/grow.t	test script
t/gsm0338.t	test script
t/guess.t	test script
t/jisx0201.enc	test data
t/jisx0201.utf	test data
t/jisx0208.enc	test data
t/jisx0208.utf	test data
t/jisx0212.enc	test data
t/jisx0212.utf	test data
t/jperl.t	test script
t/ksc5601.enc	test data
t/ksc5601.utf	test data
t/mime-header.t	test script
t/mime_header_iso2022jp.t  test script
t/perlio.t	test script
t/rt.pl		even more test script
t/unibench.pl	benchmark script
t/utf8strict.t	test script
ucm/8859-1.ucm	Unicode Character Map
ucm/8859-10.ucm	Unicode Character Map
ucm/8859-11.ucm	Unicode Character Map
ucm/8859-13.ucm	Unicode Character Map
ucm/8859-14.ucm	Unicode Character Map
ucm/8859-15.ucm	Unicode Character Map
ucm/8859-16.ucm	Unicode Character Map
ucm/8859-2.ucm	Unicode Character Map
ucm/8859-3.ucm	Unicode Character Map
ucm/8859-4.ucm	Unicode Character Map
ucm/8859-5.ucm	Unicode Character Map
ucm/8859-6.ucm	Unicode Character Map
ucm/8859-7.ucm	Unicode Character Map
ucm/8859-8.ucm	Unicode Character Map
ucm/8859-9.ucm	Unicode Character Map
ucm/adobeStdenc.ucm	Unicode Character Map
ucm/adobeSymbol.ucm	Unicode Character Map
ucm/adobeZdingbat.ucm	Unicode Character Map
ucm/ascii.ucm	Unicode Character Map
ucm/big5-eten.ucm	Unicode Character Map
ucm/big5-hkscs.ucm	Unicode Character Map
ucm/cp037.ucm	Unicode Character Map
ucm/cp1006.ucm	Unicode Character Map
ucm/cp1026.ucm	Unicode Character Map
ucm/cp1047.ucm	Unicode Character Map
ucm/cp1250.ucm	Unicode Character Map
ucm/cp1251.ucm	Unicode Character Map
ucm/cp1252.ucm	Unicode Character Map
ucm/cp1253.ucm	Unicode Character Map
ucm/cp1254.ucm	Unicode Character Map
ucm/cp1255.ucm	Unicode Character Map
ucm/cp1256.ucm	Unicode Character Map
ucm/cp1257.ucm	Unicode Character Map
ucm/cp1258.ucm	Unicode Character Map
ucm/cp424.ucm	Unicode Character Map
ucm/cp437.ucm	Unicode Character Map
ucm/cp500.ucm	Unicode Character Map
ucm/cp737.ucm	Unicode Character Map
ucm/cp775.ucm	Unicode Character Map
ucm/cp850.ucm	Unicode Character Map
ucm/cp852.ucm	Unicode Character Map
ucm/cp855.ucm	Unicode Character Map
ucm/cp856.ucm	Unicode Character Map
ucm/cp857.ucm	Unicode Character Map
ucm/cp860.ucm	Unicode Character Map
ucm/cp861.ucm	Unicode Character Map
ucm/cp862.ucm	Unicode Character Map
ucm/cp863.ucm	Unicode Character Map
ucm/cp864.ucm	Unicode Character Map
ucm/cp865.ucm	Unicode Character Map
ucm/cp866.ucm	Unicode Character Map
ucm/cp869.ucm	Unicode Character Map
ucm/cp874.ucm	Unicode Character Map
ucm/cp875.ucm	Unicode Character Map
ucm/cp932.ucm	Unicode Character Map
ucm/cp936.ucm	Unicode Character Map
ucm/cp949.ucm	Unicode Character Map
ucm/cp950.ucm	Unicode Character Map
ucm/ctrl.ucm	Unicode Character Map
ucm/dingbats.ucm	Unicode Character Map
ucm/euc-cn.ucm	Unicode Character Map
ucm/euc-jp.ucm	Unicode Character Map
ucm/euc-kr.ucm	Unicode Character Map
ucm/gb12345.ucm	Unicode Character Map
ucm/gb2312.ucm	Unicode Character Map
ucm/gsm0338.ucm	Unicode Character Map
ucm/hp-roman8.ucm	Unicode Character Map
ucm/ir-165.ucm	Unicode Character Map
ucm/jis0201.ucm	Unicode Character Map
ucm/jis0208.ucm	Unicode Character Map
ucm/jis0212.ucm	Unicode Character Map
ucm/johab.ucm	Unicode Character Map
ucm/koi8-f.ucm	Unicode Character Map
ucm/koi8-r.ucm	Unicode Character Map
ucm/koi8-u.ucm	Unicode Character Map
ucm/ksc5601.ucm	Unicode Character Map
ucm/macArabic.ucm	Unicode Character Map
ucm/macCentEuro.ucm	Unicode Character Map
ucm/macChinsimp.ucm	Unicode Character Map
ucm/macChintrad.ucm	Unicode Character Map
ucm/macCroatian.ucm	Unicode Character Map
ucm/macCyrillic.ucm	Unicode Character Map
ucm/macDingbats.ucm	Unicode Character Map
ucm/macFarsi.ucm	Unicode Character Map
ucm/macGreek.ucm	Unicode Character Map
ucm/macHebrew.ucm	Unicode Character Map
ucm/macIceland.ucm	Unicode Character Map
ucm/macJapanese.ucm	Unicode Character Map
ucm/macKorean.ucm	Unicode Character Map
ucm/macROMnn.ucm	Unicode Character Map
ucm/macRUMnn.ucm	Unicode Character Map
ucm/macRoman.ucm	Unicode Character Map
ucm/macSami.ucm	Unicode Character Map
ucm/macSymbol.ucm	Unicode Character Map
ucm/macThai.ucm	Unicode Character Map
ucm/macTurkish.ucm	Unicode Character Map
ucm/macUkraine.ucm	Unicode Character Map
ucm/nextstep.ucm	Unicode Character Map
ucm/null.ucm	Unicode Character Map
ucm/posix-bc.ucm	Unicode Character Map
ucm/shiftjis.ucm	Unicode Character Map
ucm/symbol.ucm	Unicode Character Map
ucm/viscii.ucm	Unicode Character Map

--- NEW FILE: Encode.xs ---
/*
 $Id: Encode.xs,v 1.1 2006-12-05 04:26:33 dslinux_cayenne Exp $
 */

#define PERL_NO_GET_CONTEXT
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
#define U8 U8
#include "encode.h"

# define PERLIO_MODNAME  "PerlIO::encoding"
# define PERLIO_FILENAME "PerlIO/encoding.pm"

/* set 1 or more to profile.  t/encoding.t dumps core because of
   Perl_warner and PerlIO don't work well */
#define ENCODE_XS_PROFILE 0

/* set 0 to disable floating point to calculate buffer size for
   encode_method().  1 is recommended. 2 restores NI-S original */
#define ENCODE_XS_USEFP   1

#define UNIMPLEMENTED(x,y) y x (SV *sv, char *encoding) {dTHX;   \
                         Perl_croak(aTHX_ "panic_unimplemented"); \
			 return (y)0; /* fool picky compilers */ \
                         }
/**/

UNIMPLEMENTED(_encoded_utf8_to_bytes, I32)
UNIMPLEMENTED(_encoded_bytes_to_utf8, I32)

#define UTF8_ALLOW_STRICT 0
#define UTF8_ALLOW_NONSTRICT (UTF8_ALLOW_ANY &                    \
                              ~(UTF8_ALLOW_CONTINUATION |         \
                                UTF8_ALLOW_NON_CONTINUATION |     \
                                UTF8_ALLOW_LONG))

static SV* fallback_cb = (SV*)NULL ;

void
Encode_XSEncoding(pTHX_ encode_t * enc)
{
    dSP;
    HV *stash = gv_stashpv("Encode::XS", TRUE);
    SV *sv = sv_bless(newRV_noinc(newSViv(PTR2IV(enc))), stash);
    int i = 0;
    PUSHMARK(sp);
    XPUSHs(sv);
    while (enc->name[i]) {
	const char *name = enc->name[i++];
	XPUSHs(sv_2mortal(newSVpvn(name, strlen(name))));
    }
    PUTBACK;
    call_pv("Encode::define_encoding", G_DISCARD);
    SvREFCNT_dec(sv);
}

void
call_failure(SV * routine, U8 * done, U8 * dest, U8 * orig)
{
    /* Exists for breakpointing */
}


#define ERR_ENCODE_NOMAP "\"\\x{%04" UVxf "}\" does not map to %s"
#define ERR_DECODE_NOMAP "%s \"\\x%02" UVXf "\" does not map to Unicode"

static SV *
do_fallback_cb(pTHX_ UV ch)
{
    dSP;
    int argc;
    SV* retval;
    ENTER;
    SAVETMPS;
    PUSHMARK(sp);
    XPUSHs(sv_2mortal(newSVnv((UV)ch)));
    PUTBACK;
    argc = call_sv(fallback_cb, G_SCALAR);
    SPAGAIN;
    if (argc != 1){
	croak("fallback sub must return scalar!");
    }
    retval = newSVsv(POPs);
    PUTBACK;
    FREETMPS;
    LEAVE;
    return retval;
}

static SV *
encode_method(pTHX_ encode_t * enc, encpage_t * dir, SV * src,
	      int check, STRLEN * offset, SV * term, int * retcode)
{
    STRLEN slen;
    U8 *s = (U8 *) SvPV(src, slen);
    STRLEN tlen  = slen;
    STRLEN ddone = 0;
    STRLEN sdone = 0;

    /* We allocate slen+1.
       PerlIO dumps core if this value is smaller than this. */
    SV *dst = sv_2mortal(newSV(slen+1));
    U8 *d = (U8 *)SvPVX(dst);
    STRLEN dlen = SvLEN(dst)-1;
    int code = 0;
    STRLEN trmlen = 0;
    U8 *trm = term ? (U8*) SvPV(term, trmlen) : NULL;

    if (offset) {
      s += *offset;
      if (slen > *offset){ /* safeguard against slen overflow */
	  slen -= *offset;
      }else{
	  slen = 0;
      }
      tlen = slen;
    }

    if (slen == 0){
	SvCUR_set(dst, 0);
	SvPOK_only(dst);
	goto ENCODE_END;
    }

    while( (code = do_encode(dir, s, &slen, d, dlen, &dlen, !check,
			     trm, trmlen)) ) 
    {
	SvCUR_set(dst, dlen+ddone);
	SvPOK_only(dst);
	
	if (code == ENCODE_FALLBACK || code == ENCODE_PARTIAL ||
	    code == ENCODE_FOUND_TERM) {
	    break;
	}
	switch (code) {
	case ENCODE_NOSPACE:
	{	
	    STRLEN more = 0; /* make sure you initialize! */
	    STRLEN sleft;
	    sdone += slen;
	    ddone += dlen;
	    sleft = tlen - sdone;
#if ENCODE_XS_PROFILE >= 2
	    Perl_warn(aTHX_
		      "more=%d, sdone=%d, sleft=%d, SvLEN(dst)=%d\n",
		      more, sdone, sleft, SvLEN(dst));
#endif
	    if (sdone != 0) { /* has src ever been processed ? */
#if   ENCODE_XS_USEFP == 2
		more = (1.0*tlen*SvLEN(dst)+sdone-1)/sdone
		    - SvLEN(dst);
#elif ENCODE_XS_USEFP
		more = (STRLEN)((1.0*SvLEN(dst)+1)/sdone * sleft);
#else
		/* safe until SvLEN(dst) == MAX_INT/16 */
		more = (16*SvLEN(dst)+1)/sdone/16 * sleft;
#endif
	    }
	    more += UTF8_MAXLEN; /* insurance policy */
	    d = (U8 *) SvGROW(dst, SvLEN(dst) + more);
	    /* dst need to grow need MORE bytes! */
	    if (ddone >= SvLEN(dst)) {
		Perl_croak(aTHX_ "Destination couldn't be grown.");
	    }
	    dlen = SvLEN(dst)-ddone-1;
	    d   += ddone;
	    s   += slen;
	    slen = tlen-sdone;
	    continue;
	}
	case ENCODE_NOREP:
	    /* encoding */	
	    if (dir == enc->f_utf8) {
		STRLEN clen;
		UV ch =
		    utf8n_to_uvuni(s+slen, (SvCUR(src)-slen),
				   &clen, UTF8_ALLOW_ANY|UTF8_CHECK_ONLY);
		/* if non-representable multibyte prefix at end of current buffer - break*/
		if (clen > tlen - sdone) break;
		if (check & ENCODE_DIE_ON_ERR) {
		    Perl_croak(aTHX_ ERR_ENCODE_NOMAP,
			       (UV)ch, enc->name[0]);
		    return &PL_sv_undef; /* never reaches but be safe */
		}
		if (check & ENCODE_WARN_ON_ERR){
		    Perl_warner(aTHX_ packWARN(WARN_UTF8),
				ERR_ENCODE_NOMAP, (UV)ch, enc->name[0]);
		}
		if (check & ENCODE_RETURN_ON_ERR){
		    goto ENCODE_SET_SRC;
		}
		if (check & (ENCODE_PERLQQ|ENCODE_HTMLCREF|ENCODE_XMLCREF)){
		    SV* subchar = 
			(fallback_cb != (SV*)NULL) ? do_fallback_cb(aTHX_ ch) :
			newSVpvf(check & ENCODE_PERLQQ ? "\\x{%04"UVxf"}" :
				 check & ENCODE_HTMLCREF ? "&#%" UVuf ";" :
				 "&#x%" UVxf ";", (UV)ch);
		    sdone += slen + clen;
		    ddone += dlen + SvCUR(subchar);
		    sv_catsv(dst, subchar);
		    SvREFCNT_dec(subchar);
		} else {
		    /* fallback char */
		    sdone += slen + clen;
		    ddone += dlen + enc->replen;
		    sv_catpvn(dst, (char*)enc->rep, enc->replen);
		}
	    }
	    /* decoding */
	    else {
		if (check & ENCODE_DIE_ON_ERR){
		    Perl_croak(aTHX_ ERR_DECODE_NOMAP,
                              enc->name[0], (UV)s[slen]);
		    return &PL_sv_undef; /* never reaches but be safe */
		}
		if (check & ENCODE_WARN_ON_ERR){
		    Perl_warner(
			aTHX_ packWARN(WARN_UTF8),
			ERR_DECODE_NOMAP,
               	        enc->name[0], (UV)s[slen]);
		}
		if (check & ENCODE_RETURN_ON_ERR){
		    goto ENCODE_SET_SRC;
		}
		if (check &
		    (ENCODE_PERLQQ|ENCODE_HTMLCREF|ENCODE_XMLCREF)){
		    SV* subchar = 
			(fallback_cb != (SV*)NULL) ? 
			do_fallback_cb(aTHX_ (UV)s[slen]) :
			newSVpvf("\\x%02" UVXf, (UV)s[slen]);
		    sdone += slen + 1;
		    ddone += dlen + SvCUR(subchar);
		    sv_catsv(dst, subchar);
		    SvREFCNT_dec(subchar);
		} else {
		    sdone += slen + 1;
		    ddone += dlen + strlen(FBCHAR_UTF8);
		    sv_catpv(dst, FBCHAR_UTF8);
		}
	    }
	    /* settle variables when fallback */
	    d    = (U8 *)SvEND(dst);
            dlen = SvLEN(dst) - ddone - 1;
	    s    = (U8*)SvPVX(src) + sdone;
	    slen = tlen - sdone;
	    break;

	default:
	    Perl_croak(aTHX_ "Unexpected code %d converting %s %s",
		       code, (dir == enc->f_utf8) ? "to" : "from",
		       enc->name[0]);
	    return &PL_sv_undef;
	}
    }
 ENCODE_SET_SRC:
    if (check && !(check & ENCODE_LEAVE_SRC)){
	sdone = SvCUR(src) - (slen+sdone);
	if (sdone) {
	    sv_setpvn(src, (char*)s+slen, sdone);
	}
	SvCUR_set(src, sdone);
    }
    /* warn("check = 0x%X, code = 0x%d\n", check, code); */

    SvCUR_set(dst, dlen+ddone);
    SvPOK_only(dst);

#if ENCODE_XS_PROFILE
    if (SvCUR(dst) > SvCUR(src)){
	Perl_warn(aTHX_
		  "SvLEN(dst)=%d, SvCUR(dst)=%d. %d bytes unused(%f %%)\n",
		  SvLEN(dst), SvCUR(dst), SvLEN(dst) - SvCUR(dst),
		  (SvLEN(dst) - SvCUR(dst))*1.0/SvLEN(dst)*100.0);
    }
#endif

    if (offset) 
      *offset += sdone + slen;

 ENCODE_END:
    *SvEND(dst) = '\0';
    if (retcode) *retcode = code;
    return dst;
}

static bool
strict_utf8(pTHX_ SV* sv)
{
    HV* hv;
    SV** svp;
    sv = SvRV(sv);
    if (!sv || SvTYPE(sv) != SVt_PVHV)
        return 0;
    hv = (HV*)sv;
    svp = hv_fetch(hv, "strict_utf8", 11, 0);
    if (!svp)
        return 0;
    return SvTRUE(*svp);
}

static U8*
process_utf8(pTHX_ SV* dst, U8* s, U8* e, int check,
             bool encode, bool strict, bool stop_at_partial)
{
    UV uv;
    STRLEN ulen;

    SvPOK_only(dst);
    SvCUR_set(dst,0);

    while (s < e) {
        if (UTF8_IS_INVARIANT(*s)) {
            sv_catpvn(dst, (char *)s, 1);
            s++;
            continue;
        }

        if (UTF8_IS_START(*s)) {
            U8 skip = UTF8SKIP(s);
            if ((s + skip) > e) {
                /* Partial character */
                /* XXX could check that rest of bytes are UTF8_IS_CONTINUATION(ch) */
                if (stop_at_partial || (check & ENCODE_STOP_AT_PARTIAL))
                    break;

                goto malformed_byte;
            }

            uv = utf8n_to_uvuni(s, e - s, &ulen,
                                UTF8_CHECK_ONLY | (strict ? UTF8_ALLOW_STRICT :
                                                            UTF8_ALLOW_NONSTRICT)
                               );
#if 1 /* perl-5.8.6 and older do not check UTF8_ALLOW_LONG */
	    if (strict && uv > PERL_UNICODE_MAX)
		ulen = -1;
#endif
            if (ulen == -1) {
                if (strict) {
                    uv = utf8n_to_uvuni(s, e - s, &ulen,
                                        UTF8_CHECK_ONLY | UTF8_ALLOW_NONSTRICT);
                    if (ulen == -1)
                        goto malformed_byte;
                    goto malformed;
                }
                goto malformed_byte;
            }


             /* Whole char is good */
             sv_catpvn(dst,(char *)s,skip);
             s += skip;
             continue;
        }

        /* If we get here there is something wrong with alleged UTF-8 */
    malformed_byte:
        uv = (UV)*s;
        ulen = 1;

    malformed:
        if (check & ENCODE_DIE_ON_ERR){
            if (encode)
                Perl_croak(aTHX_ ERR_ENCODE_NOMAP, uv, "utf8");
            else
                Perl_croak(aTHX_ ERR_DECODE_NOMAP, "utf8", uv);
        }
        if (check & ENCODE_WARN_ON_ERR){
            if (encode)
                Perl_warner(aTHX_ packWARN(WARN_UTF8),
                            ERR_ENCODE_NOMAP, uv, "utf8");
            else
                Perl_warner(aTHX_ packWARN(WARN_UTF8),
                            ERR_DECODE_NOMAP, "utf8", uv);
        }
        if (check & ENCODE_RETURN_ON_ERR) {
                break;
        }
        if (check & (ENCODE_PERLQQ|ENCODE_HTMLCREF|ENCODE_XMLCREF)){
            SV* subchar = newSVpvf(check & ENCODE_PERLQQ ? (ulen == 1 ? "\\x%02" UVXf : "\\x{%04" UVXf "}"):
                                   check & ENCODE_HTMLCREF ? "&#%" UVuf ";" :
                                   "&#x%" UVxf ";", uv);
            sv_catsv(dst, subchar);
            SvREFCNT_dec(subchar);
        } else {
            sv_catpv(dst, FBCHAR_UTF8);
        }
        s += ulen;
    }
    *SvEND(dst) = '\0';

    return s;
}


MODULE = Encode		PACKAGE = Encode::utf8	PREFIX = Method_

PROTOTYPES: DISABLE

void
Method_decode_xs(obj,src,check = 0)
SV *	obj
SV *	src
int	check
CODE:
{
    STRLEN slen;
    U8 *s = (U8 *) SvPV(src, slen);
    U8 *e = (U8 *) SvEND(src);
    SV *dst = newSV(slen>0?slen:1); /* newSV() abhors 0 -- inaba */

    /* 
     * PerlIO check -- we assume the object is of PerlIO if renewed
     */
    int renewed = 0;
    dSP; ENTER; SAVETMPS;
    PUSHMARK(sp);
    XPUSHs(obj);
    PUTBACK;
    if (call_method("renewed",G_SCALAR) == 1) {
	SPAGAIN;
	renewed = POPi;
	PUTBACK; 
#if 0
	fprintf(stderr, "renewed == %d\n", renewed);
#endif
    }
    FREETMPS; LEAVE;
    /* end PerlIO check */

    if (SvUTF8(src)) {
	s = utf8_to_bytes(s,&slen);
	if (s) {
	    SvCUR_set(src,slen);
	    SvUTF8_off(src);
	    e = s+slen;
	}
	else {
	    croak("Cannot decode string with wide characters");
	}
    }

    s = process_utf8(aTHX_ dst, s, e, check, 0, strict_utf8(aTHX_ obj), renewed);

    /* Clear out translated part of source unless asked not to */
    if (check && !(check & ENCODE_LEAVE_SRC)){
	slen = e-s;
	if (slen) {
	    sv_setpvn(src, (char*)s, slen);
	}
	SvCUR_set(src, slen);
    }
    SvUTF8_on(dst);
    ST(0) = sv_2mortal(dst);
    XSRETURN(1);
}

void
Method_encode_xs(obj,src,check = 0)
SV *	obj
SV *	src
int	check
CODE:
{
    STRLEN slen;
    U8 *s = (U8 *) SvPV(src, slen);
    U8 *e = (U8 *) SvEND(src);
    SV *dst = newSV(slen>0?slen:1); /* newSV() abhors 0 -- inaba */
    if (SvUTF8(src)) {
	/* Already encoded */
	if (strict_utf8(aTHX_ obj)) {
	    s = process_utf8(aTHX_ dst, s, e, check, 1, 1, 0);
	}
        else {
            /* trust it and just copy the octets */
    	    sv_setpvn(dst,(char *)s,(e-s));
	    s = e;
        }
    }
    else {
    	/* Native bytes - can always encode */
	U8 *d = (U8 *) SvGROW(dst, 2*slen+1); /* +1 or assertion will botch */
    	while (s < e) {
    	    UV uv = NATIVE_TO_UNI((UV) *s++);
            if (UNI_IS_INVARIANT(uv))
            	*d++ = (U8)UTF_TO_NATIVE(uv);
            else {
    	        *d++ = (U8)UTF8_EIGHT_BIT_HI(uv);
                *d++ = (U8)UTF8_EIGHT_BIT_LO(uv);
            }
	}
        SvCUR_set(dst, d- (U8 *)SvPVX(dst));
    	*SvEND(dst) = '\0';
    }

    /* Clear out translated part of source unless asked not to */
    if (check && !(check & ENCODE_LEAVE_SRC)){
	slen = e-s;
	if (slen) {
	    sv_setpvn(src, (char*)s, slen);
	}
	SvCUR_set(src, slen);
    }
    SvPOK_only(dst);
    SvUTF8_off(dst);
    ST(0) = sv_2mortal(dst);
    XSRETURN(1);
}

MODULE = Encode		PACKAGE = Encode::XS	PREFIX = Method_

PROTOTYPES: ENABLE

void
Method_renew(obj)
SV *	obj
CODE:
{
    XSRETURN(1);
}

int
Method_renewed(obj)
SV *    obj
CODE:
    RETVAL = 0;
OUTPUT:
    RETVAL

void
Method_name(obj)
SV *	obj
CODE:
{
    encode_t *enc = INT2PTR(encode_t *, SvIV(SvRV(obj)));
    ST(0) = sv_2mortal(newSVpvn(enc->name[0],strlen(enc->name[0])));
    XSRETURN(1);
}

void
Method_cat_decode(obj, dst, src, off, term, check = 0)
SV *	obj
SV *	dst
SV *	src
SV *	off
SV *	term
int	check
CODE:
{
    encode_t *enc = INT2PTR(encode_t *, SvIV(SvRV(obj)));
    STRLEN offset = (STRLEN)SvIV(off);
    int code = 0;
    if (SvUTF8(src)) {
    	sv_utf8_downgrade(src, FALSE);
    }
    sv_catsv(dst, encode_method(aTHX_ enc, enc->t_utf8, src, check,
				&offset, term, &code));
    SvIV_set(off, (IV)offset);
    if (code == ENCODE_FOUND_TERM) {
	ST(0) = &PL_sv_yes;
    }else{
	ST(0) = &PL_sv_no;
    }
    XSRETURN(1);
}

void
Method_decode(obj,src,check_sv = &PL_sv_no)
SV *	obj
SV *	src
SV *	check_sv
CODE:
{
    int check;
    encode_t *enc = INT2PTR(encode_t *, SvIV(SvRV(obj)));
    if (SvUTF8(src)) {
    	sv_utf8_downgrade(src, FALSE);
    }
    if (SvROK(check_sv)){
	if (fallback_cb == (SV*)NULL){
            fallback_cb = newSVsv(check_sv); /* First time */
        }else{
            SvSetSV(fallback_cb, check_sv); /* Been here before */
	}
	check = ENCODE_PERLQQ|ENCODE_LEAVE_SRC; /* same as FB_PERLQQ */
    }else{
	fallback_cb = (SV*)NULL;
	check = SvIV(check_sv);
    }
    ST(0) = encode_method(aTHX_ enc, enc->t_utf8, src, check,
			  NULL, Nullsv, NULL);
    SvUTF8_on(ST(0));
    XSRETURN(1);
}



void
Method_encode(obj,src,check_sv = &PL_sv_no)
SV *	obj
SV *	src
SV *	check_sv
CODE:
{
    int check;
    encode_t *enc = INT2PTR(encode_t *, SvIV(SvRV(obj)));
    sv_utf8_upgrade(src);
    if (SvROK(check_sv)){
	if (fallback_cb == (SV*)NULL){
            fallback_cb = newSVsv(check_sv); /* First time */
        }else{
            SvSetSV(fallback_cb, check_sv); /* Been here before */
	}
	check = ENCODE_PERLQQ|ENCODE_LEAVE_SRC; /* same as FB_PERLQQ */
    }else{
	fallback_cb = (SV*)NULL;
	check = SvIV(check_sv);
    }
    ST(0) = encode_method(aTHX_ enc, enc->f_utf8, src, check,
			  NULL, Nullsv, NULL);
    XSRETURN(1);
}

void
Method_needs_lines(obj)
SV *	obj
CODE:
{
    /* encode_t *enc = INT2PTR(encode_t *, SvIV(SvRV(obj))); */
    ST(0) = &PL_sv_no;
    XSRETURN(1);
}

void
Method_perlio_ok(obj)
SV *	obj
CODE:
{
    /* encode_t *enc = INT2PTR(encode_t *, SvIV(SvRV(obj))); */
    /* require_pv(PERLIO_FILENAME); */

    eval_pv("require PerlIO::encoding", 0);

    if (SvTRUE(get_sv("@", 0))) {
	ST(0) = &PL_sv_no;
    }else{
	ST(0) = &PL_sv_yes;
    }
    XSRETURN(1);
}

MODULE = Encode         PACKAGE = Encode

PROTOTYPES: ENABLE

I32
_bytes_to_utf8(sv, ...)
SV *    sv
CODE:
{
    SV * encoding = items == 2 ? ST(1) : Nullsv;

    if (encoding)
    RETVAL = _encoded_bytes_to_utf8(sv, SvPV_nolen(encoding));
    else {
	STRLEN len;
	U8*    s = (U8*)SvPV(sv, len);
	U8*    converted;

	converted = bytes_to_utf8(s, &len); /* This allocs */
	sv_setpvn(sv, (char *)converted, len);
	SvUTF8_on(sv); /* XXX Should we? */
	Safefree(converted);                /* ... so free it */
	RETVAL = len;
    }
}
OUTPUT:
    RETVAL

I32
_utf8_to_bytes(sv, ...)
SV *    sv
CODE:
{
    SV * to    = items > 1 ? ST(1) : Nullsv;
    SV * check = items > 2 ? ST(2) : Nullsv;

    if (to) {
	RETVAL = _encoded_utf8_to_bytes(sv, SvPV_nolen(to));
    } else {
	STRLEN len;
	U8 *s = (U8*)SvPV(sv, len);

	RETVAL = 0;
	if (SvTRUE(check)) {
	    /* Must do things the slow way */
	    U8 *dest;
            /* We need a copy to pass to check() */
	    U8 *src  = (U8*)savepv((char *)s);
	    U8 *send = s + len;

	    New(83, dest, len, U8); /* I think */

	    while (s < send) {
                if (*s < 0x80){
		    *dest++ = *s++;
                } else {
		    STRLEN ulen;
		    UV uv = *s++;

		    /* Have to do it all ourselves because of error routine,
		       aargh. */
		    if (!(uv & 0x40)){ goto failure; }
		    if      (!(uv & 0x20)) { ulen = 2;  uv &= 0x1f; }
		    else if (!(uv & 0x10)) { ulen = 3;  uv &= 0x0f; }
		    else if (!(uv & 0x08)) { ulen = 4;  uv &= 0x07; }
		    else if (!(uv & 0x04)) { ulen = 5;  uv &= 0x03; }
		    else if (!(uv & 0x02)) { ulen = 6;  uv &= 0x01; }
		    else if (!(uv & 0x01)) { ulen = 7;  uv = 0; }
		    else                   { ulen = 13; uv = 0; }
		
		    /* Note change to utf8.c variable naming, for variety */
		    while (ulen--) {
			if ((*s & 0xc0) != 0x80){
			    goto failure;
			} else {
			    uv = (uv << 6) | (*s++ & 0x3f);
			}
		  }
		  if (uv > 256) {
		  failure:
		      call_failure(check, s, dest, src);
		      /* Now what happens? */
		  }
		  *dest++ = (U8)uv;
		}
	    }
	} else {
	    RETVAL = (utf8_to_bytes(s, &len) ? len : 0);
	}
    }
}
OUTPUT:
    RETVAL

bool
is_utf8(sv, check = 0)
SV *	sv
int	check
CODE:
{
    if (SvGMAGICAL(sv)) /* it could be $1, for example */
	sv = newSVsv(sv); /* GMAGIG will be done */
    if (SvPOK(sv)) {
	RETVAL = SvUTF8(sv) ? TRUE : FALSE;
	if (RETVAL &&
	    check  &&
	    !is_utf8_string((U8*)SvPVX(sv), SvCUR(sv)))
	    RETVAL = FALSE;
    } else {
	RETVAL = FALSE;
    }
    if (sv != ST(0))
	SvREFCNT_dec(sv); /* it was a temp copy */
}
OUTPUT:
    RETVAL

SV *
_utf8_on(sv)
SV *	sv
CODE:
{
    if (SvPOK(sv)) {
	SV *rsv = newSViv(SvUTF8(sv));
	RETVAL = rsv;
	SvUTF8_on(sv);
    } else {
	RETVAL = &PL_sv_undef;
    }
}
OUTPUT:
    RETVAL

SV *
_utf8_off(sv)
SV *	sv
CODE:
{
    if (SvPOK(sv)) {
	SV *rsv = newSViv(SvUTF8(sv));
	RETVAL = rsv;
	SvUTF8_off(sv);
    } else {
	RETVAL = &PL_sv_undef;
    }
}
OUTPUT:
    RETVAL

int
DIE_ON_ERR()
CODE:
    RETVAL = ENCODE_DIE_ON_ERR;
OUTPUT:
    RETVAL

int
WARN_ON_ERR()
CODE:
    RETVAL = ENCODE_WARN_ON_ERR;
OUTPUT:
    RETVAL

int
LEAVE_SRC()
CODE:
    RETVAL = ENCODE_LEAVE_SRC;
OUTPUT:
    RETVAL

int
RETURN_ON_ERR()
CODE:
    RETVAL = ENCODE_RETURN_ON_ERR;
OUTPUT:
    RETVAL

int
PERLQQ()
CODE:
    RETVAL = ENCODE_PERLQQ;
OUTPUT:
    RETVAL

int
HTMLCREF()
CODE:
    RETVAL = ENCODE_HTMLCREF;
OUTPUT:
    RETVAL

int
XMLCREF()
CODE:
    RETVAL = ENCODE_XMLCREF;
OUTPUT:
    RETVAL

int
STOP_AT_PARTIAL()
CODE:
    RETVAL = ENCODE_STOP_AT_PARTIAL;
OUTPUT:
    RETVAL

int
FB_DEFAULT()
CODE:
    RETVAL = ENCODE_FB_DEFAULT;
OUTPUT:
    RETVAL

int
FB_CROAK()
CODE:
    RETVAL = ENCODE_FB_CROAK;
OUTPUT:
    RETVAL

int
FB_QUIET()
CODE:
    RETVAL = ENCODE_FB_QUIET;
OUTPUT:
    RETVAL

int
FB_WARN()
CODE:
    RETVAL = ENCODE_FB_WARN;
OUTPUT:
    RETVAL

int
FB_PERLQQ()
CODE:
    RETVAL = ENCODE_FB_PERLQQ;
OUTPUT:
    RETVAL

int
FB_HTMLCREF()
CODE:
    RETVAL = ENCODE_FB_HTMLCREF;
OUTPUT:
    RETVAL

int
FB_XMLCREF()
CODE:
    RETVAL = ENCODE_FB_XMLCREF;
OUTPUT:
    RETVAL

BOOT:
{
#include "def_t.h"
#include "def_t.exh"
}

--- NEW FILE: AUTHORS ---
# To give due honour to those who have made the Encode module what it
# is today, here are easily-from-changelogs-extractable people and their
# (hopefully) current and preferred email addresses (as of early 2002,
# if known).
#
# The use of this database for anything else than Encode and/or Perl 
# development is strictly forbidden.  (Passive distribution with the Perl 
# source code kit or CPAN is, of course, allowed.)
#
# This list is in alphabetical order.
--
Andreas J. Koenig		<andreas.koenig at anima.de>
Anton Tagunov			<tagunov at motor.ru>
Autrijus Tang			<autrijus at autrijus.org>
Benjamin Goldberg		<goldbb2 at earthlink.net>
Bjoern Hoehrmann		<derhoermi at gmx.net>
Bjoern Jacke			<debianbugs at j3e.de>
Chris Nandor			<pudge at pobox.com>
Craig A. Berry			<craigberry at mac.com>
Dan Kogai			<dankogai at dan.co.jp>
Dave Evans			<dave at rudolf.org.uk>
Deng Liu			<dengliu at ntu.edu.tw>
Dominic Dunlop			<domo at computer.org>
Elizabeth Mattijsen		<liz at dijkmat.nl>
Gerrit P. Haase			<gp at familiehaase.de>
Graham Barr			<gbarr at pobox.com>
Gurusamy Sarathy		<gsar at activestate.com>
H.Merijn Brand			<h.m.brand at xs4all.nl>
Hugo van der Sanden		<hv at crypt.org>
Inaba Hiroto			<inaba at st.rim.or.jp>
Jarkko Hietaniemi		<jhi at iki.fi>
Jungshik Shin			<jshin at mailaps.org>
KONNO Hiroharu			<hiroharu.konno at bowneglobal.co.jp>
Laszlo Molnar			<ml1050 at freemail.hu>
MORIYAMA Masayuki		<msyk at mtg.biglobe.ne.jp>
Makamaka			<makamaka at donzoko.net>
Mark-Jason Dominus		<mjd at plover.com>
Mattia Barbon			<mbarbon at dsi.unive.it>
Michael G Schwern		<schwern at pobox.com>
Miron Cuperman			<miron at hyper.to>
Nicholas Clark			<nick at ccl4.org>
Nick Ing-Simmons		<nick at ing-simmons.net>
Paul Marquess			<paul_marquess at yahoo.co.uk>
Peter Prymmer			<pvhp at best.com>
Philip Newton			<pne at cpan.org>
Piotr Fusik			<pfusik at op.pl>
Rafael Garcia-Suarez		<rgarciasuarez at mandriva.com>
Robin Barker			<rmb1 at cise.npl.co.uk>
SADAHIRO Tomoyuki		<SADAHIRO at cpan.org>
SUGAWARA Hajime			<sugawara at hdt.co.jp>
SUZUKI Norio			<ZAP00217 at nifty.com>
Simon Cozens			<simon at netthink.co.uk>
Spider Boardman			<spider at web.zk3.dec.com>
Steve Hay			<steve.hay at uk.radan.com>
Steve Peters			<steve at fisharerojo.org>
Tatsuhiko Miyagawa		<miyagawa at edge.co.jp>
Tels				<perl_dummy at bloodgate.com>
Vadim Konovalov			<vkonovalov at peterstar.ru>
Yitzchak Scott-Thoennes		<sthoenna at efn.org>

--- NEW FILE: README ---
NAME
       Encode - character encodings

SYNOPSIS
           use Encode;

DESCRIPTION
       The "Encode" module provides the interfaces between Perl's
       strings and the rest of the system.  Perl strings are
       sequences of characters.

       See "perldoc Encode" for the rest of the story

INSTALLATION

To install this module, type the following:

   perl Makefile.PL
   make
   make test
   make install

To install scripts under bin/ directories also,

   perl Makefile.PL MORE_SCRIPTS
   make && make test && make install

By default, only enc2xs and piconv are installed.

To install *.ucm files also, say

   perl Makefile.PL INSTALL_UCM
   make && make test && make install

By default, *.ucm are not installed.

DEPENDENCIES

This module requires perl5.7.3 or later.

MAINTAINER

This project was originated by Nick Ing-Simmons and later maintained by
Dan Kogai <dankogai at dan.co.jp>.  See AUTHORS for the full list of people
involved.

QUESTIONS?

If you have any questions which "perldoc Encode" does not answer, please
feel free to ask at perl-unicode at perl.org.

--- NEW FILE: encengine.c ---
/*
Data structures for encoding transformations.

Perl works internally in either a native 'byte' encoding or
in UTF-8 encoded Unicode.  We have no immediate need for a "wchar_t"
representation. When we do we can use utf8_to_uv().

Most character encodings are either simple byte mappings or
variable length multi-byte encodings. UTF-8 can be viewed as a
rather extreme case of the latter.

So to solve an important part of perl's encode needs we need to solve the
"multi-byte -> multi-byte" case. The simple byte forms are then just degenerate
case. (Where one of multi-bytes will usually be UTF-8.)

The other type of encoding is a shift encoding where a prefix sequence
determines what subsequent bytes mean. Such encodings have state.

We also need to handle case where a character in one encoding has to be
represented as multiple characters in the other. e.g. letter+diacritic.

The process can be considered as pseudo perl:

my $dst = '';
while (length($src))
 {
  my $size    = $count($src);
  my $in_seq  = substr($src,0,$size,'');
  my $out_seq = $s2d_hash{$in_seq};
  if (defined $out_seq)
   {
    $dst .= $out_seq;
   }
  else
   {
    # an error condition
   }
 }
return $dst;

That has the following components:
 &src_count - a "rule" for how many bytes make up the next character in the
              source.
 %s2d_hash  - a mapping from input sequences to output sequences

The problem with that scheme is that it does not allow the output
character repertoire to affect the characters considered from the
input.

So we use a "trie" representation which can also be considered
a state machine:

my $dst   = '';
my $seq   = \@s2d_seq;
my $next  = \@s2d_next;
while (length($src))
 {
  my $byte    = $substr($src,0,1,'');
  my $out_seq = $seq->[$byte];
  if (defined $out_seq)
   {
    $dst .= $out_seq;
   }
  else
   {
    # an error condition
   }
  ($next,$seq) = @$next->[$byte] if $next;
 }
return $dst;

There is now a pair of data structures to represent everything.
It is valid for output sequence at a particular point to
be defined but zero length, that just means "don't know yet".
For the single byte case there is no 'next' so new tables will be the same as
the original tables. For a multi-byte case a prefix byte will flip to the tables
for  the next page (adding nothing to the output), then the tables for the page
will provide the actual output and set tables back to original base page.

This scheme can also handle shift encodings.

A slight enhancement to the scheme also allows for look-ahead - if
we add a flag to re-add the removed byte to the source we could handle
  a" -> ä
  ab -> a (and take b back please)

*/

#include <EXTERN.h>
#include <perl.h>
#define U8 U8
#include "encode.h"

int
do_encode(encpage_t * enc, const U8 * src, STRLEN * slen, U8 * dst,
	  STRLEN dlen, STRLEN * dout, int approx, const U8 *term, STRLEN tlen)
{
    const U8 *s = src;
    const U8 *send = s + *slen;
    const U8 *last = s;
    U8 *d = dst;
    U8 *dend = d + dlen, *dlast = d;
    int code = 0;
    while (s < send) {
	encpage_t *e = enc;
	U8 byte = *s;
	while (byte > e->max)
	    e++;
	if (byte >= e->min && e->slen && (approx || !(e->slen & 0x80))) {
	    const U8 *cend = s + (e->slen & 0x7f);
	    if (cend <= send) {
		STRLEN n;
		if ((n = e->dlen)) {
		    const U8 *out = e->seq + n * (byte - e->min);
		    U8 *oend = d + n;
		    if (dst) {
			if (oend <= dend) {
			    while (d < oend)
				*d++ = *out++;
			}
			else {
			    /* Out of space */
			    code = ENCODE_NOSPACE;
			    break;
			}
		    }
		    else
			d = oend;
		}
		enc = e->next;
		s++;
		if (s == cend) {
		    if (approx && (e->slen & 0x80))
			code = ENCODE_FALLBACK;
		    last = s;
		    if (term && (STRLEN)(d-dlast) == tlen && memEQ(dlast, term, tlen)) {
		      code = ENCODE_FOUND_TERM;
		      break;
		    }
		    dlast = d;
		}
	    }
	    else {
		/* partial source character */
		code = ENCODE_PARTIAL;
		break;
	    }
	}
	else {
	    /* Cannot represent */
	    code = ENCODE_NOREP;
	    break;
	}
    }
    *slen = last - src;
    *dout = d - dst;
    return code;
}




More information about the dslinux-commit mailing list