summaryrefslogtreecommitdiff
path: root/encoding.c
blob: 632f323c3d5ee77eb461fa18fb6485fa85902fa5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
/**********************************************************************

  encoding.c -

  $Author$
  created at: Thu May 24 17:23:27 JST 2007

  Copyright (C) 2007 Yukihiro Matsumoto

**********************************************************************/

#include "ruby/ruby.h"
#include "ruby/encoding.h"
#include "regenc.h"
#include <ctype.h>
#ifdef HAVE_LANGINFO_H
#include <langinfo.h>
#endif
#include "ruby/util.h"

static ID id_encoding;
VALUE rb_cEncoding;
static VALUE rb_encoding_list;

struct rb_encoding_entry {
    const char *name;
    rb_encoding *enc;
    rb_encoding *base;
};

static struct {
    struct rb_encoding_entry *list;
    int count;
    int size;
    st_table *names;
} enc_table;

void rb_enc_init(void);

#define ENCODING_COUNT ENCINDEX_BUILTIN_MAX

#define enc_autoload_p(enc) (!rb_enc_mbmaxlen(enc))

static int load_encoding(const char *name);

static void
enc_mark(void *ptr)
{
}

static VALUE
enc_new(rb_encoding *encoding)
{
    return Data_Wrap_Struct(rb_cEncoding, enc_mark, 0, encoding);
}

VALUE
rb_enc_from_encoding(rb_encoding *encoding)
{
    VALUE list, enc;
    int idx;

    if (!encoding) return Qnil;
    idx = ENC_TO_ENCINDEX(encoding);
    if (!(list = rb_encoding_list)) {
	rb_bug("rb_enc_from_encoding(%d\"%s\"): no rb_encoding_list",
	       idx, rb_enc_name(encoding));
    }
    enc = rb_ary_entry(list, idx);
    if (NIL_P(enc)) {
	rb_bug("rb_enc_from_encoding(%d\"%s\"): not created yet",
	       idx, rb_enc_name(encoding));
    }
    return enc;
}

static int enc_autoload(rb_encoding *);

static int
check_encoding(rb_encoding *enc)
{
    int index = rb_enc_to_index(enc);
    if (rb_enc_from_index(index) != enc)
	return -1;
    if (enc_autoload_p(enc)) {
	index = enc_autoload(enc);
    }
    return index;
}

static int
enc_check_encoding(VALUE obj)
{
    if (SPECIAL_CONST_P(obj) || BUILTIN_TYPE(obj) != T_DATA ||
	RDATA(obj)->dmark != enc_mark) {
	return -1;
    }
    return check_encoding(RDATA(obj)->data);
}

static int
must_encoding(VALUE enc)
{
    int index = enc_check_encoding(enc);
    if (index < 0) {
	rb_raise(rb_eTypeError, "wrong argument type %s (expected Encoding)",
		 rb_obj_classname(enc));
    }
    return index;
}

int
rb_to_encoding_index(VALUE enc)
{
    int idx;

    idx = enc_check_encoding(enc);
    if (idx >= 0) {
	return idx;
    }
    else if (NIL_P(enc = rb_check_string_type(enc))) {
	return -1;
    }
    if (!rb_enc_asciicompat(rb_enc_get(enc))) {
	return -1;
    }
    return rb_enc_find_index(StringValueCStr(enc));
}

static rb_encoding *
to_encoding(VALUE enc)
{
    int idx;

    StringValue(enc);
    if (!rb_enc_asciicompat(rb_enc_get(enc))) {
	rb_raise(rb_eArgError, "invalid name encoding (non ASCII)");
    }
    idx = rb_enc_find_index(StringValueCStr(enc));
    if (idx < 0) {
	rb_raise(rb_eArgError, "unknown encoding name - %s", RSTRING_PTR(enc));
    }
    return rb_enc_from_index(idx);
}

rb_encoding *
rb_to_encoding(VALUE enc)
{
    if (enc_check_encoding(enc) >= 0) return RDATA(enc)->data;
    return to_encoding(enc);
}

void
rb_gc_mark_encodings(void)
{
}

static int
enc_table_expand(int newsize)
{
    struct rb_encoding_entry *ent;
    int count = newsize;

    if (enc_table.size >= newsize) return newsize;
    newsize = (newsize + 7) / 8 * 8;
    ent = realloc(enc_table.list, sizeof(*enc_table.list) * newsize);
    if (!ent) return -1;
    memset(ent + enc_table.size, 0, sizeof(*ent)*(newsize - enc_table.size));
    enc_table.list = ent;
    enc_table.size = newsize;
    return count;
}

