Upgrade to Encode 2.18
[p5sagit/p5-mst-13.2.git] / ext / Encode / lib / Encode / Encoding.pm
1 package Encode::Encoding;
2
3 # Base class for classes which implement encodings
4 use strict;
5 use warnings;
6 our $VERSION = do { my @r = ( q$Revision: 2.4 $ =~ /\d+/g ); sprintf "%d." . "%02d" x $#r, @r };
7
8 require Encode;
9
10 sub DEBUG { 0 }
11
12 sub Define {
13     my $obj       = shift;
14     my $canonical = shift;
15     $obj = bless { Name => $canonical }, $obj unless ref $obj;
16
17     # warn "$canonical => $obj\n";
18     Encode::define_encoding( $obj, $canonical, @_ );
19 }
20
21 sub name { return shift->{'Name'} }
22
23 # sub renew { return $_[0] }
24
25 sub renew {
26     my $self = shift;
27     my $clone = bless {%$self} => ref($self);
28     $clone->{renewed}++;    # so the caller can see it
29     DEBUG and warn $clone->{renewed};
30     return $clone;
31 }
32
33 sub renewed { return $_[0]->{renewed} || 0 }
34
35 *new_sequence = \&renew;
36
37 sub needs_lines { 0 }
38
39 sub perlio_ok {
40     eval { require PerlIO::encoding };
41     return $@ ? 0 : 1;
42 }
43
44 # (Temporary|legacy) methods
45
46 sub toUnicode   { shift->decode(@_) }
47 sub fromUnicode { shift->encode(@_) }
48
49 #
50 # Needs to be overloaded or just croak
51 #
52
53 sub encode {
54     require Carp;
55     my $obj = shift;
56     my $class = ref($obj) ? ref($obj) : $obj;
57     Carp::croak( $class . "->encode() not defined!" );
58 }
59
60 sub decode {
61     require Carp;
62     my $obj = shift;
63     my $class = ref($obj) ? ref($obj) : $obj;
64     Carp::croak( $class . "->encode() not defined!" );
65 }
66
67 sub DESTROY { }
68
69 1;
70 __END__
71
72 =head1 NAME
73
74 Encode::Encoding - Encode Implementation Base Class
75
76 =head1 SYNOPSIS
77
78   package Encode::MyEncoding;
79   use base qw(Encode::Encoding);
80
81   __PACKAGE__->Define(qw(myCanonical myAlias));
82
83 =head1 DESCRIPTION
84
85 As mentioned in L<Encode>, encodings are (in the current
86 implementation at least) defined as objects. The mapping of encoding
87 name to object is via the C<%Encode::Encoding> hash.  Though you can
88 directly manipulate this hash, it is strongly encouraged to use this
89 base class module and add encode() and decode() methods.
90
91 =head2 Methods you should implement
92
93 You are strongly encouraged to implement methods below, at least
94 either encode() or decode().
95
96 =over 4
97
98 =item -E<gt>encode($string [,$check])
99
100 MUST return the octet sequence representing I<$string>. 
101
102 =over 2
103
104 =item *
105
106 If I<$check> is true, it SHOULD modify I<$string> in place to remove
107 the converted part (i.e.  the whole string unless there is an error).
108 If perlio_ok() is true, SHOULD becomes MUST.
109
110 =item *
111
112 If an error occurs, it SHOULD return the octet sequence for the
113 fragment of string that has been converted and modify $string in-place
114 to remove the converted part leaving it starting with the problem
115 fragment.  If perlio_ok() is true, SHOULD becomes MUST.
116
117 =item *
118
119 If I<$check> is is false then C<encode> MUST  make a "best effort" to
120 convert the string - for example, by using a replacement character.
121
122 =back
123
124 =item -E<gt>decode($octets [,$check])
125
126 MUST return the string that I<$octets> represents. 
127
128 =over 2
129
130 =item *
131
132 If I<$check> is true, it SHOULD modify I<$octets> in place to remove
133 the converted part (i.e.  the whole sequence unless there is an
134 error).  If perlio_ok() is true, SHOULD becomes MUST.
135
136 =item *
137
138 If an error occurs, it SHOULD return the fragment of string that has
139 been converted and modify $octets in-place to remove the converted
140 part leaving it starting with the problem fragment.  If perlio_ok() is
141 true, SHOULD becomes MUST.
142
143 =item *
144
145 If I<$check> is false then C<decode> should make a "best effort" to
146 convert the string - for example by using Unicode's "\x{FFFD}" as a
147 replacement character.
148
149 =back
150
151 =back
152
153 If you want your encoding to work with L<encoding> pragma, you should
154 also implement the method below.
155
156 =over 4
157
158 =item -E<gt>cat_decode($destination, $octets, $offset, $terminator [,$check])
159
160 MUST decode I<$octets> with I<$offset> and concatenate it to I<$destination>.
161 Decoding will terminate when $terminator (a string) appears in output.
162 I<$offset> will be modified to the last $octets position at end of decode.
163 Returns true if $terminator appears output, else returns false.
164
165 =back
166
167 =head2 Other methods defined in Encode::Encodings
168
169 You do not have to override methods shown below unless you have to.
170
171 =over 4
172
173 =item -E<gt>name
174
175 Predefined As:
176
177   sub name  { return shift->{'Name'} }
178
179 MUST return the string representing the canonical name of the encoding.
180
181 =item -E<gt>renew
182
183 Predefined As:
184
185   sub renew {
186     my $self = shift;
187     my $clone = bless { %$self } => ref($self);
188     $clone->{renewed}++;
189     return $clone;
190   }
191
192 This method reconstructs the encoding object if necessary.  If you need
193 to store the state during encoding, this is where you clone your object.
194
195 PerlIO ALWAYS calls this method to make sure it has its own private
196 encoding object.
197
198 =item -E<gt>renewed
199
200 Predefined As:
201
202   sub renewed { $_[0]->{renewed} || 0 }
203
204 Tells whether the object is renewed (and how many times).  Some
205 modules emit C<Use of uninitialized value in null operation> warning
206 unless the value is numeric so return 0 for false.
207
208 =item -E<gt>perlio_ok()
209
210 Predefined As:
211
212   sub perlio_ok { 
213       eval{ require PerlIO::encoding };
214       return $@ ? 0 : 1;
215   }
216
217 If your encoding does not support PerlIO for some reasons, just;
218
219  sub perlio_ok { 0 }
220
221 =item -E<gt>needs_lines()
222
223 Predefined As:
224
225   sub needs_lines { 0 };
226
227 If your encoding can work with PerlIO but needs line buffering, you
228 MUST define this method so it returns true.  7bit ISO-2022 encodings
229 are one example that needs this.  When this method is missing, false
230 is assumed.
231
232 =back
233
234 =head2 Example: Encode::ROT13
235
236   package Encode::ROT13;
237   use strict;
238   use base qw(Encode::Encoding);
239
240   __PACKAGE__->Define('rot13');
241
242   sub encode($$;$){
243       my ($obj, $str, $chk) = @_;
244       $str =~ tr/A-Za-z/N-ZA-Mn-za-m/;
245       $_[1] = '' if $chk; # this is what in-place edit means
246       return $str;
247   }
248
249   # Jr pna or ynml yvxr guvf;
250   *decode = \&encode;
251
252   1;
253
254 =head1 Why the heck Encode API is different?
255
256 It should be noted that the I<$check> behaviour is different from the
257 outer public API. The logic is that the "unchecked" case is useful
258 when the encoding is part of a stream which may be reporting errors
259 (e.g. STDERR).  In such cases, it is desirable to get everything
260 through somehow without causing additional errors which obscure the
261 original one. Also, the encoding is best placed to know what the
262 correct replacement character is, so if that is the desired behaviour
263 then letting low level code do it is the most efficient.
264
265 By contrast, if I<$check> is true, the scheme above allows the
266 encoding to do as much as it can and tell the layer above how much
267 that was. What is lacking at present is a mechanism to report what
268 went wrong. The most likely interface will be an additional method
269 call to the object, or perhaps (to avoid forcing per-stream objects
270 on otherwise stateless encodings) an additional parameter.
271
272 It is also highly desirable that encoding classes inherit from
273 C<Encode::Encoding> as a base class. This allows that class to define
274 additional behaviour for all encoding objects.
275
276   package Encode::MyEncoding;
277   use base qw(Encode::Encoding);
278
279   __PACKAGE__->Define(qw(myCanonical myAlias));
280
281 to create an object with C<< bless {Name => ...}, $class >>, and call
282 define_encoding.  They inherit their C<name> method from
283 C<Encode::Encoding>.
284
285 =head2 Compiled Encodings
286
287 For the sake of speed and efficiency, most of the encodings are now
288 supported via a I<compiled form>: XS modules generated from UCM
289 files.   Encode provides the enc2xs tool to achieve that.  Please see
290 L<enc2xs> for more details.
291
292 =head1 SEE ALSO
293
294 L<perlmod>, L<enc2xs>
295
296 =begin future
297
298 =over 4
299
300 =item Scheme 1
301
302 The fixup routine gets passed the remaining fragment of string being
303 processed.  It modifies it in place to remove bytes/characters it can
304 understand and returns a string used to represent them.  For example:
305
306  sub fixup {
307    my $ch = substr($_[0],0,1,'');
308    return sprintf("\x{%02X}",ord($ch);
309  }
310
311 This scheme is close to how the underlying C code for Encode works,
312 but gives the fixup routine very little context.
313
314 =item Scheme 2
315
316 The fixup routine gets passed the original string, an index into
317 it of the problem area, and the output string so far.  It appends
318 what it wants to the output string and returns a new index into the
319 original string.  For example:
320
321  sub fixup {
322    # my ($s,$i,$d) = @_;
323    my $ch = substr($_[0],$_[1],1);
324    $_[2] .= sprintf("\x{%02X}",ord($ch);
325    return $_[1]+1;
326  }
327
328 This scheme gives maximal control to the fixup routine but is more
329 complicated to code, and may require that the internals of Encode be tweaked to
330 keep the original string intact.
331
332 =item Other Schemes
333
334 Hybrids of the above.
335
336 Multiple return values rather than in-place modifications.
337
338 Index into the string could be C<pos($str)> allowing C<s/\G...//>.
339
340 =back
341
342 =end future
343
344 =cut