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