static int
enc_register_at(int index, const char *name, rb_encoding *encoding)
{
    struct rb_encoding_entry *ent = &enc_table.list[index];
    VALUE list;

    if (!ent->name) {
	ent->name = name = strdup(name);
    }
    else if (STRCASECMP(name, ent->name)) {
	return -1;
    }
    if (!ent->enc) {
	ent->enc = xmalloc(sizeof(rb_encoding));
    }
    if (encoding) {
	*ent->enc = *encoding;
    }
    else {
	memset(ent->enc, 0, sizeof(*ent->enc));
    }
    encoding = ent->enc;
    encoding->name = name;
    encoding->ruby_encoding_index = index;
    st_insert(enc_table.names, (st_data_t)name, (st_data_t)index);
    list = rb_encoding_list;
    if (list && NIL_P(rb_ary_entry(list, index))) {
	/* initialize encoding data */
	rb_ary_store(list, index, enc_new(encoding));
    }
    return index;
}

static int
enc_register(const char *name, rb_encoding *encoding)
{
    int index = enc_table.count;

    if ((index = enc_table_expand(index + 1)) < 0) return -1;
    enc_table.count = index;
    return enc_register_at(index - 1, name, encoding);
}

static void set_encoding_const(const char *, rb_encoding *);
int rb_enc_registered(const char *name);

int
rb_enc_register(const char *name, rb_encoding *encoding)
{
    int index = rb_enc_registered(name);

    if (index >= 0) {
	rb_encoding *oldenc = rb_enc_from_index(index);
	if (STRCASECMP(name, rb_enc_name(oldenc))) {
	    index = enc_register(name, encoding);
	}
	else if (enc_autoload_p(oldenc) || !ENC_DUMMY_P(oldenc)) {
	    enc_register_at(index, name, encoding);
	}
	else {
	    rb_raise(rb_eArgError, "encoding %s is already registered", name);
	}
    }
    else {
	index = enc_register(name, encoding);
	set_encoding_const(name, rb_enc_from_index(index));
    }
    return index;
}

void
rb_encdb_declare(const char *name)
{
    int idx = rb_enc_registered(name);
    if (idx < 0) {
	idx = enc_register(name, 0);
    }
    set_encoding_const(name, rb_enc_from_index(idx));
}

static void
enc_check_duplication(const char *name)
{
    if (rb_enc_registered(name) >= 0) {
	rb_raise(rb_eArgError, "encoding %s is already registered", name);
    }
}

static rb_encoding*
set_base_encoding(int index, rb_encoding *base)
{
    rb_encoding *enc = enc_table.list[index].enc;

    enc_table.list[index].base = base;
    if (rb_enc_dummy_p(base)) ENC_SET_DUMMY(enc);
    return enc;
}

int
rb_enc_replicate(const char *name, rb_encoding *encoding)
{
    int idx;

    enc_check_duplication(name);
    idx = enc_register(name, encoding);
    set_base_encoding(idx, encoding);
    set_encoding_const(name, rb_enc_from_index(idx));
    return idx;
}

static int
enc_replicate(int idx, const char *name, rb_encoding *origenc)
{
    if (idx < 0) {
	idx = enc_register(name, origenc);
    }
    else {
	idx = enc_register_at(idx, name, origenc);
    }
    if (idx >= 0) {
	set_base_encoding(idx, origenc);
	set_encoding_const(name, rb_enc_from_index(idx));
    }
    return idx;
}

int
rb_encdb_replicate(const char *name, const char *orig)
{
    int origidx = rb_enc_registered(orig);
    int idx = rb_enc_registered(name);

    if (origidx < 0) {
	origidx = enc_register(orig, 0);
    }
    return enc_replicate(idx, name, rb_enc_from_index(origidx));
}

int
rb_define_dummy_encoding(const char *name)
{
    int index = rb_enc_replicate(name, rb_ascii8bit_encoding());
    rb_encoding *enc = enc_table.list[index].enc;

    ENC_SET_DUMMY(enc);
    return index;
}

int
rb_encdb_dummy(const char *name)
{
    int index = enc_replicate(rb_enc_registered(name), name,
			      rb_ascii8bit_encoding());
    rb_encoding *enc = enc_table.list[index].enc;

    ENC_SET_DUMMY(enc);
    return index;
}

/*
 * call-seq:
 *   enc.dummy? => true or false
 *
 * Returns true for dummy encodings.
 * A dummy encoding is an encoding for which character handling is not properly
 * implemented.
 * It is used for stateful encodings.
 *
 *   Encoding::ISO_2022_JP.dummy?       #=> true
 *   Encoding::UTF_8.dummy?             #=> false
 *
 */
static VALUE
enc_dummy_p(VALUE enc)
{
    return ENC_DUMMY_P(enc_table.list[must_encoding(enc)].enc) ? Qtrue : Qfalse;
}

static int
enc_alias(const char *alias, int idx)
{
    alias = strdup(alias);
    st_insert(enc_table.names, (st_data_t)alias, (st_data_t)idx);
    set_encoding_const(alias, rb_enc_from_index(idx));
    return idx;
}

int
rb_enc_alias(const char *alias, const char *orig)
{
    int idx;

    enc_check_duplication(alias);
    if (!enc_table.list) {
	rb_enc_init();
    }
    if ((idx = rb_enc_find_index(orig)) < 0) {
	return -1;
    }
    return enc_alias(alias, idx);
}

