1 /**********************************************************************
2
3 encoding.c -
4
5 $Author: nobu $
6 created at: Thu May 24 17:23:27 JST 2007
7
8 Copyright (C) 2007 Yukihiro Matsumoto
9
10 **********************************************************************/
11
12 #include "ruby/encoding.h"
13 #include "internal.h"
14 #include "encindex.h"
15 #include "regenc.h"
16 #include <ctype.h>
17 #include "ruby/util.h"
18
19 #include "ruby_assert.h"
20 #ifndef ENC_DEBUG
21 #define ENC_DEBUG 0
22 #endif
23 #define ENC_ASSERT (!ENC_DEBUG)?(void)0:assert
24 #define MUST_STRING(str) (ENC_ASSERT(RB_TYPE_P(str, T_STRING)), str)
25
26 #undef rb_ascii8bit_encindex
27 #undef rb_utf8_encindex
28 #undef rb_usascii_encindex
29
30 typedef OnigEncodingType rb_raw_encoding;
31
32 #if defined __GNUC__ && __GNUC__ >= 4
33 #pragma GCC visibility push(default)
34 int rb_enc_register(const char *name, rb_encoding *encoding);
35 void rb_enc_set_base(const char *name, const char *orig);
36 int rb_enc_set_dummy(int index);
37 void rb_encdb_declare(const char *name);
38 int rb_encdb_replicate(const char *name, const char *orig);
39 int rb_encdb_dummy(const char *name);
40 int rb_encdb_alias(const char *alias, const char *orig);
41 void rb_encdb_set_unicode(int index);
42 #pragma GCC visibility pop
43 #endif
44
45 static ID id_encoding;
46 VALUE rb_cEncoding;
47 static VALUE rb_encoding_list;
48
49 struct rb_encoding_entry {
50 const char *name;
51 rb_encoding *enc;
52 rb_encoding *base;
53 };
54
55 static struct {
56 struct rb_encoding_entry *list;
57 int count;
58 int size;
59 st_table *names;
60 } enc_table;
61
62 #define ENC_DUMMY_FLAG (1<<24)
63 #define ENC_INDEX_MASK (~(~0U<<24))
64
65 #define ENC_TO_ENCINDEX(enc) (int)((enc)->ruby_encoding_index & ENC_INDEX_MASK)
66 #define ENC_DUMMY_P(enc) ((enc)->ruby_encoding_index & ENC_DUMMY_FLAG)
67 #define ENC_SET_DUMMY(enc) ((enc)->ruby_encoding_index |= ENC_DUMMY_FLAG)
68
69 void rb_enc_init(void);
70
71 #define ENCODING_COUNT ENCINDEX_BUILTIN_MAX
72 #define UNSPECIFIED_ENCODING INT_MAX
73
74 #define ENCODING_NAMELEN_MAX 63
75 #define valid_encoding_name_p(name) ((name) && strlen(name) <= ENCODING_NAMELEN_MAX)
76
77 #define enc_autoload_p(enc) (!rb_enc_mbmaxlen(enc))
78
79 static int load_encoding(const char *name);
80
81 static const rb_data_type_t encoding_data_type = {
82 "encoding",
83 {0, 0, 0,},
84 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
85 };
86
87 #define is_data_encoding(obj) (RTYPEDDATA_P(obj) && RTYPEDDATA_TYPE(obj) == &encoding_data_type)
88 #define is_obj_encoding(obj) (RB_TYPE_P((obj), T_DATA) && is_data_encoding(obj))
89
90 int
rb_data_is_encoding(VALUE obj)91 rb_data_is_encoding(VALUE obj)
92 {
93 return is_data_encoding(obj);
94 }
95
96 static VALUE
enc_new(rb_encoding * encoding)97 enc_new(rb_encoding *encoding)
98 {
99 return TypedData_Wrap_Struct(rb_cEncoding, &encoding_data_type, (void *)encoding);
100 }
101
102 static VALUE
rb_enc_from_encoding_index(int idx)103 rb_enc_from_encoding_index(int idx)
104 {
105 VALUE list, enc;
106
107 if (!(list = rb_encoding_list)) {
108 rb_bug("rb_enc_from_encoding_index(%d): no rb_encoding_list", idx);
109 }
110 enc = rb_ary_entry(list, idx);
111 if (NIL_P(enc)) {
112 rb_bug("rb_enc_from_encoding_index(%d): not created yet", idx);
113 }
114 return enc;
115 }
116
117 VALUE
rb_enc_from_encoding(rb_encoding * encoding)118 rb_enc_from_encoding(rb_encoding *encoding)
119 {
120 int idx;
121 if (!encoding) return Qnil;
122 idx = ENC_TO_ENCINDEX(encoding);
123 return rb_enc_from_encoding_index(idx);
124 }
125
126 int
rb_enc_to_index(rb_encoding * enc)127 rb_enc_to_index(rb_encoding *enc)
128 {
129 return enc ? ENC_TO_ENCINDEX(enc) : 0;
130 }
131
132 int
rb_enc_dummy_p(rb_encoding * enc)133 rb_enc_dummy_p(rb_encoding *enc)
134 {
135 return ENC_DUMMY_P(enc) != 0;
136 }
137
138 static int enc_autoload(rb_encoding *);
139
140 static int
check_encoding(rb_encoding * enc)141 check_encoding(rb_encoding *enc)
142 {
143 int index = rb_enc_to_index(enc);
144 if (rb_enc_from_index(index) != enc)
145 return -1;
146 if (enc_autoload_p(enc)) {
147 index = enc_autoload(enc);
148 }
149 return index;
150 }
151
152 static int
enc_check_encoding(VALUE obj)153 enc_check_encoding(VALUE obj)
154 {
155 if (!is_obj_encoding(obj)) {
156 return -1;
157 }
158 return check_encoding(RDATA(obj)->data);
159 }
160
161 NORETURN(static void not_encoding(VALUE enc));
162 static void
not_encoding(VALUE enc)163 not_encoding(VALUE enc)
164 {
165 rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (expected Encoding)",
166 rb_obj_class(enc));
167 }
168
169 static rb_encoding *
must_encoding(VALUE enc)170 must_encoding(VALUE enc)
171 {
172 int index = enc_check_encoding(enc);
173 if (index < 0) {
174 not_encoding(enc);
175 }
176 return DATA_PTR(enc);
177 }
178
179 static rb_encoding *
must_encindex(int index)180 must_encindex(int index)
181 {
182 rb_encoding *enc = rb_enc_from_index(index);
183 if (!enc) {
184 rb_raise(rb_eEncodingError, "encoding index out of bound: %d",
185 index);
186 }
187 if (ENC_TO_ENCINDEX(enc) != (int)(index & ENC_INDEX_MASK)) {
188 rb_raise(rb_eEncodingError, "wrong encoding index %d for %s (expected %d)",
189 index, rb_enc_name(enc), ENC_TO_ENCINDEX(enc));
190 }
191 if (enc_autoload_p(enc) && enc_autoload(enc) == -1) {
192 rb_loaderror("failed to load encoding (%s)",
193 rb_enc_name(enc));
194 }
195 return enc;
196 }
197
198 int
rb_to_encoding_index(VALUE enc)199 rb_to_encoding_index(VALUE enc)
200 {
201 int idx;
202
203 idx = enc_check_encoding(enc);
204 if (idx >= 0) {
205 return idx;
206 }
207 else if (NIL_P(enc = rb_check_string_type(enc))) {
208 return -1;
209 }
210 if (!rb_enc_asciicompat(rb_enc_get(enc))) {
211 return -1;
212 }
213 return rb_enc_find_index(StringValueCStr(enc));
214 }
215
216 /* Returns encoding index or UNSPECIFIED_ENCODING */
217 static int
str_find_encindex(VALUE enc)218 str_find_encindex(VALUE enc)
219 {
220 int idx;
221
222 StringValue(enc);
223 if (!rb_enc_asciicompat(rb_enc_get(enc))) {
224 rb_raise(rb_eArgError, "invalid name encoding (non ASCII)");
225 }
226 idx = rb_enc_find_index(StringValueCStr(enc));
227 return idx;
228 }
229
230 static int
str_to_encindex(VALUE enc)231 str_to_encindex(VALUE enc)
232 {
233 int idx = str_find_encindex(enc);
234 if (idx < 0) {
235 rb_raise(rb_eArgError, "unknown encoding name - %"PRIsVALUE, enc);
236 }
237 return idx;
238 }
239
240 static rb_encoding *
str_to_encoding(VALUE enc)241 str_to_encoding(VALUE enc)
242 {
243 return rb_enc_from_index(str_to_encindex(enc));
244 }
245
246 rb_encoding *
rb_to_encoding(VALUE enc)247 rb_to_encoding(VALUE enc)
248 {
249 if (enc_check_encoding(enc) >= 0) return RDATA(enc)->data;
250 return str_to_encoding(enc);
251 }
252
253 rb_encoding *
rb_find_encoding(VALUE enc)254 rb_find_encoding(VALUE enc)
255 {
256 int idx;
257 if (enc_check_encoding(enc) >= 0) return RDATA(enc)->data;
258 idx = str_find_encindex(enc);
259 if (idx < 0) return NULL;
260 return rb_enc_from_index(idx);
261 }
262
263 static int
enc_table_expand(int newsize)264 enc_table_expand(int newsize)
265 {
266 struct rb_encoding_entry *ent;
267 int count = newsize;
268
269 if (enc_table.size >= newsize) return newsize;
270 newsize = (newsize + 7) / 8 * 8;
271 ent = realloc(enc_table.list, sizeof(*enc_table.list) * newsize);
272 if (!ent) return -1;
273 memset(ent + enc_table.size, 0, sizeof(*ent)*(newsize - enc_table.size));
274 enc_table.list = ent;
275 enc_table.size = newsize;
276 return count;
277 }
278
279 static int
enc_register_at(int index,const char * name,rb_encoding * base_encoding)280 enc_register_at(int index, const char *name, rb_encoding *base_encoding)
281 {
282 struct rb_encoding_entry *ent = &enc_table.list[index];
283 rb_raw_encoding *encoding;
284 VALUE list;
285
286 if (!valid_encoding_name_p(name)) return -1;
287 if (!ent->name) {
288 ent->name = name = strdup(name);
289 }
290 else if (STRCASECMP(name, ent->name)) {
291 return -1;
292 }
293 encoding = (rb_raw_encoding *)ent->enc;
294 if (!encoding) {
295 encoding = xmalloc(sizeof(rb_encoding));
296 }
297 if (base_encoding) {
298 *encoding = *base_encoding;
299 }
300 else {
301 memset(encoding, 0, sizeof(*ent->enc));
302 }
303 encoding->name = name;
304 encoding->ruby_encoding_index = index;
305 ent->enc = encoding;
306 st_insert(enc_table.names, (st_data_t)name, (st_data_t)index);
307 list = rb_encoding_list;
308 if (list && NIL_P(rb_ary_entry(list, index))) {
309 /* initialize encoding data */
310 rb_ary_store(list, index, enc_new(encoding));
311 }
312 return index;
313 }
314
315 static int
enc_register(const char * name,rb_encoding * encoding)316 enc_register(const char *name, rb_encoding *encoding)
317 {
318 int index = enc_table.count;
319
320 if ((index = enc_table_expand(index + 1)) < 0) return -1;
321 enc_table.count = index;
322 return enc_register_at(index - 1, name, encoding);
323 }
324
325 static void set_encoding_const(const char *, rb_encoding *);
326 int rb_enc_registered(const char *name);
327
328 int
rb_enc_register(const char * name,rb_encoding * encoding)329 rb_enc_register(const char *name, rb_encoding *encoding)
330 {
331 int index = rb_enc_registered(name);
332
333 if (index >= 0) {
334 rb_encoding *oldenc = rb_enc_from_index(index);
335 if (STRCASECMP(name, rb_enc_name(oldenc))) {
336 index = enc_register(name, encoding);
337 }
338 else if (enc_autoload_p(oldenc) || !ENC_DUMMY_P(oldenc)) {
339 enc_register_at(index, name, encoding);
340 }
341 else {
342 rb_raise(rb_eArgError, "encoding %s is already registered", name);
343 }
344 }
345 else {
346 index = enc_register(name, encoding);
347 set_encoding_const(name, rb_enc_from_index(index));
348 }
349 return index;
350 }
351
352 void
rb_encdb_declare(const char * name)353 rb_encdb_declare(const char *name)
354 {
355 int idx = rb_enc_registered(name);
356 if (idx < 0) {
357 idx = enc_register(name, 0);
358 }
359 set_encoding_const(name, rb_enc_from_index(idx));
360 }
361
362 static void
enc_check_duplication(const char * name)363 enc_check_duplication(const char *name)
364 {
365 if (rb_enc_registered(name) >= 0) {
366 rb_raise(rb_eArgError, "encoding %s is already registered", name);
367 }
368 }
369
370 static rb_encoding*
set_base_encoding(int index,rb_encoding * base)371 set_base_encoding(int index, rb_encoding *base)
372 {
373 rb_encoding *enc = enc_table.list[index].enc;
374
375 enc_table.list[index].base = base;
376 if (ENC_DUMMY_P(base)) ENC_SET_DUMMY((rb_raw_encoding *)enc);
377 return enc;
378 }
379
380 /* for encdb.h
381 * Set base encoding for encodings which are not replicas
382 * but not in their own files.
383 */
384 void
rb_enc_set_base(const char * name,const char * orig)385 rb_enc_set_base(const char *name, const char *orig)
386 {
387 int idx = rb_enc_registered(name);
388 int origidx = rb_enc_registered(orig);
389 set_base_encoding(idx, rb_enc_from_index(origidx));
390 }
391
392 /* for encdb.h
393 * Set encoding dummy.
394 */
395 int
rb_enc_set_dummy(int index)396 rb_enc_set_dummy(int index)
397 {
398 rb_encoding *enc = enc_table.list[index].enc;
399
400 ENC_SET_DUMMY((rb_raw_encoding *)enc);
401 return index;
402 }
403
404 int
rb_enc_replicate(const char * name,rb_encoding * encoding)405 rb_enc_replicate(const char *name, rb_encoding *encoding)
406 {
407 int idx;
408
409 enc_check_duplication(name);
410 idx = enc_register(name, encoding);
411 set_base_encoding(idx, encoding);
412 set_encoding_const(name, rb_enc_from_index(idx));
413 return idx;
414 }
415
416 /*
417 * call-seq:
418 * enc.replicate(name) -> encoding
419 *
420 * Returns a replicated encoding of _enc_ whose name is _name_.
421 * The new encoding should have the same byte structure of _enc_.
422 * If _name_ is used by another encoding, raise ArgumentError.
423 *
424 */
425 static VALUE
enc_replicate(VALUE encoding,VALUE name)426 enc_replicate(VALUE encoding, VALUE name)
427 {
428 return rb_enc_from_encoding_index(
429 rb_enc_replicate(StringValueCStr(name),
430 rb_to_encoding(encoding)));
431 }
432
433 static int
enc_replicate_with_index(const char * name,rb_encoding * origenc,int idx)434 enc_replicate_with_index(const char *name, rb_encoding *origenc, int idx)
435 {
436 if (idx < 0) {
437 idx = enc_register(name, origenc);
438 }
439 else {
440 idx = enc_register_at(idx, name, origenc);
441 }
442 if (idx >= 0) {
443 set_base_encoding(idx, origenc);
444 set_encoding_const(name, rb_enc_from_index(idx));
445 }
446 return idx;
447 }
448
449 int
rb_encdb_replicate(const char * name,const char * orig)450 rb_encdb_replicate(const char *name, const char *orig)
451 {
452 int origidx = rb_enc_registered(orig);
453 int idx = rb_enc_registered(name);
454
455 if (origidx < 0) {
456 origidx = enc_register(orig, 0);
457 }
458 return enc_replicate_with_index(name, rb_enc_from_index(origidx), idx);
459 }
460
461 int
rb_define_dummy_encoding(const char * name)462 rb_define_dummy_encoding(const char *name)
463 {
464 int index = rb_enc_replicate(name, rb_ascii8bit_encoding());
465 rb_encoding *enc = enc_table.list[index].enc;
466
467 ENC_SET_DUMMY((rb_raw_encoding *)enc);
468 return index;
469 }
470
471 int
rb_encdb_dummy(const char * name)472 rb_encdb_dummy(const char *name)
473 {
474 int index = enc_replicate_with_index(name, rb_ascii8bit_encoding(),
475 rb_enc_registered(name));
476 rb_encoding *enc = enc_table.list[index].enc;
477
478 ENC_SET_DUMMY((rb_raw_encoding *)enc);
479 return index;
480 }
481
482 /*
483 * call-seq:
484 * enc.dummy? -> true or false
485 *
486 * Returns true for dummy encodings.
487 * A dummy encoding is an encoding for which character handling is not properly
488 * implemented.
489 * It is used for stateful encodings.
490 *
491 * Encoding::ISO_2022_JP.dummy? #=> true
492 * Encoding::UTF_8.dummy? #=> false
493 *
494 */
495 static VALUE
enc_dummy_p(VALUE enc)496 enc_dummy_p(VALUE enc)
497 {
498 return ENC_DUMMY_P(must_encoding(enc)) ? Qtrue : Qfalse;
499 }
500
501 /*
502 * call-seq:
503 * enc.ascii_compatible? -> true or false
504 *
505 * Returns whether ASCII-compatible or not.
506 *
507 * Encoding::UTF_8.ascii_compatible? #=> true
508 * Encoding::UTF_16BE.ascii_compatible? #=> false
509 *
510 */
511 static VALUE
enc_ascii_compatible_p(VALUE enc)512 enc_ascii_compatible_p(VALUE enc)
513 {
514 return rb_enc_asciicompat(must_encoding(enc)) ? Qtrue : Qfalse;
515 }
516
517 /*
518 * Returns non-zero when the encoding is Unicode series other than UTF-7 else 0.
519 */
520 int
rb_enc_unicode_p(rb_encoding * enc)521 rb_enc_unicode_p(rb_encoding *enc)
522 {
523 return ONIGENC_IS_UNICODE(enc);
524 }
525
526 static st_data_t
enc_dup_name(st_data_t name)527 enc_dup_name(st_data_t name)
528 {
529 return (st_data_t)strdup((const char *)name);
530 }
531
532 /*
533 * Returns copied alias name when the key is added for st_table,
534 * else returns NULL.
535 */
536 static int
enc_alias_internal(const char * alias,int idx)537 enc_alias_internal(const char *alias, int idx)
538 {
539 return st_insert2(enc_table.names, (st_data_t)alias, (st_data_t)idx,
540 enc_dup_name);
541 }
542
543 static int
enc_alias(const char * alias,int idx)544 enc_alias(const char *alias, int idx)
545 {
546 if (!valid_encoding_name_p(alias)) return -1;
547 if (!enc_alias_internal(alias, idx))
548 set_encoding_const(alias, rb_enc_from_index(idx));
549 return idx;
550 }
551
552 int
rb_enc_alias(const char * alias,const char * orig)553 rb_enc_alias(const char *alias, const char *orig)
554 {
555 int idx;
556
557 enc_check_duplication(alias);
558 if (!enc_table.list) {
559 rb_enc_init();
560 }
561 if ((idx = rb_enc_find_index(orig)) < 0) {
562 return -1;
563 }
564 return enc_alias(alias, idx);
565 }
566
567 int
rb_encdb_alias(const char * alias,const char * orig)568 rb_encdb_alias(const char *alias, const char *orig)
569 {
570 int idx = rb_enc_registered(orig);
571
572 if (idx < 0) {
573 idx = enc_register(orig, 0);
574 }
575 return enc_alias(alias, idx);
576 }
577
578 void
rb_encdb_set_unicode(int index)579 rb_encdb_set_unicode(int index)
580 {
581 ((rb_raw_encoding *)rb_enc_from_index(index))->flags |= ONIGENC_FLAG_UNICODE;
582 }
583
584 void
rb_enc_init(void)585 rb_enc_init(void)
586 {
587 enc_table_expand(ENCODING_COUNT + 1);
588 if (!enc_table.names) {
589 enc_table.names = st_init_strcasetable();
590 }
591 #define ENC_REGISTER(enc) enc_register_at(ENCINDEX_##enc, rb_enc_name(&OnigEncoding##enc), &OnigEncoding##enc)
592 ENC_REGISTER(ASCII);
593 ENC_REGISTER(UTF_8);
594 ENC_REGISTER(US_ASCII);
595 #undef ENC_REGISTER
596 #define ENCDB_REGISTER(name, enc) enc_register_at(ENCINDEX_##enc, name, NULL)
597 ENCDB_REGISTER("UTF-16BE", UTF_16BE);
598 ENCDB_REGISTER("UTF-16LE", UTF_16LE);
599 ENCDB_REGISTER("UTF-32BE", UTF_32BE);
600 ENCDB_REGISTER("UTF-32LE", UTF_32LE);
601 ENCDB_REGISTER("UTF-16", UTF_16);
602 ENCDB_REGISTER("UTF-32", UTF_32);
603 ENCDB_REGISTER("UTF8-MAC", UTF8_MAC);
604
605 ENCDB_REGISTER("EUC-JP", EUC_JP);
606 ENCDB_REGISTER("Windows-31J", Windows_31J);
607 #undef ENCDB_REGISTER
608 enc_table.count = ENCINDEX_BUILTIN_MAX;
609 }
610
611 rb_encoding *
rb_enc_from_index(int index)612 rb_enc_from_index(int index)
613 {
614 if (!enc_table.list) {
615 rb_enc_init();
616 }
617 if (index < 0 || enc_table.count <= (index &= ENC_INDEX_MASK)) {
618 return 0;
619 }
620 return enc_table.list[index].enc;
621 }
622
623 rb_encoding *
rb_enc_get_from_index(int index)624 rb_enc_get_from_index(int index)
625 {
626 return must_encindex(index);
627 }
628
629 int
rb_enc_registered(const char * name)630 rb_enc_registered(const char *name)
631 {
632 st_data_t idx = 0;
633
634 if (!name) return -1;
635 if (!enc_table.list) return -1;
636 if (st_lookup(enc_table.names, (st_data_t)name, &idx)) {
637 return (int)idx;
638 }
639 return -1;
640 }
641
642 static int
load_encoding(const char * name)643 load_encoding(const char *name)
644 {
645 VALUE enclib = rb_sprintf("enc/%s.so", name);
646 VALUE verbose = ruby_verbose;
647 VALUE debug = ruby_debug;
648 VALUE errinfo;
649 char *s = RSTRING_PTR(enclib) + 4, *e = RSTRING_END(enclib) - 3;
650 int loaded;
651 int idx;
652
653 while (s < e) {
654 if (!ISALNUM(*s)) *s = '_';
655 else if (ISUPPER(*s)) *s = (char)TOLOWER(*s);
656 ++s;
657 }
658 FL_UNSET(enclib, FL_TAINT);
659 enclib = rb_fstring(enclib);
660 ruby_verbose = Qfalse;
661 ruby_debug = Qfalse;
662 errinfo = rb_errinfo();
663 loaded = rb_require_internal(enclib, rb_safe_level());
664 ruby_verbose = verbose;
665 ruby_debug = debug;
666 rb_set_errinfo(errinfo);
667 if (loaded < 0 || 1 < loaded) return -1;
668 if ((idx = rb_enc_registered(name)) < 0) return -1;
669 if (enc_autoload_p(enc_table.list[idx].enc)) return -1;
670 return idx;
671 }
672
673 static int
enc_autoload(rb_encoding * enc)674 enc_autoload(rb_encoding *enc)
675 {
676 int i;
677 rb_encoding *base = enc_table.list[ENC_TO_ENCINDEX(enc)].base;
678
679 if (base) {
680 i = 0;
681 do {
682 if (i >= enc_table.count) return -1;
683 } while (enc_table.list[i].enc != base && (++i, 1));
684 if (enc_autoload_p(base)) {
685 if (enc_autoload(base) < 0) return -1;
686 }
687 i = enc->ruby_encoding_index;
688 enc_register_at(i & ENC_INDEX_MASK, rb_enc_name(enc), base);
689 ((rb_raw_encoding *)enc)->ruby_encoding_index = i;
690 i &= ENC_INDEX_MASK;
691 }
692 else {
693 i = load_encoding(rb_enc_name(enc));
694 }
695 return i;
696 }
697
698 /* Return encoding index or UNSPECIFIED_ENCODING from encoding name */
699 int
rb_enc_find_index(const char * name)700 rb_enc_find_index(const char *name)
701 {
702 int i = rb_enc_registered(name);
703 rb_encoding *enc;
704
705 if (i < 0) {
706 i = load_encoding(name);
707 }
708 else if (!(enc = rb_enc_from_index(i))) {
709 if (i != UNSPECIFIED_ENCODING) {
710 rb_raise(rb_eArgError, "encoding %s is not registered", name);
711 }
712 }
713 else if (enc_autoload_p(enc)) {
714 if (enc_autoload(enc) < 0) {
715 rb_warn("failed to load encoding (%s); use ASCII-8BIT instead",
716 name);
717 return 0;
718 }
719 }
720 return i;
721 }
722
723 int
rb_enc_find_index2(const char * name,long len)724 rb_enc_find_index2(const char *name, long len)
725 {
726 char buf[ENCODING_NAMELEN_MAX+1];
727
728 if (len > ENCODING_NAMELEN_MAX) return -1;
729 memcpy(buf, name, len);
730 buf[len] = '\0';
731 return rb_enc_find_index(buf);
732 }
733
734 rb_encoding *
rb_enc_find(const char * name)735 rb_enc_find(const char *name)
736 {
737 int idx = rb_enc_find_index(name);
738 if (idx < 0) idx = 0;
739 return rb_enc_from_index(idx);
740 }
741
742 static inline int
enc_capable(VALUE obj)743 enc_capable(VALUE obj)
744 {
745 if (SPECIAL_CONST_P(obj)) return SYMBOL_P(obj);
746 switch (BUILTIN_TYPE(obj)) {
747 case T_STRING:
748 case T_REGEXP:
749 case T_FILE:
750 case T_SYMBOL:
751 return TRUE;
752 case T_DATA:
753 if (is_data_encoding(obj)) return TRUE;
754 default:
755 return FALSE;
756 }
757 }
758
759 int
rb_enc_capable(VALUE obj)760 rb_enc_capable(VALUE obj)
761 {
762 return enc_capable(obj);
763 }
764
765 ID
rb_id_encoding(void)766 rb_id_encoding(void)
767 {
768 CONST_ID(id_encoding, "encoding");
769 return id_encoding;
770 }
771
772 static int
enc_get_index_str(VALUE str)773 enc_get_index_str(VALUE str)
774 {
775 int i = ENCODING_GET_INLINED(str);
776 if (i == ENCODING_INLINE_MAX) {
777 VALUE iv;
778
779 iv = rb_ivar_get(str, rb_id_encoding());
780 i = NUM2INT(iv);
781 }
782 return i;
783 }
784
785 int
rb_enc_get_index(VALUE obj)786 rb_enc_get_index(VALUE obj)
787 {
788 int i = -1;
789 VALUE tmp;
790
791 if (SPECIAL_CONST_P(obj)) {
792 if (!SYMBOL_P(obj)) return -1;
793 obj = rb_sym2str(obj);
794 }
795 switch (BUILTIN_TYPE(obj)) {
796 case T_STRING:
797 case T_SYMBOL:
798 case T_REGEXP:
799 i = enc_get_index_str(obj);
800 break;
801 case T_FILE:
802 tmp = rb_funcallv(obj, rb_intern("internal_encoding"), 0, 0);
803 if (NIL_P(tmp)) {
804 tmp = rb_funcallv(obj, rb_intern("external_encoding"), 0, 0);
805 }
806 if (is_obj_encoding(tmp)) {
807 i = enc_check_encoding(tmp);
808 }
809 break;
810 case T_DATA:
811 if (is_data_encoding(obj)) {
812 i = enc_check_encoding(obj);
813 }
814 break;
815 default:
816 break;
817 }
818 return i;
819 }
820
821 static void
enc_set_index(VALUE obj,int idx)822 enc_set_index(VALUE obj, int idx)
823 {
824 if (!enc_capable(obj)) {
825 rb_raise(rb_eArgError, "cannot set encoding on non-encoding capable object");
826 }
827
828 if (idx < ENCODING_INLINE_MAX) {
829 ENCODING_SET_INLINED(obj, idx);
830 return;
831 }
832 ENCODING_SET_INLINED(obj, ENCODING_INLINE_MAX);
833 rb_ivar_set(obj, rb_id_encoding(), INT2NUM(idx));
834 }
835
836 void
rb_enc_set_index(VALUE obj,int idx)837 rb_enc_set_index(VALUE obj, int idx)
838 {
839 rb_check_frozen(obj);
840 must_encindex(idx);
841 enc_set_index(obj, idx);
842 }
843
844 VALUE
rb_enc_associate_index(VALUE obj,int idx)845 rb_enc_associate_index(VALUE obj, int idx)
846 {
847 rb_encoding *enc;
848 int oldidx, oldtermlen, termlen;
849
850 /* enc_check_capable(obj);*/
851 rb_check_frozen(obj);
852 oldidx = rb_enc_get_index(obj);
853 if (oldidx == idx)
854 return obj;
855 if (SPECIAL_CONST_P(obj)) {
856 rb_raise(rb_eArgError, "cannot set encoding");
857 }
858 enc = must_encindex(idx);
859 if (!ENC_CODERANGE_ASCIIONLY(obj) ||
860 !rb_enc_asciicompat(enc)) {
861 ENC_CODERANGE_CLEAR(obj);
862 }
863 termlen = rb_enc_mbminlen(enc);
864 oldtermlen = rb_enc_mbminlen(rb_enc_from_index(oldidx));
865 if (oldtermlen != termlen && RB_TYPE_P(obj, T_STRING)) {
866 rb_str_change_terminator_length(obj, oldtermlen, termlen);
867 }
868 enc_set_index(obj, idx);
869 return obj;
870 }
871
872 VALUE
rb_enc_associate(VALUE obj,rb_encoding * enc)873 rb_enc_associate(VALUE obj, rb_encoding *enc)
874 {
875 return rb_enc_associate_index(obj, rb_enc_to_index(enc));
876 }
877
878 rb_encoding*
rb_enc_get(VALUE obj)879 rb_enc_get(VALUE obj)
880 {
881 return rb_enc_from_index(rb_enc_get_index(obj));
882 }
883
884 static rb_encoding* enc_compatible_str(VALUE str1, VALUE str2);
885
886 rb_encoding*
rb_enc_check_str(VALUE str1,VALUE str2)887 rb_enc_check_str(VALUE str1, VALUE str2)
888 {
889 rb_encoding *enc = enc_compatible_str(MUST_STRING(str1), MUST_STRING(str2));
890 if (!enc)
891 rb_raise(rb_eEncCompatError, "incompatible character encodings: %s and %s",
892 rb_enc_name(rb_enc_get(str1)),
893 rb_enc_name(rb_enc_get(str2)));
894 return enc;
895 }
896
897 rb_encoding*
rb_enc_check(VALUE str1,VALUE str2)898 rb_enc_check(VALUE str1, VALUE str2)
899 {
900 rb_encoding *enc = rb_enc_compatible(str1, str2);
901 if (!enc)
902 rb_raise(rb_eEncCompatError, "incompatible character encodings: %s and %s",
903 rb_enc_name(rb_enc_get(str1)),
904 rb_enc_name(rb_enc_get(str2)));
905 return enc;
906 }
907
908 static rb_encoding*
enc_compatible_latter(VALUE str1,VALUE str2,int idx1,int idx2)909 enc_compatible_latter(VALUE str1, VALUE str2, int idx1, int idx2)
910 {
911 int isstr1, isstr2;
912 rb_encoding *enc1 = rb_enc_from_index(idx1);
913 rb_encoding *enc2 = rb_enc_from_index(idx2);
914
915 isstr2 = RB_TYPE_P(str2, T_STRING);
916 if (isstr2 && RSTRING_LEN(str2) == 0)
917 return enc1;
918 isstr1 = RB_TYPE_P(str1, T_STRING);
919 if (isstr1 && RSTRING_LEN(str1) == 0)
920 return (rb_enc_asciicompat(enc1) && rb_enc_str_asciionly_p(str2)) ? enc1 : enc2;
921 if (!rb_enc_asciicompat(enc1) || !rb_enc_asciicompat(enc2)) {
922 return 0;
923 }
924
925 /* objects whose encoding is the same of contents */
926 if (!isstr2 && idx2 == ENCINDEX_US_ASCII)
927 return enc1;
928 if (!isstr1 && idx1 == ENCINDEX_US_ASCII)
929 return enc2;
930
931 if (!isstr1) {
932 VALUE tmp = str1;
933 int idx0 = idx1;
934 str1 = str2;
935 str2 = tmp;
936 idx1 = idx2;
937 idx2 = idx0;
938 idx0 = isstr1;
939 isstr1 = isstr2;
940 isstr2 = idx0;
941 }
942 if (isstr1) {
943 int cr1, cr2;
944
945 cr1 = rb_enc_str_coderange(str1);
946 if (isstr2) {
947 cr2 = rb_enc_str_coderange(str2);
948 if (cr1 != cr2) {
949 /* may need to handle ENC_CODERANGE_BROKEN */
950 if (cr1 == ENC_CODERANGE_7BIT) return enc2;
951 if (cr2 == ENC_CODERANGE_7BIT) return enc1;
952 }
953 if (cr2 == ENC_CODERANGE_7BIT) {
954 return enc1;
955 }
956 }
957 if (cr1 == ENC_CODERANGE_7BIT)
958 return enc2;
959 }
960 return 0;
961 }
962
963 static rb_encoding*
enc_compatible_str(VALUE str1,VALUE str2)964 enc_compatible_str(VALUE str1, VALUE str2)
965 {
966 int idx1 = enc_get_index_str(str1);
967 int idx2 = enc_get_index_str(str2);
968
969 if (idx1 < 0 || idx2 < 0)
970 return 0;
971
972 if (idx1 == idx2) {
973 return rb_enc_from_index(idx1);
974 }
975 else {
976 return enc_compatible_latter(str1, str2, idx1, idx2);
977 }
978 }
979
980 rb_encoding*
rb_enc_compatible(VALUE str1,VALUE str2)981 rb_enc_compatible(VALUE str1, VALUE str2)
982 {
983 int idx1 = rb_enc_get_index(str1);
984 int idx2 = rb_enc_get_index(str2);
985
986 if (idx1 < 0 || idx2 < 0)
987 return 0;
988
989 if (idx1 == idx2) {
990 return rb_enc_from_index(idx1);
991 }
992
993 return enc_compatible_latter(str1, str2, idx1, idx2);
994 }
995
996 void
rb_enc_copy(VALUE obj1,VALUE obj2)997 rb_enc_copy(VALUE obj1, VALUE obj2)
998 {
999 rb_enc_associate_index(obj1, rb_enc_get_index(obj2));
1000 }
1001
1002
1003 /*
1004 * call-seq:
1005 * obj.encoding -> encoding
1006 *
1007 * Returns the Encoding object that represents the encoding of obj.
1008 */
1009
1010 VALUE
rb_obj_encoding(VALUE obj)1011 rb_obj_encoding(VALUE obj)
1012 {
1013 int idx = rb_enc_get_index(obj);
1014 if (idx < 0) {
1015 rb_raise(rb_eTypeError, "unknown encoding");
1016 }
1017 return rb_enc_from_encoding_index(idx & ENC_INDEX_MASK);
1018 }
1019
1020 int
rb_enc_fast_mbclen(const char * p,const char * e,rb_encoding * enc)1021 rb_enc_fast_mbclen(const char *p, const char *e, rb_encoding *enc)
1022 {
1023 return ONIGENC_MBC_ENC_LEN(enc, (UChar*)p, (UChar*)e);
1024 }
1025
1026 int
rb_enc_mbclen(const char * p,const char * e,rb_encoding * enc)1027 rb_enc_mbclen(const char *p, const char *e, rb_encoding *enc)
1028 {
1029 int n = ONIGENC_PRECISE_MBC_ENC_LEN(enc, (UChar*)p, (UChar*)e);
1030 if (MBCLEN_CHARFOUND_P(n) && MBCLEN_CHARFOUND_LEN(n) <= e-p)
1031 return MBCLEN_CHARFOUND_LEN(n);
1032 else {
1033 int min = rb_enc_mbminlen(enc);
1034 return min <= e-p ? min : (int)(e-p);
1035 }
1036 }
1037
1038 int
rb_enc_precise_mbclen(const char * p,const char * e,rb_encoding * enc)1039 rb_enc_precise_mbclen(const char *p, const char *e, rb_encoding *enc)
1040 {
1041 int n;
1042 if (e <= p)
1043 return ONIGENC_CONSTRUCT_MBCLEN_NEEDMORE(1);
1044 n = ONIGENC_PRECISE_MBC_ENC_LEN(enc, (UChar*)p, (UChar*)e);
1045 if (e-p < n)
1046 return ONIGENC_CONSTRUCT_MBCLEN_NEEDMORE(n-(int)(e-p));
1047 return n;
1048 }
1049
1050 int
rb_enc_ascget(const char * p,const char * e,int * len,rb_encoding * enc)1051 rb_enc_ascget(const char *p, const char *e, int *len, rb_encoding *enc)
1052 {
1053 unsigned int c;
1054 int l;
1055 if (e <= p)
1056 return -1;
1057 if (rb_enc_asciicompat(enc)) {
1058 c = (unsigned char)*p;
1059 if (!ISASCII(c))
1060 return -1;
1061 if (len) *len = 1;
1062 return c;
1063 }
1064 l = rb_enc_precise_mbclen(p, e, enc);
1065 if (!MBCLEN_CHARFOUND_P(l))
1066 return -1;
1067 c = rb_enc_mbc_to_codepoint(p, e, enc);
1068 if (!rb_enc_isascii(c, enc))
1069 return -1;
1070 if (len) *len = l;
1071 return c;
1072 }
1073
1074 unsigned int
rb_enc_codepoint_len(const char * p,const char * e,int * len_p,rb_encoding * enc)1075 rb_enc_codepoint_len(const char *p, const char *e, int *len_p, rb_encoding *enc)
1076 {
1077 int r;
1078 if (e <= p)
1079 rb_raise(rb_eArgError, "empty string");
1080 r = rb_enc_precise_mbclen(p, e, enc);
1081 if (!MBCLEN_CHARFOUND_P(r)) {
1082 rb_raise(rb_eArgError, "invalid byte sequence in %s", rb_enc_name(enc));
1083 }
1084 if (len_p) *len_p = MBCLEN_CHARFOUND_LEN(r);
1085 return rb_enc_mbc_to_codepoint(p, e, enc);
1086 }
1087
1088 #undef rb_enc_codepoint
1089 unsigned int
rb_enc_codepoint(const char * p,const char * e,rb_encoding * enc)1090 rb_enc_codepoint(const char *p, const char *e, rb_encoding *enc)
1091 {
1092 return rb_enc_codepoint_len(p, e, 0, enc);
1093 }
1094
1095 int
rb_enc_codelen(int c,rb_encoding * enc)1096 rb_enc_codelen(int c, rb_encoding *enc)
1097 {
1098 int n = ONIGENC_CODE_TO_MBCLEN(enc,c);
1099 if (n == 0) {
1100 rb_raise(rb_eArgError, "invalid codepoint 0x%x in %s", c, rb_enc_name(enc));
1101 }
1102 return n;
1103 }
1104
1105 #undef rb_enc_code_to_mbclen
1106 int
rb_enc_code_to_mbclen(int code,rb_encoding * enc)1107 rb_enc_code_to_mbclen(int code, rb_encoding *enc)
1108 {
1109 return ONIGENC_CODE_TO_MBCLEN(enc, code);
1110 }
1111
1112 int
rb_enc_toupper(int c,rb_encoding * enc)1113 rb_enc_toupper(int c, rb_encoding *enc)
1114 {
1115 return (ONIGENC_IS_ASCII_CODE(c)?ONIGENC_ASCII_CODE_TO_UPPER_CASE(c):(c));
1116 }
1117
1118 int
rb_enc_tolower(int c,rb_encoding * enc)1119 rb_enc_tolower(int c, rb_encoding *enc)
1120 {
1121 return (ONIGENC_IS_ASCII_CODE(c)?ONIGENC_ASCII_CODE_TO_LOWER_CASE(c):(c));
1122 }
1123
1124 /*
1125 * call-seq:
1126 * enc.inspect -> string
1127 *
1128 * Returns a string which represents the encoding for programmers.
1129 *
1130 * Encoding::UTF_8.inspect #=> "#<Encoding:UTF-8>"
1131 * Encoding::ISO_2022_JP.inspect #=> "#<Encoding:ISO-2022-JP (dummy)>"
1132 */
1133 static VALUE
enc_inspect(VALUE self)1134 enc_inspect(VALUE self)
1135 {
1136 rb_encoding *enc;
1137
1138 if (!is_data_encoding(self)) {
1139 not_encoding(self);
1140 }
1141 if (!(enc = DATA_PTR(self)) || rb_enc_from_index(rb_enc_to_index(enc)) != enc) {
1142 rb_raise(rb_eTypeError, "broken Encoding");
1143 }
1144 return rb_enc_sprintf(rb_usascii_encoding(),
1145 "#<%"PRIsVALUE":%s%s%s>", rb_obj_class(self),
1146 rb_enc_name(enc),
1147 (ENC_DUMMY_P(enc) ? " (dummy)" : ""),
1148 enc_autoload_p(enc) ? " (autoload)" : "");
1149 }
1150
1151 /*
1152 * call-seq:
1153 * enc.name -> string
1154 * enc.to_s -> string
1155 *
1156 * Returns the name of the encoding.
1157 *
1158 * Encoding::UTF_8.name #=> "UTF-8"
1159 */
1160 static VALUE
enc_name(VALUE self)1161 enc_name(VALUE self)
1162 {
1163 return rb_fstring_cstr(rb_enc_name((rb_encoding*)DATA_PTR(self)));
1164 }
1165
1166 static int
enc_names_i(st_data_t name,st_data_t idx,st_data_t args)1167 enc_names_i(st_data_t name, st_data_t idx, st_data_t args)
1168 {
1169 VALUE *arg = (VALUE *)args;
1170
1171 if ((int)idx == (int)arg[0]) {
1172 VALUE str = rb_fstring_cstr((char *)name);
1173 rb_ary_push(arg[1], str);
1174 }
1175 return ST_CONTINUE;
1176 }
1177
1178 /*
1179 * call-seq:
1180 * enc.names -> array
1181 *
1182 * Returns the list of name and aliases of the encoding.
1183 *
1184 * Encoding::WINDOWS_31J.names #=> ["Windows-31J", "CP932", "csWindows31J"]
1185 */
1186 static VALUE
enc_names(VALUE self)1187 enc_names(VALUE self)
1188 {
1189 VALUE args[2];
1190
1191 args[0] = (VALUE)rb_to_encoding_index(self);
1192 args[1] = rb_ary_new2(0);
1193 st_foreach(enc_table.names, enc_names_i, (st_data_t)args);
1194 return args[1];
1195 }
1196
1197 /*
1198 * call-seq:
1199 * Encoding.list -> [enc1, enc2, ...]
1200 *
1201 * Returns the list of loaded encodings.
1202 *
1203 * Encoding.list
1204 * #=> [#<Encoding:ASCII-8BIT>, #<Encoding:UTF-8>,
1205 * #<Encoding:ISO-2022-JP (dummy)>]
1206 *
1207 * Encoding.find("US-ASCII")
1208 * #=> #<Encoding:US-ASCII>
1209 *
1210 * Encoding.list
1211 * #=> [#<Encoding:ASCII-8BIT>, #<Encoding:UTF-8>,
1212 * #<Encoding:US-ASCII>, #<Encoding:ISO-2022-JP (dummy)>]
1213 *
1214 */
1215 static VALUE
enc_list(VALUE klass)1216 enc_list(VALUE klass)
1217 {
1218 VALUE ary = rb_ary_new2(0);
1219 rb_ary_replace(ary, rb_encoding_list);
1220 return ary;
1221 }
1222
1223 /*
1224 * call-seq:
1225 * Encoding.find(string) -> enc
1226 *
1227 * Search the encoding with specified <i>name</i>.
1228 * <i>name</i> should be a string.
1229 *
1230 * Encoding.find("US-ASCII") #=> #<Encoding:US-ASCII>
1231 *
1232 * Names which this method accept are encoding names and aliases
1233 * including following special aliases
1234 *
1235 * "external":: default external encoding
1236 * "internal":: default internal encoding
1237 * "locale":: locale encoding
1238 * "filesystem":: filesystem encoding
1239 *
1240 * An ArgumentError is raised when no encoding with <i>name</i>.
1241 * Only <code>Encoding.find("internal")</code> however returns nil
1242 * when no encoding named "internal", in other words, when Ruby has no
1243 * default internal encoding.
1244 */
1245 static VALUE
enc_find(VALUE klass,VALUE enc)1246 enc_find(VALUE klass, VALUE enc)
1247 {
1248 int idx;
1249 if (is_obj_encoding(enc))
1250 return enc;
1251 idx = str_to_encindex(enc);
1252 if (idx == UNSPECIFIED_ENCODING) return Qnil;
1253 return rb_enc_from_encoding_index(idx);
1254 }
1255
1256 /*
1257 * call-seq:
1258 * Encoding.compatible?(obj1, obj2) -> enc or nil
1259 *
1260 * Checks the compatibility of two objects.
1261 *
1262 * If the objects are both strings they are compatible when they are
1263 * concatenatable. The encoding of the concatenated string will be returned
1264 * if they are compatible, nil if they are not.
1265 *
1266 * Encoding.compatible?("\xa1".force_encoding("iso-8859-1"), "b")
1267 * #=> #<Encoding:ISO-8859-1>
1268 *
1269 * Encoding.compatible?(
1270 * "\xa1".force_encoding("iso-8859-1"),
1271 * "\xa1\xa1".force_encoding("euc-jp"))
1272 * #=> nil
1273 *
1274 * If the objects are non-strings their encodings are compatible when they
1275 * have an encoding and:
1276 * * Either encoding is US-ASCII compatible
1277 * * One of the encodings is a 7-bit encoding
1278 *
1279 */
1280 static VALUE
enc_compatible_p(VALUE klass,VALUE str1,VALUE str2)1281 enc_compatible_p(VALUE klass, VALUE str1, VALUE str2)
1282 {
1283 rb_encoding *enc;
1284
1285 if (!enc_capable(str1)) return Qnil;
1286 if (!enc_capable(str2)) return Qnil;
1287 enc = rb_enc_compatible(str1, str2);
1288 if (!enc) return Qnil;
1289 return rb_enc_from_encoding(enc);
1290 }
1291
1292 /* :nodoc: */
1293 static VALUE
enc_s_alloc(VALUE klass)1294 enc_s_alloc(VALUE klass)
1295 {
1296 rb_undefined_alloc(klass);
1297 return Qnil;
1298 }
1299
1300 /* :nodoc: */
1301 static VALUE
enc_dump(int argc,VALUE * argv,VALUE self)1302 enc_dump(int argc, VALUE *argv, VALUE self)
1303 {
1304 rb_check_arity(argc, 0, 1);
1305 return enc_name(self);
1306 }
1307
1308 /* :nodoc: */
1309 static VALUE
enc_load(VALUE klass,VALUE str)1310 enc_load(VALUE klass, VALUE str)
1311 {
1312 return str;
1313 }
1314
1315 /* :nodoc: */
1316 static VALUE
enc_m_loader(VALUE klass,VALUE str)1317 enc_m_loader(VALUE klass, VALUE str)
1318 {
1319 return enc_find(klass, str);
1320 }
1321
1322 rb_encoding *
rb_ascii8bit_encoding(void)1323 rb_ascii8bit_encoding(void)
1324 {
1325 if (!enc_table.list) {
1326 rb_enc_init();
1327 }
1328 return enc_table.list[ENCINDEX_ASCII].enc;
1329 }
1330
1331 int
rb_ascii8bit_encindex(void)1332 rb_ascii8bit_encindex(void)
1333 {
1334 return ENCINDEX_ASCII;
1335 }
1336
1337 rb_encoding *
rb_utf8_encoding(void)1338 rb_utf8_encoding(void)
1339 {
1340 if (!enc_table.list) {
1341 rb_enc_init();
1342 }
1343 return enc_table.list[ENCINDEX_UTF_8].enc;
1344 }
1345
1346 int
rb_utf8_encindex(void)1347 rb_utf8_encindex(void)
1348 {
1349 return ENCINDEX_UTF_8;
1350 }
1351
1352 rb_encoding *
rb_usascii_encoding(void)1353 rb_usascii_encoding(void)
1354 {
1355 if (!enc_table.list) {
1356 rb_enc_init();
1357 }
1358 return enc_table.list[ENCINDEX_US_ASCII].enc;
1359 }
1360
1361 int
rb_usascii_encindex(void)1362 rb_usascii_encindex(void)
1363 {
1364 return ENCINDEX_US_ASCII;
1365 }
1366
1367 int rb_locale_charmap_index(void);
1368
1369 int
rb_locale_encindex(void)1370 rb_locale_encindex(void)
1371 {
1372 int idx = rb_locale_charmap_index();
1373
1374 if (idx < 0) idx = ENCINDEX_ASCII;
1375
1376 if (rb_enc_registered("locale") < 0) {
1377 # if defined _WIN32
1378 void Init_w32_codepage(void);
1379 Init_w32_codepage();
1380 # endif
1381 enc_alias_internal("locale", idx);
1382 }
1383
1384 return idx;
1385 }
1386
1387 rb_encoding *
rb_locale_encoding(void)1388 rb_locale_encoding(void)
1389 {
1390 return rb_enc_from_index(rb_locale_encindex());
1391 }
1392
1393 int
rb_filesystem_encindex(void)1394 rb_filesystem_encindex(void)
1395 {
1396 int idx = rb_enc_registered("filesystem");
1397 if (idx < 0)
1398 idx = ENCINDEX_ASCII;
1399 return idx;
1400 }
1401
1402 rb_encoding *
rb_filesystem_encoding(void)1403 rb_filesystem_encoding(void)
1404 {
1405 return rb_enc_from_index(rb_filesystem_encindex());
1406 }
1407
1408 struct default_encoding {
1409 int index; /* -2 => not yet set, -1 => nil */
1410 rb_encoding *enc;
1411 };
1412
1413 static struct default_encoding default_external = {0};
1414
1415 static int
enc_set_default_encoding(struct default_encoding * def,VALUE encoding,const char * name)1416 enc_set_default_encoding(struct default_encoding *def, VALUE encoding, const char *name)
1417 {
1418 int overridden = FALSE;
1419
1420 if (def->index != -2)
1421 /* Already set */
1422 overridden = TRUE;
1423
1424 if (NIL_P(encoding)) {
1425 def->index = -1;
1426 def->enc = 0;
1427 st_insert(enc_table.names, (st_data_t)strdup(name),
1428 (st_data_t)UNSPECIFIED_ENCODING);
1429 }
1430 else {
1431 def->index = rb_enc_to_index(rb_to_encoding(encoding));
1432 def->enc = 0;
1433 enc_alias_internal(name, def->index);
1434 }
1435
1436 if (def == &default_external)
1437 enc_alias_internal("filesystem", Init_enc_set_filesystem_encoding());
1438
1439 return overridden;
1440 }
1441
1442 rb_encoding *
rb_default_external_encoding(void)1443 rb_default_external_encoding(void)
1444 {
1445 if (default_external.enc) return default_external.enc;
1446
1447 if (default_external.index >= 0) {
1448 default_external.enc = rb_enc_from_index(default_external.index);
1449 return default_external.enc;
1450 }
1451 else {
1452 return rb_locale_encoding();
1453 }
1454 }
1455
1456 VALUE
rb_enc_default_external(void)1457 rb_enc_default_external(void)
1458 {
1459 return rb_enc_from_encoding(rb_default_external_encoding());
1460 }
1461
1462 /*
1463 * call-seq:
1464 * Encoding.default_external -> enc
1465 *
1466 * Returns default external encoding.
1467 *
1468 * The default external encoding is used by default for strings created from
1469 * the following locations:
1470 *
1471 * * CSV
1472 * * File data read from disk
1473 * * SDBM
1474 * * StringIO
1475 * * Zlib::GzipReader
1476 * * Zlib::GzipWriter
1477 * * String#inspect
1478 * * Regexp#inspect
1479 *
1480 * While strings created from these locations will have this encoding, the
1481 * encoding may not be valid. Be sure to check String#valid_encoding?.
1482 *
1483 * File data written to disk will be transcoded to the default external
1484 * encoding when written.
1485 *
1486 * The default external encoding is initialized by the locale or -E option.
1487 */
1488 static VALUE
get_default_external(VALUE klass)1489 get_default_external(VALUE klass)
1490 {
1491 return rb_enc_default_external();
1492 }
1493
1494 void
rb_enc_set_default_external(VALUE encoding)1495 rb_enc_set_default_external(VALUE encoding)
1496 {
1497 if (NIL_P(encoding)) {
1498 rb_raise(rb_eArgError, "default external can not be nil");
1499 }
1500 enc_set_default_encoding(&default_external, encoding,
1501 "external");
1502 }
1503
1504 /*
1505 * call-seq:
1506 * Encoding.default_external = enc
1507 *
1508 * Sets default external encoding. You should not set
1509 * Encoding::default_external in ruby code as strings created before changing
1510 * the value may have a different encoding from strings created after the value
1511 * was changed., instead you should use <tt>ruby -E</tt> to invoke ruby with
1512 * the correct default_external.
1513 *
1514 * See Encoding::default_external for information on how the default external
1515 * encoding is used.
1516 */
1517 static VALUE
set_default_external(VALUE klass,VALUE encoding)1518 set_default_external(VALUE klass, VALUE encoding)
1519 {
1520 rb_warning("setting Encoding.default_external");
1521 rb_enc_set_default_external(encoding);
1522 return encoding;
1523 }
1524
1525 static struct default_encoding default_internal = {-2};
1526
1527 rb_encoding *
rb_default_internal_encoding(void)1528 rb_default_internal_encoding(void)
1529 {
1530 if (!default_internal.enc && default_internal.index >= 0) {
1531 default_internal.enc = rb_enc_from_index(default_internal.index);
1532 }
1533 return default_internal.enc; /* can be NULL */
1534 }
1535
1536 VALUE
rb_enc_default_internal(void)1537 rb_enc_default_internal(void)
1538 {
1539 /* Note: These functions cope with default_internal not being set */
1540 return rb_enc_from_encoding(rb_default_internal_encoding());
1541 }
1542
1543 /*
1544 * call-seq:
1545 * Encoding.default_internal -> enc
1546 *
1547 * Returns default internal encoding. Strings will be transcoded to the
1548 * default internal encoding in the following places if the default internal
1549 * encoding is not nil:
1550 *
1551 * * CSV
1552 * * Etc.sysconfdir and Etc.systmpdir
1553 * * File data read from disk
1554 * * File names from Dir
1555 * * Integer#chr
1556 * * String#inspect and Regexp#inspect
1557 * * Strings returned from Readline
1558 * * Strings returned from SDBM
1559 * * Time#zone
1560 * * Values from ENV
1561 * * Values in ARGV including $PROGRAM_NAME
1562 *
1563 * Additionally String#encode and String#encode! use the default internal
1564 * encoding if no encoding is given.
1565 *
1566 * The locale encoding (__ENCODING__), not default_internal, is used as the
1567 * encoding of created strings.
1568 *
1569 * Encoding::default_internal is initialized by the source file's
1570 * internal_encoding or -E option.
1571 */
1572 static VALUE
get_default_internal(VALUE klass)1573 get_default_internal(VALUE klass)
1574 {
1575 return rb_enc_default_internal();
1576 }
1577
1578 void
rb_enc_set_default_internal(VALUE encoding)1579 rb_enc_set_default_internal(VALUE encoding)
1580 {
1581 enc_set_default_encoding(&default_internal, encoding,
1582 "internal");
1583 }
1584
1585 /*
1586 * call-seq:
1587 * Encoding.default_internal = enc or nil
1588 *
1589 * Sets default internal encoding or removes default internal encoding when
1590 * passed nil. You should not set Encoding::default_internal in ruby code as
1591 * strings created before changing the value may have a different encoding
1592 * from strings created after the change. Instead you should use
1593 * <tt>ruby -E</tt> to invoke ruby with the correct default_internal.
1594 *
1595 * See Encoding::default_internal for information on how the default internal
1596 * encoding is used.
1597 */
1598 static VALUE
set_default_internal(VALUE klass,VALUE encoding)1599 set_default_internal(VALUE klass, VALUE encoding)
1600 {
1601 rb_warning("setting Encoding.default_internal");
1602 rb_enc_set_default_internal(encoding);
1603 return encoding;
1604 }
1605
1606 static void
set_encoding_const(const char * name,rb_encoding * enc)1607 set_encoding_const(const char *name, rb_encoding *enc)
1608 {
1609 VALUE encoding = rb_enc_from_encoding(enc);
1610 char *s = (char *)name;
1611 int haslower = 0, hasupper = 0, valid = 0;
1612
1613 if (ISDIGIT(*s)) return;
1614 if (ISUPPER(*s)) {
1615 hasupper = 1;
1616 while (*++s && (ISALNUM(*s) || *s == '_')) {
1617 if (ISLOWER(*s)) haslower = 1;
1618 }
1619 }
1620 if (!*s) {
1621 if (s - name > ENCODING_NAMELEN_MAX) return;
1622 valid = 1;
1623 rb_define_const(rb_cEncoding, name, encoding);
1624 }
1625 if (!valid || haslower) {
1626 size_t len = s - name;
1627 if (len > ENCODING_NAMELEN_MAX) return;
1628 if (!haslower || !hasupper) {
1629 do {
1630 if (ISLOWER(*s)) haslower = 1;
1631 if (ISUPPER(*s)) hasupper = 1;
1632 } while (*++s && (!haslower || !hasupper));
1633 len = s - name;
1634 }
1635 len += strlen(s);
1636 if (len++ > ENCODING_NAMELEN_MAX) return;
1637 MEMCPY(s = ALLOCA_N(char, len), name, char, len);
1638 name = s;
1639 if (!valid) {
1640 if (ISLOWER(*s)) *s = ONIGENC_ASCII_CODE_TO_UPPER_CASE((int)*s);
1641 for (; *s; ++s) {
1642 if (!ISALNUM(*s)) *s = '_';
1643 }
1644 if (hasupper) {
1645 rb_define_const(rb_cEncoding, name, encoding);
1646 }
1647 }
1648 if (haslower) {
1649 for (s = (char *)name; *s; ++s) {
1650 if (ISLOWER(*s)) *s = ONIGENC_ASCII_CODE_TO_UPPER_CASE((int)*s);
1651 }
1652 rb_define_const(rb_cEncoding, name, encoding);
1653 }
1654 }
1655 }
1656
1657 static int
rb_enc_name_list_i(st_data_t name,st_data_t idx,st_data_t arg)1658 rb_enc_name_list_i(st_data_t name, st_data_t idx, st_data_t arg)
1659 {
1660 VALUE ary = (VALUE)arg;
1661 VALUE str = rb_fstring_cstr((char *)name);
1662 rb_ary_push(ary, str);
1663 return ST_CONTINUE;
1664 }
1665
1666 /*
1667 * call-seq:
1668 * Encoding.name_list -> ["enc1", "enc2", ...]
1669 *
1670 * Returns the list of available encoding names.
1671 *
1672 * Encoding.name_list
1673 * #=> ["US-ASCII", "ASCII-8BIT", "UTF-8",
1674 * "ISO-8859-1", "Shift_JIS", "EUC-JP",
1675 * "Windows-31J",
1676 * "BINARY", "CP932", "eucJP"]
1677 *
1678 */
1679
1680 static VALUE
rb_enc_name_list(VALUE klass)1681 rb_enc_name_list(VALUE klass)
1682 {
1683 VALUE ary = rb_ary_new2(enc_table.names->num_entries);
1684 st_foreach(enc_table.names, rb_enc_name_list_i, (st_data_t)ary);
1685 return ary;
1686 }
1687
1688 static int
rb_enc_aliases_enc_i(st_data_t name,st_data_t orig,st_data_t arg)1689 rb_enc_aliases_enc_i(st_data_t name, st_data_t orig, st_data_t arg)
1690 {
1691 VALUE *p = (VALUE *)arg;
1692 VALUE aliases = p[0], ary = p[1];
1693 int idx = (int)orig;
1694 VALUE key, str = rb_ary_entry(ary, idx);
1695
1696 if (NIL_P(str)) {
1697 rb_encoding *enc = rb_enc_from_index(idx);
1698
1699 if (!enc) return ST_CONTINUE;
1700 if (STRCASECMP((char*)name, rb_enc_name(enc)) == 0) {
1701 return ST_CONTINUE;
1702 }
1703 str = rb_fstring_cstr(rb_enc_name(enc));
1704 rb_ary_store(ary, idx, str);
1705 }
1706 key = rb_fstring_cstr((char *)name);
1707 rb_hash_aset(aliases, key, str);
1708 return ST_CONTINUE;
1709 }
1710
1711 /*
1712 * call-seq:
1713 * Encoding.aliases -> {"alias1" => "orig1", "alias2" => "orig2", ...}
1714 *
1715 * Returns the hash of available encoding alias and original encoding name.
1716 *
1717 * Encoding.aliases
1718 * #=> {"BINARY"=>"ASCII-8BIT", "ASCII"=>"US-ASCII", "ANSI_X3.4-1986"=>"US-ASCII",
1719 * "SJIS"=>"Shift_JIS", "eucJP"=>"EUC-JP", "CP932"=>"Windows-31J"}
1720 *
1721 */
1722
1723 static VALUE
rb_enc_aliases(VALUE klass)1724 rb_enc_aliases(VALUE klass)
1725 {
1726 VALUE aliases[2];
1727 aliases[0] = rb_hash_new();
1728 aliases[1] = rb_ary_new();
1729 st_foreach(enc_table.names, rb_enc_aliases_enc_i, (st_data_t)aliases);
1730 return aliases[0];
1731 }
1732
1733 /*
1734 * An Encoding instance represents a character encoding usable in Ruby. It is
1735 * defined as a constant under the Encoding namespace. It has a name and
1736 * optionally, aliases:
1737 *
1738 * Encoding::ISO_8859_1.name
1739 * #=> "ISO-8859-1"
1740 *
1741 * Encoding::ISO_8859_1.names
1742 * #=> ["ISO-8859-1", "ISO8859-1"]
1743 *
1744 * Ruby methods dealing with encodings return or accept Encoding instances as
1745 * arguments (when a method accepts an Encoding instance as an argument, it
1746 * can be passed an Encoding name or alias instead).
1747 *
1748 * "some string".encoding
1749 * #=> #<Encoding:UTF-8>
1750 *
1751 * string = "some string".encode(Encoding::ISO_8859_1)
1752 * #=> "some string"
1753 * string.encoding
1754 * #=> #<Encoding:ISO-8859-1>
1755 *
1756 * "some string".encode "ISO-8859-1"
1757 * #=> "some string"
1758 *
1759 * <code>Encoding::ASCII_8BIT</code> is a special encoding that is usually
1760 * used for a byte string, not a character string. But as the name insists,
1761 * its characters in the range of ASCII are considered as ASCII characters.
1762 * This is useful when you use ASCII-8BIT characters with other ASCII
1763 * compatible characters.
1764 *
1765 * == Changing an encoding
1766 *
1767 * The associated Encoding of a String can be changed in two different ways.
1768 *
1769 * First, it is possible to set the Encoding of a string to a new Encoding
1770 * without changing the internal byte representation of the string, with
1771 * String#force_encoding. This is how you can tell Ruby the correct encoding
1772 * of a string.
1773 *
1774 * string
1775 * #=> "R\xC3\xA9sum\xC3\xA9"
1776 * string.encoding
1777 * #=> #<Encoding:ISO-8859-1>
1778 * string.force_encoding(Encoding::UTF_8)
1779 * #=> "R\u00E9sum\u00E9"
1780 *
1781 * Second, it is possible to transcode a string, i.e. translate its internal
1782 * byte representation to another encoding. Its associated encoding is also
1783 * set to the other encoding. See String#encode for the various forms of
1784 * transcoding, and the Encoding::Converter class for additional control over
1785 * the transcoding process.
1786 *
1787 * string
1788 * #=> "R\u00E9sum\u00E9"
1789 * string.encoding
1790 * #=> #<Encoding:UTF-8>
1791 * string = string.encode!(Encoding::ISO_8859_1)
1792 * #=> "R\xE9sum\xE9"
1793 * string.encoding
1794 * #=> #<Encoding::ISO-8859-1>
1795 *
1796 * == Script encoding
1797 *
1798 * All Ruby script code has an associated Encoding which any String literal
1799 * created in the source code will be associated to.
1800 *
1801 * The default script encoding is <code>Encoding::UTF-8</code> after v2.0, but it can
1802 * be changed by a magic comment on the first line of the source code file (or
1803 * second line, if there is a shebang line on the first). The comment must
1804 * contain the word <code>coding</code> or <code>encoding</code>, followed
1805 * by a colon, space and the Encoding name or alias:
1806 *
1807 * # encoding: UTF-8
1808 *
1809 * "some string".encoding
1810 * #=> #<Encoding:UTF-8>
1811 *
1812 * The <code>__ENCODING__</code> keyword returns the script encoding of the file
1813 * which the keyword is written:
1814 *
1815 * # encoding: ISO-8859-1
1816 *
1817 * __ENCODING__
1818 * #=> #<Encoding:ISO-8859-1>
1819 *
1820 * <code>ruby -K</code> will change the default locale encoding, but this is
1821 * not recommended. Ruby source files should declare its script encoding by a
1822 * magic comment even when they only depend on US-ASCII strings or regular
1823 * expressions.
1824 *
1825 * == Locale encoding
1826 *
1827 * The default encoding of the environment. Usually derived from locale.
1828 *
1829 * see Encoding.locale_charmap, Encoding.find('locale')
1830 *
1831 * == Filesystem encoding
1832 *
1833 * The default encoding of strings from the filesystem of the environment.
1834 * This is used for strings of file names or paths.
1835 *
1836 * see Encoding.find('filesystem')
1837 *
1838 * == External encoding
1839 *
1840 * Each IO object has an external encoding which indicates the encoding that
1841 * Ruby will use to read its data. By default Ruby sets the external encoding
1842 * of an IO object to the default external encoding. The default external
1843 * encoding is set by locale encoding or the interpreter <code>-E</code> option.
1844 * Encoding.default_external returns the current value of the external
1845 * encoding.
1846 *
1847 * ENV["LANG"]
1848 * #=> "UTF-8"
1849 * Encoding.default_external
1850 * #=> #<Encoding:UTF-8>
1851 *
1852 * $ ruby -E ISO-8859-1 -e "p Encoding.default_external"
1853 * #<Encoding:ISO-8859-1>
1854 *
1855 * $ LANG=C ruby -e 'p Encoding.default_external'
1856 * #<Encoding:US-ASCII>
1857 *
1858 * The default external encoding may also be set through
1859 * Encoding.default_external=, but you should not do this as strings created
1860 * before and after the change will have inconsistent encodings. Instead use
1861 * <code>ruby -E</code> to invoke ruby with the correct external encoding.
1862 *
1863 * When you know that the actual encoding of the data of an IO object is not
1864 * the default external encoding, you can reset its external encoding with
1865 * IO#set_encoding or set it at IO object creation (see IO.new options).
1866 *
1867 * == Internal encoding
1868 *
1869 * To process the data of an IO object which has an encoding different
1870 * from its external encoding, you can set its internal encoding. Ruby will use
1871 * this internal encoding to transcode the data when it is read from the IO
1872 * object.
1873 *
1874 * Conversely, when data is written to the IO object it is transcoded from the
1875 * internal encoding to the external encoding of the IO object.
1876 *
1877 * The internal encoding of an IO object can be set with
1878 * IO#set_encoding or at IO object creation (see IO.new options).
1879 *
1880 * The internal encoding is optional and when not set, the Ruby default
1881 * internal encoding is used. If not explicitly set this default internal
1882 * encoding is +nil+ meaning that by default, no transcoding occurs.
1883 *
1884 * The default internal encoding can be set with the interpreter option
1885 * <code>-E</code>. Encoding.default_internal returns the current internal
1886 * encoding.
1887 *
1888 * $ ruby -e 'p Encoding.default_internal'
1889 * nil
1890 *
1891 * $ ruby -E ISO-8859-1:UTF-8 -e "p [Encoding.default_external, \
1892 * Encoding.default_internal]"
1893 * [#<Encoding:ISO-8859-1>, #<Encoding:UTF-8>]
1894 *
1895 * The default internal encoding may also be set through
1896 * Encoding.default_internal=, but you should not do this as strings created
1897 * before and after the change will have inconsistent encodings. Instead use
1898 * <code>ruby -E</code> to invoke ruby with the correct internal encoding.
1899 *
1900 * == IO encoding example
1901 *
1902 * In the following example a UTF-8 encoded string "R\u00E9sum\u00E9" is transcoded for
1903 * output to ISO-8859-1 encoding, then read back in and transcoded to UTF-8:
1904 *
1905 * string = "R\u00E9sum\u00E9"
1906 *
1907 * open("transcoded.txt", "w:ISO-8859-1") do |io|
1908 * io.write(string)
1909 * end
1910 *
1911 * puts "raw text:"
1912 * p File.binread("transcoded.txt")
1913 * puts
1914 *
1915 * open("transcoded.txt", "r:ISO-8859-1:UTF-8") do |io|
1916 * puts "transcoded text:"
1917 * p io.read
1918 * end
1919 *
1920 * While writing the file, the internal encoding is not specified as it is
1921 * only necessary for reading. While reading the file both the internal and
1922 * external encoding must be specified to obtain the correct result.
1923 *
1924 * $ ruby t.rb
1925 * raw text:
1926 * "R\xE9sum\xE9"
1927 *
1928 * transcoded text:
1929 * "R\u00E9sum\u00E9"
1930 *
1931 */
1932
1933 void
Init_Encoding(void)1934 Init_Encoding(void)
1935 {
1936 #undef rb_intern
1937 #define rb_intern(str) rb_intern_const(str)
1938 VALUE list;
1939 int i;
1940
1941 rb_cEncoding = rb_define_class("Encoding", rb_cObject);
1942 rb_define_alloc_func(rb_cEncoding, enc_s_alloc);
1943 rb_undef_method(CLASS_OF(rb_cEncoding), "new");
1944 rb_define_method(rb_cEncoding, "to_s", enc_name, 0);
1945 rb_define_method(rb_cEncoding, "inspect", enc_inspect, 0);
1946 rb_define_method(rb_cEncoding, "name", enc_name, 0);
1947 rb_define_method(rb_cEncoding, "names", enc_names, 0);
1948 rb_define_method(rb_cEncoding, "dummy?", enc_dummy_p, 0);
1949 rb_define_method(rb_cEncoding, "ascii_compatible?", enc_ascii_compatible_p, 0);
1950 rb_define_method(rb_cEncoding, "replicate", enc_replicate, 1);
1951 rb_define_singleton_method(rb_cEncoding, "list", enc_list, 0);
1952 rb_define_singleton_method(rb_cEncoding, "name_list", rb_enc_name_list, 0);
1953 rb_define_singleton_method(rb_cEncoding, "aliases", rb_enc_aliases, 0);
1954 rb_define_singleton_method(rb_cEncoding, "find", enc_find, 1);
1955 rb_define_singleton_method(rb_cEncoding, "compatible?", enc_compatible_p, 2);
1956
1957 rb_define_method(rb_cEncoding, "_dump", enc_dump, -1);
1958 rb_define_singleton_method(rb_cEncoding, "_load", enc_load, 1);
1959
1960 rb_define_singleton_method(rb_cEncoding, "default_external", get_default_external, 0);
1961 rb_define_singleton_method(rb_cEncoding, "default_external=", set_default_external, 1);
1962 rb_define_singleton_method(rb_cEncoding, "default_internal", get_default_internal, 0);
1963 rb_define_singleton_method(rb_cEncoding, "default_internal=", set_default_internal, 1);
1964 rb_define_singleton_method(rb_cEncoding, "locale_charmap", rb_locale_charmap, 0); /* in localeinit.c */
1965
1966 list = rb_ary_new2(enc_table.count);
1967 RBASIC_CLEAR_CLASS(list);
1968 rb_encoding_list = list;
1969 rb_gc_register_mark_object(list);
1970
1971 for (i = 0; i < enc_table.count; ++i) {
1972 rb_ary_push(list, enc_new(enc_table.list[i].enc));
1973 }
1974
1975 rb_marshal_define_compat(rb_cEncoding, Qnil, NULL, enc_m_loader);
1976 }
1977
1978 /* locale insensitive ctype functions */
1979
1980 void
rb_enc_foreach_name(int (* func)(st_data_t name,st_data_t idx,st_data_t arg),st_data_t arg)1981 rb_enc_foreach_name(int (*func)(st_data_t name, st_data_t idx, st_data_t arg), st_data_t arg)
1982 {
1983 st_foreach(enc_table.names, func, arg);
1984 }
1985