int
rb_encdb_alias(const char *alias, const char *orig)
{
    int idx = rb_enc_registered(orig);

    if (idx < 0) {
	idx = enc_register(orig, 0);
    }
    return enc_alias(alias, idx);
}

enum {
    ENCINDEX_ASCII,
    ENCINDEX_UTF_8,
    ENCINDEX_US_ASCII,
    ENCINDEX_BUILTIN_MAX
};

extern rb_encoding OnigEncodingUTF_8;
extern rb_encoding OnigEncodingUS_ASCII;

void
rb_enc_init(void)
{
    enc_table_expand(ENCODING_COUNT + 1);
    if (!enc_table.names) {
	enc_table.names = st_init_strcasetable();
    }
#define ENC_REGISTER(enc) enc_register_at(ENCINDEX_##enc, rb_enc_name(&OnigEncoding##enc), &OnigEncoding##enc)
    ENC_REGISTER(ASCII);
    ENC_REGISTER(UTF_8);
    ENC_REGISTER(US_ASCII);
#undef ENC_REGISTER
    enc_table.count = ENCINDEX_BUILTIN_MAX;
}

rb_encoding *
rb_enc_from_index(int index)
{
    if (!enc_table.list) {
	rb_enc_init();
    }
    if (index < 0 || enc_table.count <= index) {
	return 0;
    }
    return enc_table.list[index].enc;
}

int
rb_enc_registered(const char *name)
{
    st_data_t idx = 0;

    if (!name) return -1;
    if (!enc_table.list) return -1;
    if (st_lookup(enc_table.names, (st_data_t)name, &idx)) {
	return (int)idx;
    }
    return -1;
}

static VALUE
require_enc(VALUE enclib)
{
    return rb_require_safe(enclib, rb_safe_level());
}

static int
load_encoding(const char *name)
{
    VALUE enclib = rb_sprintf("enc/%s", name);
    VALUE verbose = ruby_verbose;
    VALUE debug = ruby_debug;
    VALUE loaded;
    char *s = RSTRING_PTR(enclib) + 4, *e = RSTRING_END(enclib);
    int idx;

    while (s < e) {
	if (!ISALNUM(*s)) *s = '_';
	else if (ISUPPER(*s)) *s = TOLOWER(*s);
	++s;
    }
    OBJ_FREEZE(enclib);
    ruby_verbose = Qfalse;
    ruby_debug = Qfalse;
    loaded = rb_protect(require_enc, enclib, 0);
    ruby_verbose = verbose;
    ruby_debug = debug;
    rb_set_errinfo(Qnil);
    if (NIL_P(loaded)) return -1;
    if ((idx = rb_enc_registered(name)) < 0) return -1;
    if (enc_autoload_p(enc_table.list[idx].enc)) return -1;
    return idx;
}

static int
enc_autoload(rb_encoding *enc)
{
    int i;
    rb_encoding *base = enc_table.list[ENC_TO_ENCINDEX(enc)].base;

    if (base) {
	i = 0;
	do {
	    if (i >= enc_table.count) return -1;
	} while (enc_table.list[i].enc != base && (++i, 1));
	if (enc_autoload_p(base)) {
	    if (enc_autoload(base) < 0) return -1;
	}
	i = ENC_TO_ENCINDEX(enc);
	enc_register_at(i, rb_enc_name(enc), base);
    }
    else {
	i = load_encoding(rb_enc_name(enc));
    }
    return i;
}

int
rb_enc_find_index(const char *name)
{
    int i = rb_enc_registered(name);
    rb_encoding *enc;

    if (i < 0) {
	i = load_encoding(name);
    }
    else if (enc_autoload_p(enc = rb_enc_from_index(i))) {
	if (enc_autoload(enc) < 0) {
	    rb_warn("failed to load encoding (%s); use ASCII-8BIT instead",
		    name);
	    return 0;
	}
    }
    return i;
}

rb_encoding *
rb_enc_find(const char *name)
{
    int idx = rb_enc_find_index(name);
    if (idx < 0) idx = 0;
    return rb_enc_from_index(idx);
}

static inline int
enc_capable(VALUE obj)
{
    if (SPECIAL_CONST_P(obj)) return Qfalse;
    switch (BUILTIN_TYPE(obj)) {
      case T_STRING:
      case T_REGEXP:
      case T_FILE:
	return Qtrue;
      case T_DATA:
	if (RDATA(obj)->dmark == enc_mark) return Qtrue;
      default:
	return Qfalse;
    }
}

ID
rb_id_encoding(void)
{
    CONST_ID(id_encoding, "encoding");
    return id_encoding;
}

int
rb_enc_get_index(VALUE obj)
{
    int i = -1;
    VALUE tmp;

    switch (BUILTIN_TYPE(obj)) {
        default:
	case T_STRING:
	case T_REGEXP:
	    i = ENCODING_GET_INLINED(obj);
	    if (i == ENCODING_INLINE_MAX) {
		VALUE iv;

		iv = rb_ivar_get(obj, rb_id_encoding());
		i = NUM2INT(iv);
	    }
	    break;
	case T_FILE:
	    tmp = rb_funcall(obj, rb_intern("internal_encoding"), 0, 0);
	    if (NIL_P(tmp)) obj = rb_funcall(obj, rb_intern("external_encoding"), 0, 0);
	    else obj = tmp;
	    if (NIL_P(obj)) break;
	case T_DATA:
	    if (RDATA(obj)->dmark == enc_mark) {
		i = enc_check_encoding(obj);
	    }
	    break;
    }
    return i;
}

void
rb_enc_set_index(VALUE obj, int idx)
{
    if (idx < ENCODING_INLINE_MAX) {
	ENCODING_SET_INLINED(obj, idx);
	return;
    }
    ENCODING_SET_INLINED(obj, ENCODING_INLINE_MAX);
    rb_ivar_set(obj, rb_id_encoding(), INT2NUM(idx));
    return;
}

VALUE
rb_enc_associate_index(VALUE obj, int idx)
{
/*    enc_check_capable(obj);*/
    if (rb_enc_get_index(obj) == idx)
    	return obj;
    if (!ENC_CODERANGE_ASCIIONLY(obj) ||
	!rb_enc_asciicompat(rb_enc_from_index(idx))) {
	ENC_CODERANGE_CLEAR(obj);
    }
    rb_enc_set_index(obj, idx);
    return obj;
}

VALUE
rb_enc_associate(VALUE obj, rb_encoding *enc)
{
    return rb_enc_associate_index(obj, rb_enc_to_index(enc));
}

rb_encoding*
rb_enc_get(VALUE obj)
{
    return rb_enc_from_index(rb_enc_get_index(obj));
}

rb_encoding*
rb_enc_check(VALUE str1, VALUE str2)
{
    rb_encoding *enc = rb_enc_compatible(str1, str2);
    if (!enc)
	rb_raise(rb_eEncCompatError, "incompatible character encodings: %s and %s",
		 rb_enc_name(rb_enc_get(str1)),
		 rb_enc_name(rb_enc_get(str2)));
    return enc;
}

rb_encoding*
rb_enc_compatible(VALUE str1, VALUE str2)
{
    int idx1, idx2;
    rb_encoding *enc1, *enc2;

    idx1 = rb_enc_get_index(str1);
    idx2 = rb_enc_get_index(str2);

    if (idx1 < 0 || idx2 < 0)
        return 0;

    if (idx1 == idx2) {
	return rb_enc_from_index(idx1);
    }
    enc1 = rb_enc_from_index(idx1);
    enc2 = rb_enc_from_index(idx2);

    if (TYPE(str2) == T_STRING && RSTRING_LEN(str2) == 0)
	return enc1;
    if (TYPE(str1) == T_STRING && RSTRING_LEN(str1) == 0)
	return enc2;
    if (!rb_enc_asciicompat(enc1) || !rb_enc_asciicompat(enc2)) {
	return 0;
    }

    /* objects whose encoding is the same of contents */
    if (BUILTIN_TYPE(str2) != T_STRING && idx2 == ENCINDEX_US_ASCII)
	return enc1;
    if (BUILTIN_TYPE(str1) != T_STRING && idx1 == ENCINDEX_US_ASCII)
	return enc2;

    if (BUILTIN_TYPE(str1) != T_STRING) {
	VALUE tmp = str1;
	int idx0 = idx1;
	str1 = str2;
	str2 = tmp;
	idx1 = idx2;
	idx2 = idx0;
    }
    if (BUILTIN_TYPE(str1) == T_STRING) {
	int cr1, cr2;

	cr1 = rb_enc_str_coderange(str1);
	if (BUILTIN_TYPE(str2) == T_STRING) {
	    cr2 = rb_enc_str_coderange(str2);
	    if (cr1 != cr2) {
		/* may need to handle ENC_CODERANGE_BROKEN */
		if (cr1 == ENC_CODERANGE_7BIT) return enc2;
		if (cr2 == ENC_CODERANGE_7BIT) return enc1;
	    }
	    if (cr2 == ENC_CODERANGE_7BIT) {
		if (idx1 == ENCINDEX_ASCII) return enc2;
		return enc1;
	    }
	}
	if (cr1 == ENC_CODERANGE_7BIT)
	    return enc2;
    }
    return 0;
}

void
rb_enc_copy(VALUE obj1, VALUE obj2)
{
    rb_enc_associate_index(obj1, rb_enc_get_index(obj2));
}


/*
 *  call-seq:
 *     obj.encoding   => encoding
 *
 *  Returns the Encoding object that represents the encoding of obj.
 */

VALUE
rb_obj_encoding(VALUE obj)
{
    rb_encoding *enc = rb_enc_get(obj);
    if (!enc) {
	rb_raise(rb_eTypeError, "unknown encoding");
    }
    return rb_enc_from_encoding(enc);
}

int
rb_enc_mbclen(const char *p, const char *e, rb_encoding *enc)
{
    int n = ONIGENC_PRECISE_MBC_ENC_LEN(enc, (UChar*)p, (UChar*)e);
    if (MBCLEN_CHARFOUND_P(n) && MBCLEN_CHARFOUND_LEN(n) <= e-p)
        return MBCLEN_CHARFOUND_LEN(n);
    else {
        int min = rb_enc_mbminlen(enc);
        return min <= e-p ? min : e-p;
    }
}

int
rb_enc_precise_mbclen(const char *p, const char *e, rb_encoding *enc)
{
    int n;
    if (e <= p)
        return ONIGENC_CONSTRUCT_MBCLEN_NEEDMORE(1);
    n = ONIGENC_PRECISE_MBC_ENC_LEN(enc, (UChar*)p, (UChar*)e);
    if (e-p < n)
        return ONIGENC_CONSTRUCT_MBCLEN_NEEDMORE(n-(e-p));
    return n;
}

int
rb_enc_ascget(const char *p, const char *e, int *len, rb_encoding *enc)
{
    unsigned int c, l;
    if (e <= p)
        return -1;
    if (rb_enc_asciicompat(enc)) {
        c = (unsigned char)*p;
        if (!ISASCII(c))
            return -1;
        if (len) *len = 1;
        return c;
    }
    l = rb_enc_precise_mbclen(p, e, enc);
    if (!MBCLEN_CHARFOUND_P(l))
        return -1;
    c = rb_enc_mbc_to_codepoint(p, e, enc);
    if (!rb_enc_isascii(c, enc))
        return -1;
    if (len) *len = l;
    return c;
}

unsigned int
rb_enc_codepoint(const char *p, const char *e, rb_encoding *enc)
{
    int r;
    if (e <= p)
        rb_raise(rb_eArgError, "empty string");
    r = rb_enc_precise_mbclen(p, e, enc);
    if (MBCLEN_CHARFOUND_P(r))
        return rb_enc_mbc_to_codepoint(p, e, enc);
    else
	rb_raise(rb_eArgError, "invalid byte sequence in %s", rb_enc_name(enc));
}

int
rb_enc_codelen(int c, rb_encoding *enc)
{
    int n = ONIGENC_CODE_TO_MBCLEN(enc,c);
    if (n == 0) {
	rb_raise(rb_eArgError, "invalid codepoint 0x%x in %s", c, rb_enc_name(enc));
    }
    return n;
}

int
rb_enc_toupper(int c, rb_encoding *enc)
{
    return (ONIGENC_IS_ASCII_CODE(c)?ONIGENC_ASCII_CODE_TO_UPPER_CASE(c):(c));
}

int
rb_enc_tolower(int c, rb_encoding *enc)
{
    return (ONIGENC_IS_ASCII_CODE(c)?ONIGENC_ASCII_CODE_TO_LOWER_CASE(c):(c));
}

/*
 * call-seq:
 *   enc.inspect => string
 *
 * Returns a string which represents the encoding for programmers.
 *
 *   Encoding::UTF_8.inspect       #=> "#<Encoding:UTF-8>"
 *   Encoding::ISO_2022_JP.inspect #=> "#<Encoding:ISO-2022-JP (dummy)>"
 */
static VALUE
enc_inspect(VALUE self)
{
    VALUE str = rb_sprintf("#<%s:%s%s>", rb_obj_classname(self),
		      rb_enc_name((rb_encoding*)DATA_PTR(self)),
		      (enc_dummy_p(self) ? " (dummy)" : ""));
    ENCODING_CODERANGE_SET(str, rb_usascii_encindex(), ENC_CODERANGE_7BIT);
    return str;
}

/*
 * call-seq:
 *   enc.name => string
 *
 * Returns the name of the encoding.
 *
 *   Encoding::UTF_8.name       => "UTF-8"
 */
static VALUE
enc_name(VALUE self)
{
    return rb_usascii_str_new2(rb_enc_name((rb_encoding*)DATA_PTR(self)));
}

static int
enc_names_i(st_data_t name, st_data_t idx, st_data_t args)
{
    VALUE *arg = (VALUE *)args;

    if ((int)idx == (int)arg[0]) {
	VALUE str = rb_usascii_str_new2((char *)name);
	OBJ_FREEZE(str);
	rb_ary_push(arg[1], str);
    }
    return ST_CONTINUE;
}

/*
 * call-seq:
 *   enc.names => array
 *
 * Returns the list of name and aliases of the encoding.
 *
 *   Encoding::WINDOWS_31J.names => ["Windows-31J", "CP932", "csWindows31J"]
 */
static VALUE
enc_names(VALUE self)
{
    VALUE args[2];

    args[0] = (VALUE)rb_to_encoding_index(self);
    args[1] = rb_ary_new2(0);
    st_foreach(enc_table.names, enc_names_i, (st_data_t)args);
    return args[1];
}

/*
 * call-seq:
 *   Encoding.list => [enc1, enc2, ...]
 *
 * Returns the list of loaded encodings.
 *
 *   Encoding.list
 *   => [#<Encoding:ASCII-8BIT>, #<Encoding:UTF-8>,
 *       #<Encoding:ISO-2022-JP (dummy)>]
 *
 *   Encoding.find("US-ASCII")
 *   => #<Encoding:US-ASCII>
 *
 *   Encoding.list
 *   => [#<Encoding:ASCII-8BIT>, #<Encoding:UTF-8>,
 *       #<Encoding:US-ASCII>, #<Encoding:ISO-2022-JP (dummy)>]
 *
 */
static VALUE
enc_list(VALUE klass)
{
    VALUE ary = rb_ary_new2(0);
    rb_ary_replace(ary, rb_encoding_list);
    return ary;
}

/*
 * call-seq:
 *   Encoding.find(string) => enc
 *   Encoding.find(symbol) => enc
 *
 * Search the encoding with specified <i>name</i>.
 * <i>name</i> should be a string or symbol.
 *
 *   Encoding.find("US-ASCII")  => #<Encoding:US-ASCII>
 *   Encoding.find(:Shift_JIS)  => #<Encoding:Shift_JIS>
 *
 */
static VALUE
enc_find(VALUE klass, VALUE enc)
{
    return rb_enc_from_encoding(to_encoding(enc));
}

/*
 * call-seq:
 *   Encoding.compatible?(str1, str2) => enc or nil
 *
 * Checks the compatibility of two strings.
 * If they are compatible, means concatenatable, 
 * returns an encoding which the concatinated string will be.
 * If they are not compatible, nil is returned.
 *
 *   Encoding.compatible?("\xa1".force_encoding("iso-8859-1"), "b")
 *   => #<Encoding:ISO-8859-1>
 *
 *   Encoding.compatible?(
 *     "\xa1".force_encoding("iso-8859-1"),
 *     "\xa1\xa1".force_encoding("euc-jp"))
 *   => nil
 *
 */
static VALUE
enc_compatible_p(VALUE klass, VALUE str1, VALUE str2)
{
    rb_encoding *enc;

    if (!enc_capable(str1)) return Qnil;
    if (!enc_capable(str2)) return Qnil;
    enc = rb_enc_compatible(str1, str2);
    if (!enc) return Qnil;
    return rb_enc_from_encoding(enc);
}

/* :nodoc: */
static VALUE
enc_dump(int argc, VALUE *argv, VALUE self)
{
    rb_scan_args(argc, argv, "01", 0);
    return enc_name(self);
}

/* :nodoc: */
static VALUE
enc_load(VALUE klass, VALUE str)
{
    return enc_find(klass, str);
}

rb_encoding *
rb_ascii8bit_encoding(void)
{
    if (!enc_table.list) {
	rb_enc_init();
    }
    return enc_table.list[ENCINDEX_ASCII].enc;
}

int
rb_ascii8bit_encindex(void)
{
    return ENCINDEX_ASCII;
}

rb_encoding *
rb_utf8_encoding(void)
{
    if (!enc_table.list) {
	rb_enc_init();
    }
    return enc_table.list[ENCINDEX_UTF_8].enc;
}

int
rb_utf8_encindex(void)
{
    return ENCINDEX_UTF_8;
}

rb_encoding *
rb_usascii_encoding(void)
{
    if (!enc_table.list) {
	rb_enc_init();
    }
    return enc_table.list[ENCINDEX_US_ASCII].enc;
}

int
rb_usascii_encindex(void)
{
    return ENCINDEX_US_ASCII;
}

rb_encoding *
rb_locale_encoding(void)
{
    VALUE charmap = rb_locale_charmap(rb_cEncoding);
    int idx;

    if (NIL_P(charmap))
        return rb_usascii_encoding();
    else
        idx = rb_enc_find_index(StringValueCStr(charmap));
    if (idx < 0)
        return rb_ascii8bit_encoding();

    return rb_enc_from_index(idx);
}

rb_encoding *
rb_filesystem_encoding(void)
{
    rb_encoding *enc;
#if defined _WIN32
    enc = rb_locale_encoding();
#elif defined __APPLE__
    enc = rb_enc_find("UTF8-MAC");
#else
    enc = rb_default_external_encoding();
#endif
    return enc;
}

static int default_external_index;
static rb_encoding *default_external;

rb_encoding *
rb_default_external_encoding(void)
{
    if (!default_external) {
	default_external = rb_enc_from_index(default_external_index);
    }
    return default_external;
}

VALUE
rb_enc_default_external(void)
{
    return rb_enc_from_encoding(rb_default_external_encoding());
}

/*
 * call-seq:
 *   Encoding.default_external => enc
 *
 * Returns default external encoding.
 *
 * It is initialized by the locale or -E option,
 * and can't be modified after that.
 */
static VALUE
get_default_external(VALUE klass)
{
    return rb_enc_default_external();
}

void
rb_enc_set_default_external(VALUE encoding)
{
    default_external_index = rb_enc_to_index(rb_to_encoding(encoding));
    default_external = 0;
}

/* -2 => not yet set, -1 => nil */
static int default_internal_index = -2;
static rb_encoding *default_internal;

rb_encoding *
rb_default_internal_encoding(void)
{
    if (!default_internal && default_internal_index >= 0) {
	default_internal = rb_enc_from_index(default_internal_index);
    }
    return default_internal;
}

VALUE
rb_enc_default_internal(void)
{
    /* Note: These functions cope with default_internal not being set */
    return rb_enc_from_encoding(rb_default_internal_encoding());
}

/*
 * call-seq:
 *   Encoding.default_internal => enc
 *
 * Returns default internal encoding.
 *
 * It is initialized by the source internal_encoding or -E option,
 * and can't be modified after that.
 */
static VALUE
get_default_internal(VALUE klass)
{
    return rb_enc_default_internal();
}

void
rb_enc_set_default_internal(VALUE encoding)
{
    if (default_internal_index != -2)
	/* Already set */
	return;
    default_internal_index = encoding == Qnil ?
				-1 :rb_enc_to_index(rb_to_encoding(encoding));
    /* Convert US-ASCII => UTF-8 */
    if (default_internal_index == rb_usascii_encindex())
	default_internal_index = rb_utf8_encindex();
    default_internal = 0;
}

/*
 * call-seq:
 *   Encoding.locale_charmap => string
 *
 * Returns the locale charmap name.
 *
 *   Debian GNU/Linux
 *     LANG=C
 *       Encoding.locale_charmap  => "ANSI_X3.4-1968"
 *     LANG=ja_JP.EUC-JP
 *       Encoding.locale_charmap  => "EUC-JP"
 *
 *   SunOS 5
 *     LANG=C
 *       Encoding.locale_charmap  => "646"
 *     LANG=ja
 *       Encoding.locale_charmap  => "eucJP"
 *
 */
VALUE
rb_locale_charmap(VALUE klass)
{
#if defined NO_LOCALE_CHARMAP
    return rb_usascii_str_new2("ASCII-8BIT");
#elif defined HAVE_LANGINFO_H
    char *codeset;
    codeset = nl_langinfo(CODESET);
    return rb_usascii_str_new2(codeset);
#elif defined _WIN32
    return rb_sprintf("CP%d", GetACP());
#else
    return Qnil;
#endif
}

static void
set_encoding_const(const char *name, rb_encoding *enc)
{
    VALUE encoding = rb_enc_from_encoding(enc);
    char *s = (char *)name;
    int haslower = 0, hasupper = 0, valid = 0;

    if (ISDIGIT(*s)) return;
    if (ISUPPER(*s)) {
	hasupper = 1;
	while (*++s && (ISALNUM(*s) || *s == '_')) {
	    if (ISLOWER(*s)) haslower = 1;
	}
    }
    if (!*s) {
	valid = 1;
	rb_define_const(rb_cEncoding, name, encoding);
    }
    if (!valid || haslower) {
	int len = strlen(name) + 1;
	if (!haslower || !hasupper) {
	    do {
		if (ISLOWER(*s)) haslower = 1;
		if (ISUPPER(*s)) hasupper = 1;
	    } while (*++s && (!haslower || !hasupper));
	}
	MEMCPY(s = ALLOCA_N(char, len), name, char, len);
	name = s;
	if (!valid) {
	    if (ISLOWER(*s)) *s = ONIGENC_ASCII_CODE_TO_UPPER_CASE((int)*s);
	    for (; *s; ++s) {
		if (!ISALNUM(*s)) *s = '_';
	    }
	    if (hasupper) {
		rb_define_const(rb_cEncoding, name, encoding);
	    }
	}
	if (haslower) {
	    for (s = (char *)name; *s; ++s) {
		if (ISLOWER(*s)) *s = ONIGENC_ASCII_CODE_TO_UPPER_CASE((int)*s);
	    }
	    rb_define_const(rb_cEncoding, name, encoding);
	}
    }
}

static int
rb_enc_name_list_i(st_data_t name, st_data_t idx, st_data_t arg)
{
    VALUE ary = (VALUE)arg;
    VALUE str = rb_usascii_str_new2((char *)name);
    OBJ_FREEZE(str);
    rb_ary_push(ary, str);
    return ST_CONTINUE;
}

/*
 * call-seq:
 *   Encoding.name_list => ["enc1", "enc2", ...]
 *
 * Returns the list of available encoding names.
 *
 *   Encoding.name_list
 *   => ["US-ASCII", "ASCII-8BIT", "UTF-8",
 *       "ISO-8859-1", "Shift_JIS", "EUC-JP",
 *       "Windows-31J",
 *       "BINARY", "CP932", "eucJP"]
 *
 * This list doesn't include dummy encodings.
 *
 */

static VALUE
rb_enc_name_list(VALUE klass)
{
    VALUE ary = rb_ary_new2(enc_table.names->num_entries);
    st_foreach(enc_table.names, rb_enc_name_list_i, (st_data_t)ary);
    return ary;
}

static int
rb_enc_aliases_enc_i(st_data_t name, st_data_t orig, st_data_t arg)
{
    VALUE *p = (VALUE *)arg;
    VALUE aliases = p[0], ary = p[1];
    int idx = (int)orig;
    VALUE key, str = rb_ary_entry(ary, idx);

    if (NIL_P(str)) {
	rb_encoding *enc = rb_enc_from_index(idx);

	if (STRCASECMP((char*)name, rb_enc_name(enc)) == 0) {
	    return ST_CONTINUE;
	}
	str = rb_usascii_str_new2(rb_enc_name(enc));
	OBJ_FREEZE(str);
	rb_ary_store(ary, idx, str);
    }
    key = rb_usascii_str_new2((char *)name);
    OBJ_FREEZE(key);
    rb_hash_aset(aliases, key, str);
    return ST_CONTINUE;
}

/*
 * call-seq:
 *   Encoding.aliases => {"alias1" => "orig1", "alias2" => "orig2", ...}
 *
 * Returns the hash of available encoding alias and original encoding name.
 *
 *   Encoding.aliases
 *   => {"BINARY"=>"ASCII-8BIT", "ASCII"=>"US-ASCII", "ANSI_X3.4-1986"=>"US-ASCII",
 *       "SJIS"=>"Shift_JIS", "eucJP"=>"EUC-JP", "CP932"=>"Windows-31J"}
 *
 */

static VALUE
rb_enc_aliases(VALUE klass)
{
    VALUE aliases[2];
    aliases[0] = rb_hash_new();
    aliases[1] = rb_ary_new();
    st_foreach(enc_table.names, rb_enc_aliases_enc_i, (st_data_t)aliases);
    return aliases[0];
}

void
Init_Encoding(void)
{
#undef rb_intern
#define rb_intern(str) rb_intern_const(str)
    VALUE list;
    int i;

    rb_cEncoding = rb_define_class("Encoding", rb_cObject);
    rb_undef_alloc_func(rb_cEncoding);
    rb_define_method(rb_cEncoding, "to_s", enc_name, 0);
    rb_define_method(rb_cEncoding, "inspect", enc_inspect, 0);
    rb_define_method(rb_cEncoding, "name", enc_name, 0);
    rb_define_method(rb_cEncoding, "names", enc_names, 0);
    rb_define_method(rb_cEncoding, "dummy?", enc_dummy_p, 0);
    rb_define_singleton_method(rb_cEncoding, "list", enc_list, 0);
    rb_define_singleton_method(rb_cEncoding, "name_list", rb_enc_name_list, 0);
    rb_define_singleton_method(rb_cEncoding, "aliases", rb_enc_aliases, 0);
    rb_define_singleton_method(rb_cEncoding, "find", enc_find, 1);
    rb_define_singleton_method(rb_cEncoding, "compatible?", enc_compatible_p, 2);

    rb_define_method(rb_cEncoding, "_dump", enc_dump, -1);
    rb_define_singleton_method(rb_cEncoding, "_load", enc_load, 1);

    rb_define_singleton_method(rb_cEncoding, "default_external", get_default_external, 0);
    rb_define_singleton_method(rb_cEncoding, "default_internal", get_default_internal, 0);
    rb_define_singleton_method(rb_cEncoding, "locale_charmap", rb_locale_charmap, 0);

    list = rb_ary_new2(enc_table.count);
    RBASIC(list)->klass = 0;
    rb_encoding_list = list;
    rb_gc_register_mark_object(list);

    for (i = 0; i < enc_table.count; ++i) {
	rb_ary_push(list, enc_new(enc_table.list[i].enc));
    }
}

/* locale insensitive functions */

#define ctype_test(c, ctype) \
    (rb_isascii(c) && ONIGENC_IS_ASCII_CODE_CTYPE((c), ctype))

int rb_isalnum(int c) { return ctype_test(c, ONIGENC_CTYPE_ALNUM); }
int rb_isalpha(int c) { return ctype_test(c, ONIGENC_CTYPE_ALPHA); }
int rb_isblank(int c) { return ctype_test(c, ONIGENC_CTYPE_BLANK); }
int rb_iscntrl(int c) { return ctype_test(c, ONIGENC_CTYPE_CNTRL); }
int rb_isdigit(int c) { return ctype_test(c, ONIGENC_CTYPE_DIGIT); }
int rb_isgraph(int c) { return ctype_test(c, ONIGENC_CTYPE_GRAPH); }
int rb_islower(int c) { return ctype_test(c, ONIGENC_CTYPE_LOWER); }
int rb_isprint(int c) { return ctype_test(c, ONIGENC_CTYPE_PRINT); }
int rb_ispunct(int c) { return ctype_test(c, ONIGENC_CTYPE_PUNCT); }
int rb_isspace(int c) { return ctype_test(c, ONIGENC_CTYPE_SPACE); }
int rb_isupper(int c) { return ctype_test(c, ONIGENC_CTYPE_UPPER); }
int rb_isxdigit(int c) { return ctype_test(c, ONIGENC_CTYPE_XDIGIT); }

int
rb_tolower(int c)
{
    return rb_isascii(c) ? ONIGENC_ASCII_CODE_TO_LOWER_CASE(c) : c;
}

int
rb_toupper(int c)
{
    return rb_isascii(c) ? ONIGENC_ASCII_CODE_TO_UPPER_CASE(c) : c;
}