Ruby 4.1.0dev (2026-12-05 revision 9e7be751113d7486b00b18200ea1046ef59adc9c)
transcode.c (9e7be751113d7486b00b18200ea1046ef59adc9c)
1/**********************************************************************
2
3 transcode.c -
4
5 $Author$
6 created at: Tue Oct 30 16:10:22 JST 2007
7
8 Copyright (C) 2007 Martin Duerst
9
10**********************************************************************/
11
12#include "ruby/internal/config.h"
13
14#include <ctype.h>
15
16#include "internal.h"
17#include "internal/array.h"
18#include "internal/inits.h"
19#include "internal/gc.h"
20#include "internal/object.h"
21#include "internal/string.h"
22#include "internal/transcode.h"
23#include "internal/encoding.h"
24#include "ruby/encoding.h"
25#include "vm_sync.h"
26
27#include "transcode_data.h"
28#include "id.h"
29
30#define ENABLE_ECONV_NEWLINE_OPTION 1
31
32/* VALUE rb_cEncoding = rb_define_class("Encoding", rb_cObject); */
33static VALUE rb_eUndefinedConversionError;
34static VALUE rb_eInvalidByteSequenceError;
35static VALUE rb_eConverterNotFoundError;
36
37VALUE rb_cEncodingConverter;
38
39static ID id_destination_encoding;
40static ID id_destination_encoding_name;
41static ID id_error_bytes;
42static ID id_error_char;
43static ID id_incomplete_input;
44static ID id_readagain_bytes;
45static ID id_source_encoding;
46static ID id_source_encoding_name;
47
48static VALUE sym_invalid, sym_undef, sym_replace, sym_fallback;
49static VALUE sym_xml, sym_text, sym_attr;
50static VALUE sym_universal_newline;
51static VALUE sym_crlf_newline;
52static VALUE sym_cr_newline;
53static VALUE sym_lf_newline;
54#ifdef ENABLE_ECONV_NEWLINE_OPTION
55static VALUE sym_newline, sym_universal, sym_crlf, sym_cr, sym_lf;
56#endif
57static VALUE sym_partial_input;
58
59static VALUE sym_invalid_byte_sequence;
60static VALUE sym_undefined_conversion;
61static VALUE sym_destination_buffer_full;
62static VALUE sym_source_buffer_empty;
63static VALUE sym_finished;
64static VALUE sym_after_output;
65static VALUE sym_incomplete_input;
66
67static unsigned char *
68allocate_converted_string(const char *sname, const char *dname,
69 const unsigned char *str, size_t len,
70 unsigned char *caller_dst_buf, size_t caller_dst_bufsize,
71 size_t *dst_len_ptr, size_t *dst_bufsize_ptr);
72
73/* dynamic structure, one per conversion (similar to iconv_t) */
74/* may carry conversion state (e.g. for iso-2022-jp) */
75typedef struct rb_transcoding {
76 const rb_transcoder *transcoder;
77
78 int flags;
79
80 int resume_position;
81 unsigned int next_table;
82 VALUE next_info;
83 unsigned char next_byte;
84 unsigned int output_index;
85
86 ssize_t recognized_len; /* already interpreted */
87 ssize_t readagain_len; /* not yet interpreted */
88 union {
89 unsigned char ary[8]; /* max_input <= sizeof(ary) */
90 unsigned char *ptr; /* length: max_input */
91 } readbuf; /* recognized_len + readagain_len used */
92
93 ssize_t writebuf_off;
94 ssize_t writebuf_len;
95 union {
96 unsigned char ary[8]; /* max_output <= sizeof(ary) */
97 unsigned char *ptr; /* length: max_output */
98 } writebuf;
99
100 union rb_transcoding_state_t { /* opaque data for stateful encoding */
101 void *ptr;
102 char ary[sizeof(double) > sizeof(void*) ? sizeof(double) : sizeof(void*)];
103 double dummy_for_alignment;
104 } state;
106#define TRANSCODING_READBUF(tc) \
107 ((tc)->transcoder->max_input <= (int)sizeof((tc)->readbuf.ary) ? \
108 (tc)->readbuf.ary : \
109 (tc)->readbuf.ptr)
110#define TRANSCODING_WRITEBUF(tc) \
111 ((tc)->transcoder->max_output <= (int)sizeof((tc)->writebuf.ary) ? \
112 (tc)->writebuf.ary : \
113 (tc)->writebuf.ptr)
114#define TRANSCODING_WRITEBUF_SIZE(tc) \
115 ((tc)->transcoder->max_output <= (int)sizeof((tc)->writebuf.ary) ? \
116 sizeof((tc)->writebuf.ary) : \
117 (size_t)(tc)->transcoder->max_output)
118#define TRANSCODING_STATE_EMBED_MAX ((int)sizeof(union rb_transcoding_state_t))
119#define TRANSCODING_STATE(tc) \
120 ((tc)->transcoder->state_size <= (int)sizeof((tc)->state) ? \
121 (tc)->state.ary : \
122 (tc)->state.ptr)
123
124typedef struct {
125 struct rb_transcoding *tc;
126 unsigned char *out_buf_start;
127 unsigned char *out_data_start;
128 unsigned char *out_data_end;
129 unsigned char *out_buf_end;
130 rb_econv_result_t last_result;
132
134 int flags;
135 int started; /* bool */
136
137 const char *source_encoding_name;
138 const char *destination_encoding_name;
139
140 const unsigned char *replacement_str;
141 size_t replacement_len;
142 size_t replacement_bufsize;
143 const char *replacement_enc;
144
145 unsigned char *in_buf_start;
146 unsigned char *in_data_start;
147 unsigned char *in_data_end;
148 unsigned char *in_buf_end;
149 rb_econv_elem_t *elems;
150 int replacement_allocated; /* bool */
151 int num_allocated;
152 int num_trans;
153 int num_finished;
154 struct rb_transcoding *last_tc;
155
156 /* last error */
157 struct {
158 rb_econv_result_t result;
159 struct rb_transcoding *error_tc;
160 const char *source_encoding;
161 const char *destination_encoding;
162 const unsigned char *error_bytes_start;
163 size_t error_bytes_len;
164 size_t readagain_len;
165 } last_error;
166
167 /* The following fields are only for Encoding::Converter.
168 * rb_econv_open set them NULL. */
169 rb_encoding *source_encoding;
170 rb_encoding *destination_encoding;
171};
172
173/*
174 * Dispatch data and logic
175 */
176
177#define DECORATOR_P(sname, dname) (*(sname) == '\0')
178
179typedef struct {
180 const char *sname;
181 const char *dname;
182 const char *lib; /* null means no need to load a library */
183 const rb_transcoder *transcoder;
185
186static st_table *transcoder_table;
187
188static int
189free_inner_transcode_i(st_data_t key, st_data_t val, st_data_t arg)
190{
191 SIZED_FREE((transcoder_entry_t *)val);
192 return ST_DELETE;
193}
194
195static int
196free_transcode_i(st_data_t key, st_data_t val, st_data_t arg)
197{
198 st_foreach((void *)val, free_inner_transcode_i, 0);
199 st_free_table((void *)val);
200 return ST_DELETE;
201}
202
203void
204rb_free_transcoder_table(void)
205{
206 st_foreach(transcoder_table, free_transcode_i, 0);
207 st_free_table(transcoder_table);
208}
209
210static transcoder_entry_t *
211make_transcoder_entry(const char *sname, const char *dname)
212{
213 st_data_t val;
214 st_table *table2;
215
216 RB_VM_LOCKING() {
217 if (!st_lookup(transcoder_table, (st_data_t)sname, &val)) {
218 val = (st_data_t)st_init_strcasetable();
219 st_add_direct(transcoder_table, (st_data_t)sname, val);
220 }
221 table2 = (st_table *)val;
222 if (!st_lookup(table2, (st_data_t)dname, &val)) {
224 entry->sname = sname;
225 entry->dname = dname;
226 entry->lib = NULL;
227 entry->transcoder = NULL;
228 val = (st_data_t)entry;
229 st_add_direct(table2, (st_data_t)dname, val);
230 }
231 }
232 return (transcoder_entry_t *)val;
233}
234
235static transcoder_entry_t *
236get_transcoder_entry(const char *sname, const char *dname)
237{
238 st_data_t val = 0;
239 st_table *table2;
240 RB_VM_LOCKING() {
241 if (st_lookup(transcoder_table, (st_data_t)sname, &val)) {
242 table2 = (st_table *)val;
243 if (!st_lookup(table2, (st_data_t)dname, &val)) {
244 val = 0;
245 }
246 }
247 }
248 return (transcoder_entry_t *)val;
249}
250
251void
252rb_register_transcoder(const rb_transcoder *tr)
253{
254 const char *const sname = tr->src_encoding;
255 const char *const dname = tr->dst_encoding;
256
257 transcoder_entry_t *entry;
258
259 RB_VM_LOCKING() {
260 entry = make_transcoder_entry(sname, dname);
261 if (entry->transcoder) {
262 rb_raise(rb_eArgError, "transcoder from %s to %s has been already registered",
263 sname, dname);
264 }
265 entry->transcoder = tr;
266 }
267}
268
269static void
270declare_transcoder(const char *sname, const char *dname, const char *lib)
271{
272 transcoder_entry_t *entry;
273
274 entry = make_transcoder_entry(sname, dname);
275 entry->lib = lib;
276}
277
278static const char transcoder_lib_prefix[] = "enc/trans/";
279
280void
281rb_declare_transcoder(const char *enc1, const char *enc2, const char *lib)
282{
283 if (!lib) {
284 rb_raise(rb_eArgError, "invalid library name - (null)");
285 }
286 declare_transcoder(enc1, enc2, lib);
287}
288
289#define encoding_equal(enc1, enc2) (STRCASECMP((enc1), (enc2)) == 0)
290
291typedef struct search_path_queue_tag {
292 struct search_path_queue_tag *next;
293 const char *enc;
294} search_path_queue_t;
295
296typedef struct {
297 st_table *visited;
298 search_path_queue_t *queue;
299 search_path_queue_t **queue_last_ptr;
300 const char *base_enc;
302
303static int
304transcode_search_path_i(st_data_t key, st_data_t val, st_data_t arg)
305{
306 const char *dname = (const char *)key;
308 search_path_queue_t *q;
309
310 if (st_lookup(bfs->visited, (st_data_t)dname, &val)) {
311 return ST_CONTINUE;
312 }
313
314 q = ALLOC(search_path_queue_t);
315 q->enc = dname;
316 q->next = NULL;
317 *bfs->queue_last_ptr = q;
318 bfs->queue_last_ptr = &q->next;
319
320 st_add_direct(bfs->visited, (st_data_t)dname, (st_data_t)bfs->base_enc);
321 return ST_CONTINUE;
322}
323
324static int
325transcode_search_path(const char *sname, const char *dname,
326 void (*callback)(const char *sname, const char *dname, int depth, void *arg),
327 void *arg)
328{
330 search_path_queue_t *q;
331 st_data_t val;
332 st_table *table2;
333 int pathlen = -1;
334 bool found = false;
335 bool lookup_res;
336
337 if (encoding_equal(sname, dname))
338 return -1;
339
340 q = ALLOC(search_path_queue_t);
341 q->enc = sname;
342 q->next = NULL;
343 bfs.queue_last_ptr = &q->next;
344 bfs.queue = q;
345
346 bfs.visited = st_init_strcasetable(); // due to base encodings, we need to do search in a loop
347 st_add_direct(bfs.visited, (st_data_t)sname, (st_data_t)NULL);
348
349 RB_VM_LOCKING() {
350 while (bfs.queue) {
351 q = bfs.queue;
352 bfs.queue = q->next;
353 if (!bfs.queue) {
354 bfs.queue_last_ptr = &bfs.queue;
355 }
356
357 lookup_res = st_lookup(transcoder_table, (st_data_t)q->enc, &val); // src => table2
358 if (!lookup_res) {
359 SIZED_FREE(q);
360 continue;
361 }
362 table2 = (st_table *)val;
363
364 if (st_lookup(table2, (st_data_t)dname, &val)) { // dest => econv
365 st_add_direct(bfs.visited, (st_data_t)dname, (st_data_t)q->enc);
366 SIZED_FREE(q);
367 found = true;
368 break;
369 }
370
371 bfs.base_enc = q->enc;
372 st_foreach(table2, transcode_search_path_i, (st_data_t)&bfs);
373
374 bfs.base_enc = NULL;
375 SIZED_FREE(q);
376 }
377 }
378
379 while (bfs.queue) {
380 q = bfs.queue;
381 bfs.queue = q->next;
382 SIZED_FREE(q);
383 }
384
385 if (found) {
386 const char *enc = dname;
387 int depth;
388 pathlen = 0;
389 while (1) {
390 st_lookup(bfs.visited, (st_data_t)enc, &val);
391 if (!val)
392 break;
393 pathlen++;
394 enc = (const char *)val;
395 }
396 depth = pathlen;
397 enc = dname;
398 while (1) {
399 st_lookup(bfs.visited, (st_data_t)enc, &val);
400 if (!val)
401 break;
402 callback((const char *)val, enc, --depth, arg);
403 enc = (const char *)val;
404 }
405 }
406
407 st_free_table(bfs.visited);
408
409 return pathlen; /* is -1 if not found */
410}
411
412int rb_require_internal_silent(VALUE fname);
413
414static const rb_transcoder *
415load_transcoder_entry(transcoder_entry_t *entry)
416{
417 ASSERT_vm_unlocking();
418 if (entry->transcoder)
419 return entry->transcoder;
420
421 if (entry->lib) {
422 const char *const lib = entry->lib;
423 const size_t len = strlen(lib);
424 const size_t total_len = sizeof(transcoder_lib_prefix) - 1 + len;
425 const VALUE fn = rb_str_new(0, total_len);
426 char *const path = RSTRING_PTR(fn);
427
428 memcpy(path, transcoder_lib_prefix, sizeof(transcoder_lib_prefix) - 1);
429 memcpy(path + sizeof(transcoder_lib_prefix) - 1, lib, len);
430 rb_str_set_len(fn, total_len);
431 OBJ_FREEZE(fn);
432 rb_require_internal_silent(fn); // Sets entry->transcoder
433 }
434
435 if (entry->transcoder)
436 return entry->transcoder;
437
438 return NULL;
439}
440
441static const char*
442get_replacement_character(const char *encname, size_t *len_ret, const char **repl_encname_ptr)
443{
444 if (encoding_equal(encname, "UTF-8")) {
445 *len_ret = 3;
446 *repl_encname_ptr = "UTF-8";
447 return "\xEF\xBF\xBD";
448 }
449 else {
450 *len_ret = 1;
451 *repl_encname_ptr = "US-ASCII";
452 return "?";
453 }
454}
455
456/*
457 * Transcoding engine logic
458 */
459
460static const unsigned char *
461transcode_char_start(rb_transcoding *tc,
462 const unsigned char *in_start,
463 const unsigned char *inchar_start,
464 const unsigned char *in_p,
465 size_t *char_len_ptr)
466{
467 const unsigned char *ptr;
468 if (inchar_start - in_start < tc->recognized_len) {
469 MEMCPY(TRANSCODING_READBUF(tc) + tc->recognized_len,
470 inchar_start, unsigned char, in_p - inchar_start);
471 ptr = TRANSCODING_READBUF(tc);
472 }
473 else {
474 ptr = inchar_start - tc->recognized_len;
475 }
476 *char_len_ptr = tc->recognized_len + (in_p - inchar_start);
477 return ptr;
478}
479
481transcode_restartable0(const unsigned char **in_pos, unsigned char **out_pos,
482 const unsigned char *in_stop, unsigned char *out_stop,
483 rb_transcoding *tc,
484 const int opt)
485{
486 const rb_transcoder *tr = tc->transcoder;
487 int unitlen = tr->input_unit_length;
488 ssize_t readagain_len = 0;
489
490 const unsigned char *inchar_start;
491 const unsigned char *in_p;
492
493 unsigned char *out_p;
494
495 in_p = inchar_start = *in_pos;
496
497 out_p = *out_pos;
498
499#define SUSPEND(ret, num) \
500 do { \
501 tc->resume_position = (num); \
502 if (0 < in_p - inchar_start) \
503 MEMMOVE(TRANSCODING_READBUF(tc)+tc->recognized_len, \
504 inchar_start, unsigned char, in_p - inchar_start); \
505 *in_pos = in_p; \
506 *out_pos = out_p; \
507 tc->recognized_len += in_p - inchar_start; \
508 if (readagain_len) { \
509 tc->recognized_len -= readagain_len; \
510 tc->readagain_len = readagain_len; \
511 } \
512 return (ret); \
513 resume_label ## num:; \
514 } while (0)
515#define SUSPEND_OBUF(num) \
516 do { \
517 while (out_stop - out_p < 1) { SUSPEND(econv_destination_buffer_full, num); } \
518 } while (0)
519
520#define SUSPEND_AFTER_OUTPUT(num) \
521 if ((opt & ECONV_AFTER_OUTPUT) && *out_pos != out_p) { \
522 SUSPEND(econv_after_output, num); \
523 }
524
525#define next_table (tc->next_table)
526#define next_info (tc->next_info)
527#define next_byte (tc->next_byte)
528#define writebuf_len (tc->writebuf_len)
529#define writebuf_off (tc->writebuf_off)
530
531 switch (tc->resume_position) {
532 case 0: break;
533 case 1: goto resume_label1;
534 case 2: goto resume_label2;
535 case 3: goto resume_label3;
536 case 4: goto resume_label4;
537 case 5: goto resume_label5;
538 case 6: goto resume_label6;
539 case 7: goto resume_label7;
540 case 8: goto resume_label8;
541 case 9: goto resume_label9;
542 case 10: goto resume_label10;
543 case 11: goto resume_label11;
544 case 12: goto resume_label12;
545 case 13: goto resume_label13;
546 case 14: goto resume_label14;
547 case 15: goto resume_label15;
548 case 16: goto resume_label16;
549 case 17: goto resume_label17;
550 case 18: goto resume_label18;
551 case 19: goto resume_label19;
552 case 20: goto resume_label20;
553 case 21: goto resume_label21;
554 case 22: goto resume_label22;
555 case 23: goto resume_label23;
556 case 24: goto resume_label24;
557 case 25: goto resume_label25;
558 case 26: goto resume_label26;
559 case 27: goto resume_label27;
560 case 28: goto resume_label28;
561 case 29: goto resume_label29;
562 case 30: goto resume_label30;
563 case 31: goto resume_label31;
564 case 32: goto resume_label32;
565 case 33: goto resume_label33;
566 case 34: goto resume_label34;
567 }
568
569 while (1) {
570 inchar_start = in_p;
571 tc->recognized_len = 0;
572 next_table = tr->conv_tree_start;
573
574 SUSPEND_AFTER_OUTPUT(24);
575
576 if (in_stop <= in_p) {
577 if (!(opt & ECONV_PARTIAL_INPUT))
578 break;
579 SUSPEND(econv_source_buffer_empty, 7);
580 continue;
581 }
582
583#define BYTE_ADDR(index) (tr->byte_array + (index))
584#define WORD_ADDR(index) (tr->word_array + INFO2WORDINDEX(index))
585#define BL_BASE BYTE_ADDR(BYTE_LOOKUP_BASE(WORD_ADDR(next_table)))
586#define BL_INFO WORD_ADDR(BYTE_LOOKUP_INFO(WORD_ADDR(next_table)))
587#define BL_MIN_BYTE (BL_BASE[0])
588#define BL_MAX_BYTE (BL_BASE[1])
589#define BL_OFFSET(byte) (BL_BASE[2+(byte)-BL_MIN_BYTE])
590#define BL_ACTION(byte) (BL_INFO[BL_OFFSET((byte))])
591
592 next_byte = (unsigned char)*in_p++;
593 follow_byte:
594 if (next_byte < BL_MIN_BYTE || BL_MAX_BYTE < next_byte)
595 next_info = INVALID;
596 else {
597 next_info = (VALUE)BL_ACTION(next_byte);
598 }
599 follow_info:
600 switch (next_info & 0x1F) {
601 case NOMAP:
602 {
603 const unsigned char *p = inchar_start;
604 writebuf_off = 0;
605 while (p < in_p) {
606 TRANSCODING_WRITEBUF(tc)[writebuf_off++] = (unsigned char)*p++;
607 }
608 writebuf_len = writebuf_off;
609 writebuf_off = 0;
610 while (writebuf_off < writebuf_len) {
611 SUSPEND_OBUF(3);
612 *out_p++ = TRANSCODING_WRITEBUF(tc)[writebuf_off++];
613 }
614 }
615 continue;
616 case 0x00: case 0x04: case 0x08: case 0x0C:
617 case 0x10: case 0x14: case 0x18: case 0x1C:
618 SUSPEND_AFTER_OUTPUT(25);
619 while (in_p >= in_stop) {
620 if (!(opt & ECONV_PARTIAL_INPUT))
621 goto incomplete;
622 SUSPEND(econv_source_buffer_empty, 5);
623 }
624 next_byte = (unsigned char)*in_p++;
625 next_table = (unsigned int)next_info;
626 goto follow_byte;
627 case ZERObt: /* drop input */
628 continue;
629 case ONEbt:
630 SUSPEND_OBUF(9); *out_p++ = getBT1(next_info);
631 continue;
632 case TWObt:
633 SUSPEND_OBUF(10); *out_p++ = getBT1(next_info);
634 SUSPEND_OBUF(21); *out_p++ = getBT2(next_info);
635 continue;
636 case THREEbt:
637 SUSPEND_OBUF(11); *out_p++ = getBT1(next_info);
638 SUSPEND_OBUF(15); *out_p++ = getBT2(next_info);
639 SUSPEND_OBUF(16); *out_p++ = getBT3(next_info);
640 continue;
641 case FOURbt:
642 SUSPEND_OBUF(12); *out_p++ = getBT0(next_info);
643 SUSPEND_OBUF(17); *out_p++ = getBT1(next_info);
644 SUSPEND_OBUF(18); *out_p++ = getBT2(next_info);
645 SUSPEND_OBUF(19); *out_p++ = getBT3(next_info);
646 continue;
647 case GB4bt:
648 SUSPEND_OBUF(29); *out_p++ = getGB4bt0(next_info);
649 SUSPEND_OBUF(30); *out_p++ = getGB4bt1(next_info);
650 SUSPEND_OBUF(31); *out_p++ = getGB4bt2(next_info);
651 SUSPEND_OBUF(32); *out_p++ = getGB4bt3(next_info);
652 continue;
653 case STR1:
654 tc->output_index = 0;
655 while (tc->output_index < STR1_LENGTH(BYTE_ADDR(STR1_BYTEINDEX(next_info)))) {
656 SUSPEND_OBUF(28); *out_p++ = BYTE_ADDR(STR1_BYTEINDEX(next_info))[1+tc->output_index];
657 tc->output_index++;
658 }
659 continue;
660 case FUNii:
661 next_info = (VALUE)(*tr->func_ii)(TRANSCODING_STATE(tc), next_info);
662 goto follow_info;
663 case FUNsi:
664 {
665 const unsigned char *char_start;
666 size_t char_len;
667 char_start = transcode_char_start(tc, *in_pos, inchar_start, in_p, &char_len);
668 next_info = (VALUE)(*tr->func_si)(TRANSCODING_STATE(tc), char_start, (size_t)char_len);
669 goto follow_info;
670 }
671 case FUNio:
672 SUSPEND_OBUF(13);
673 if (tr->max_output <= out_stop - out_p)
674 out_p += tr->func_io(TRANSCODING_STATE(tc),
675 next_info, out_p, out_stop - out_p);
676 else {
677 writebuf_len = tr->func_io(TRANSCODING_STATE(tc),
678 next_info,
679 TRANSCODING_WRITEBUF(tc), TRANSCODING_WRITEBUF_SIZE(tc));
680 writebuf_off = 0;
681 while (writebuf_off < writebuf_len) {
682 SUSPEND_OBUF(20);
683 *out_p++ = TRANSCODING_WRITEBUF(tc)[writebuf_off++];
684 }
685 }
686 break;
687 case FUNso:
688 {
689 const unsigned char *char_start;
690 size_t char_len;
691 SUSPEND_OBUF(14);
692 if (tr->max_output <= out_stop - out_p) {
693 char_start = transcode_char_start(tc, *in_pos, inchar_start, in_p, &char_len);
694 out_p += tr->func_so(TRANSCODING_STATE(tc),
695 char_start, (size_t)char_len,
696 out_p, out_stop - out_p);
697 }
698 else {
699 char_start = transcode_char_start(tc, *in_pos, inchar_start, in_p, &char_len);
700 writebuf_len = tr->func_so(TRANSCODING_STATE(tc),
701 char_start, (size_t)char_len,
702 TRANSCODING_WRITEBUF(tc), TRANSCODING_WRITEBUF_SIZE(tc));
703 writebuf_off = 0;
704 while (writebuf_off < writebuf_len) {
705 SUSPEND_OBUF(22);
706 *out_p++ = TRANSCODING_WRITEBUF(tc)[writebuf_off++];
707 }
708 }
709 break;
710 }
711 case FUNsio:
712 {
713 const unsigned char *char_start;
714 size_t char_len;
715 SUSPEND_OBUF(33);
716 if (tr->max_output <= out_stop - out_p) {
717 char_start = transcode_char_start(tc, *in_pos, inchar_start, in_p, &char_len);
718 out_p += tr->func_sio(TRANSCODING_STATE(tc),
719 char_start, (size_t)char_len, next_info,
720 out_p, out_stop - out_p);
721 }
722 else {
723 char_start = transcode_char_start(tc, *in_pos, inchar_start, in_p, &char_len);
724 writebuf_len = tr->func_sio(TRANSCODING_STATE(tc),
725 char_start, (size_t)char_len, next_info,
726 TRANSCODING_WRITEBUF(tc), TRANSCODING_WRITEBUF_SIZE(tc));
727 writebuf_off = 0;
728 while (writebuf_off < writebuf_len) {
729 SUSPEND_OBUF(34);
730 *out_p++ = TRANSCODING_WRITEBUF(tc)[writebuf_off++];
731 }
732 }
733 break;
734 }
735 case INVALID:
736 if (tc->recognized_len + (in_p - inchar_start) <= unitlen) {
737 if (tc->recognized_len + (in_p - inchar_start) < unitlen)
738 SUSPEND_AFTER_OUTPUT(26);
739 while ((opt & ECONV_PARTIAL_INPUT) && tc->recognized_len + (in_stop - inchar_start) < unitlen) {
740 in_p = in_stop;
741 SUSPEND(econv_source_buffer_empty, 8);
742 }
743 if (tc->recognized_len + (in_stop - inchar_start) <= unitlen) {
744 in_p = in_stop;
745 }
746 else {
747 in_p = inchar_start + (unitlen - tc->recognized_len);
748 }
749 }
750 else {
751 ssize_t invalid_len; /* including the last byte which causes invalid */
752 ssize_t discard_len;
753 invalid_len = tc->recognized_len + (in_p - inchar_start);
754 discard_len = ((invalid_len - 1) / unitlen) * unitlen;
755 readagain_len = invalid_len - discard_len;
756 }
757 goto invalid;
758 case UNDEF:
759 goto undef;
760 default:
761 rb_raise(rb_eRuntimeError, "unknown transcoding instruction");
762 }
763 continue;
764
765 invalid:
766 SUSPEND(econv_invalid_byte_sequence, 1);
767 continue;
768
769 incomplete:
770 SUSPEND(econv_incomplete_input, 27);
771 continue;
772
773 undef:
774 SUSPEND(econv_undefined_conversion, 2);
775 continue;
776 }
777
778 /* cleanup */
779 if (tr->finish_func) {
780 SUSPEND_OBUF(4);
781 if (tr->max_output <= out_stop - out_p) {
782 out_p += tr->finish_func(TRANSCODING_STATE(tc),
783 out_p, out_stop - out_p);
784 }
785 else {
786 writebuf_len = tr->finish_func(TRANSCODING_STATE(tc),
787 TRANSCODING_WRITEBUF(tc), TRANSCODING_WRITEBUF_SIZE(tc));
788 writebuf_off = 0;
789 while (writebuf_off < writebuf_len) {
790 SUSPEND_OBUF(23);
791 *out_p++ = TRANSCODING_WRITEBUF(tc)[writebuf_off++];
792 }
793 }
794 }
795 while (1)
796 SUSPEND(econv_finished, 6);
797#undef SUSPEND
798#undef next_table
799#undef next_info
800#undef next_byte
801#undef writebuf_len
802#undef writebuf_off
803}
804
806transcode_restartable(const unsigned char **in_pos, unsigned char **out_pos,
807 const unsigned char *in_stop, unsigned char *out_stop,
808 rb_transcoding *tc,
809 const int opt)
810{
811 if (tc->readagain_len) {
812 unsigned char *readagain_buf = ALLOCA_N(unsigned char, tc->readagain_len);
813 const unsigned char *readagain_pos = readagain_buf;
814 const unsigned char *readagain_stop = readagain_buf + tc->readagain_len;
816
817 MEMCPY(readagain_buf, TRANSCODING_READBUF(tc) + tc->recognized_len,
818 unsigned char, tc->readagain_len);
819 tc->readagain_len = 0;
820 res = transcode_restartable0(&readagain_pos, out_pos, readagain_stop, out_stop, tc, opt|ECONV_PARTIAL_INPUT);
821 if (res != econv_source_buffer_empty) {
822 MEMCPY(TRANSCODING_READBUF(tc) + tc->recognized_len + tc->readagain_len,
823 readagain_pos, unsigned char, readagain_stop - readagain_pos);
824 tc->readagain_len += readagain_stop - readagain_pos;
825 return res;
826 }
827 }
828 return transcode_restartable0(in_pos, out_pos, in_stop, out_stop, tc, opt);
829}
830
831static rb_transcoding *
832rb_transcoding_open_by_transcoder(const rb_transcoder *tr, int flags)
833{
834 rb_transcoding *tc;
835
836 tc = ALLOC(rb_transcoding);
837 tc->transcoder = tr;
838 tc->flags = flags;
839 if (TRANSCODING_STATE_EMBED_MAX < tr->state_size)
840 tc->state.ptr = xmalloc(tr->state_size);
841 if (tr->state_init_func) {
842 (tr->state_init_func)(TRANSCODING_STATE(tc)); /* xxx: check return value */
843 }
844 tc->resume_position = 0;
845 tc->recognized_len = 0;
846 tc->readagain_len = 0;
847 tc->writebuf_len = 0;
848 tc->writebuf_off = 0;
849 if ((int)sizeof(tc->readbuf.ary) < tr->max_input) {
850 tc->readbuf.ptr = xmalloc(tr->max_input);
851 }
852 if ((int)sizeof(tc->writebuf.ary) < tr->max_output) {
853 tc->writebuf.ptr = xmalloc(tr->max_output);
854 }
855 return tc;
856}
857
859rb_transcoding_convert(rb_transcoding *tc,
860 const unsigned char **input_ptr, const unsigned char *input_stop,
861 unsigned char **output_ptr, unsigned char *output_stop,
862 int flags)
863{
864 return transcode_restartable(
865 input_ptr, output_ptr,
866 input_stop, output_stop,
867 tc, flags);
868}
869
870static void
871rb_transcoding_close(rb_transcoding *tc)
872{
873 const rb_transcoder *tr = tc->transcoder;
874 if (tr->state_fini_func) {
875 (tr->state_fini_func)(TRANSCODING_STATE(tc)); /* check return value? */
876 }
877 if (TRANSCODING_STATE_EMBED_MAX < tr->state_size)
878 ruby_xfree_sized(tc->state.ptr, tr->state_size);
879 if ((int)sizeof(tc->readbuf.ary) < tr->max_input)
880 ruby_xfree_sized(tc->readbuf.ptr, tr->max_input);
881 if ((int)sizeof(tc->writebuf.ary) < tr->max_output)
882 ruby_xfree_sized(tc->writebuf.ptr, tr->max_output);
883 SIZED_FREE(tc);
884}
885
886static size_t
887rb_transcoding_memsize(rb_transcoding *tc)
888{
889 size_t size = sizeof(rb_transcoding);
890 const rb_transcoder *tr = tc->transcoder;
891
892 if (TRANSCODING_STATE_EMBED_MAX < tr->state_size) {
893 size += tr->state_size;
894 }
895 if ((int)sizeof(tc->readbuf.ary) < tr->max_input) {
896 size += tr->max_input;
897 }
898 if ((int)sizeof(tc->writebuf.ary) < tr->max_output) {
899 size += tr->max_output;
900 }
901 return size;
902}
903
904static rb_econv_t *
905rb_econv_alloc(int n_hint)
906{
907 rb_econv_t *ec;
908
909 if (n_hint <= 0)
910 n_hint = 1;
911
912 ec = ALLOC(rb_econv_t);
913 ec->flags = 0;
914 ec->source_encoding_name = NULL;
915 ec->destination_encoding_name = NULL;
916 ec->started = 0;
917 ec->replacement_str = NULL;
918 ec->replacement_len = 0;
919 ec->replacement_bufsize = 0;
920 ec->replacement_enc = NULL;
921 ec->replacement_allocated = 0;
922 ec->in_buf_start = NULL;
923 ec->in_data_start = NULL;
924 ec->in_data_end = NULL;
925 ec->in_buf_end = NULL;
926 ec->num_allocated = n_hint;
927 ec->num_trans = 0;
928 ec->elems = ALLOC_N(rb_econv_elem_t, ec->num_allocated);
929 ec->num_finished = 0;
930 ec->last_tc = NULL;
931 ec->last_error.result = econv_source_buffer_empty;
932 ec->last_error.error_tc = NULL;
933 ec->last_error.source_encoding = NULL;
934 ec->last_error.destination_encoding = NULL;
935 ec->last_error.error_bytes_start = NULL;
936 ec->last_error.error_bytes_len = 0;
937 ec->last_error.readagain_len = 0;
938 ec->source_encoding = NULL;
939 ec->destination_encoding = NULL;
940 return ec;
941}
942
943static int
944rb_econv_add_transcoder_at(rb_econv_t *ec, const rb_transcoder *tr, int i)
945{
946 int n, j;
947 int bufsize = 4096;
948 unsigned char *p;
949
950 if (ec->num_trans == ec->num_allocated) {
951 n = ec->num_allocated * 2;
952 SIZED_REALLOC_N(ec->elems, rb_econv_elem_t, n, ec->num_allocated);
953 ec->num_allocated = n;
954 }
955
956 p = xmalloc(bufsize);
957
958 MEMMOVE(ec->elems+i+1, ec->elems+i, rb_econv_elem_t, ec->num_trans-i);
959
960 ec->elems[i].tc = rb_transcoding_open_by_transcoder(tr, 0);
961 ec->elems[i].out_buf_start = p;
962 ec->elems[i].out_buf_end = p + bufsize;
963 ec->elems[i].out_data_start = p;
964 ec->elems[i].out_data_end = p;
965 ec->elems[i].last_result = econv_source_buffer_empty;
966
967 ec->num_trans++;
968
969 if (!DECORATOR_P(tr->src_encoding, tr->dst_encoding))
970 for (j = ec->num_trans-1; i <= j; j--) {
971 rb_transcoding *tc = ec->elems[j].tc;
972 const rb_transcoder *tr2 = tc->transcoder;
973 if (!DECORATOR_P(tr2->src_encoding, tr2->dst_encoding)) {
974 ec->last_tc = tc;
975 break;
976 }
977 }
978
979 return 0;
980}
981
982static rb_econv_t *
983rb_econv_open_by_transcoder_entries(int n, transcoder_entry_t **entries)
984{
985 rb_econv_t *ec;
986 int i, ret;
987
988 for (i = 0; i < n; i++) {
989 const rb_transcoder *tr;
990 tr = load_transcoder_entry(entries[i]);
991 if (!tr)
992 return NULL;
993 }
994
995 ec = rb_econv_alloc(n);
996
997 for (i = 0; i < n; i++) {
998 const rb_transcoder *tr = load_transcoder_entry(entries[i]);
999 ret = rb_econv_add_transcoder_at(ec, tr, ec->num_trans);
1000 if (ret == -1) {
1001 rb_econv_close(ec);
1002 return NULL;
1003 }
1004 }
1005
1006 return ec;
1007}
1008
1010 transcoder_entry_t **entries;
1011};
1012
1013static void
1014trans_open_i(const char *sname, const char *dname, int depth, void *arg)
1015{
1016 struct trans_open_t *toarg = arg;
1017
1018 if (!toarg->entries) {
1019 toarg->entries = ALLOC_N(transcoder_entry_t *, depth + 1);
1020 }
1021 toarg->entries[depth] = get_transcoder_entry(sname, dname);
1022}
1023
1024static rb_econv_t *
1025rb_econv_open0(const char *sname, const char *dname, int ecflags)
1026{
1027 transcoder_entry_t **entries = NULL;
1028 int num_trans;
1029 rb_econv_t *ec;
1030
1031 // loads encodings if not loaded already
1032 if (*sname) rb_enc_find_index(sname);
1033 if (*dname) rb_enc_find_index(dname);
1034
1035 if (*sname == '\0' && *dname == '\0') {
1036 num_trans = 0;
1037 entries = NULL;
1038 sname = dname = "";
1039 }
1040 else {
1041 struct trans_open_t toarg = {0};
1042 num_trans = transcode_search_path(sname, dname, trans_open_i, (void *)&toarg);
1043 entries = toarg.entries;
1044 if (num_trans < 0) {
1045 SIZED_FREE_N(entries, num_trans);
1046 return NULL;
1047 }
1048 sname = entries[0]->sname;
1049 dname = entries[num_trans-1]->dname;
1050 }
1051
1052 ec = rb_econv_open_by_transcoder_entries(num_trans, entries);
1053 SIZED_FREE_N(entries, num_trans);
1054 if (!ec)
1055 return NULL;
1056
1057 ec->flags = ecflags;
1058 ec->source_encoding_name = sname;
1059 ec->destination_encoding_name = dname;
1060
1061 return ec;
1062}
1063
1064#define MAX_ECFLAGS_DECORATORS 32
1065
1066static int
1067decorator_names(int ecflags, const char **decorators_ret)
1068{
1069 int num_decorators;
1070
1071 switch (ecflags & ECONV_NEWLINE_DECORATOR_MASK) {
1076 case 0:
1077 break;
1078 default:
1079 return -1;
1080 }
1081
1082 if ((ecflags & ECONV_XML_TEXT_DECORATOR) &&
1084 return -1;
1085
1086 num_decorators = 0;
1087
1088 if (ecflags & ECONV_XML_TEXT_DECORATOR)
1089 decorators_ret[num_decorators++] = "xml_text_escape";
1091 decorators_ret[num_decorators++] = "xml_attr_content_escape";
1092 if (ecflags & ECONV_XML_ATTR_QUOTE_DECORATOR)
1093 decorators_ret[num_decorators++] = "xml_attr_quote";
1094
1095 if (ecflags & ECONV_CRLF_NEWLINE_DECORATOR)
1096 decorators_ret[num_decorators++] = "crlf_newline";
1097 if (ecflags & ECONV_CR_NEWLINE_DECORATOR)
1098 decorators_ret[num_decorators++] = "cr_newline";
1099 if (ecflags & ECONV_LF_NEWLINE_DECORATOR)
1100 decorators_ret[num_decorators++] = "lf_newline";
1102 decorators_ret[num_decorators++] = "universal_newline";
1103
1104 return num_decorators;
1105}
1106
1107rb_econv_t *
1108rb_econv_open(const char *sname, const char *dname, int ecflags)
1109{
1110 rb_econv_t *ec;
1111 int num_decorators;
1112 const char *decorators[MAX_ECFLAGS_DECORATORS];
1113 int i;
1114
1115 num_decorators = decorator_names(ecflags, decorators);
1116 if (num_decorators == -1)
1117 return NULL;
1118
1119 ec = rb_econv_open0(sname, dname, ecflags & ECONV_ERROR_HANDLER_MASK);
1120 if (ec) {
1121 for (i = 0; i < num_decorators; i++) {
1122 if (rb_econv_decorate_at_last(ec, decorators[i]) == -1) {
1123 rb_econv_close(ec);
1124 ec = NULL;
1125 break;
1126 }
1127 }
1128 }
1129
1130 if (ec) {
1131 ec->flags |= ecflags & ~ECONV_ERROR_HANDLER_MASK;
1132 }
1133 return ec; // can be NULL
1134}
1135
1136static int
1137trans_sweep(rb_econv_t *ec,
1138 const unsigned char **input_ptr, const unsigned char *input_stop,
1139 unsigned char **output_ptr, unsigned char *output_stop,
1140 int flags,
1141 int start)
1142{
1143 int try;
1144 int i, f;
1145
1146 const unsigned char **ipp, *is, *iold;
1147 unsigned char **opp, *os, *oold;
1149
1150 try = 1;
1151 while (try) {
1152 try = 0;
1153 for (i = start; i < ec->num_trans; i++) {
1154 rb_econv_elem_t *te = &ec->elems[i];
1155
1156 if (i == 0) {
1157 ipp = input_ptr;
1158 is = input_stop;
1159 }
1160 else {
1161 rb_econv_elem_t *prev_te = &ec->elems[i-1];
1162 ipp = (const unsigned char **)&prev_te->out_data_start;
1163 is = prev_te->out_data_end;
1164 }
1165
1166 if (i == ec->num_trans-1) {
1167 opp = output_ptr;
1168 os = output_stop;
1169 }
1170 else {
1171 if (te->out_buf_start != te->out_data_start) {
1172 ssize_t len = te->out_data_end - te->out_data_start;
1173 ssize_t off = te->out_data_start - te->out_buf_start;
1174 MEMMOVE(te->out_buf_start, te->out_data_start, unsigned char, len);
1175 te->out_data_start = te->out_buf_start;
1176 te->out_data_end -= off;
1177 }
1178 opp = &te->out_data_end;
1179 os = te->out_buf_end;
1180 }
1181
1182 f = flags;
1183 if (ec->num_finished != i)
1185 if (i == 0 && (flags & ECONV_AFTER_OUTPUT)) {
1186 start = 1;
1187 flags &= ~ECONV_AFTER_OUTPUT;
1188 }
1189 if (i != 0)
1191 iold = *ipp;
1192 oold = *opp;
1193 te->last_result = res = rb_transcoding_convert(te->tc, ipp, is, opp, os, f);
1194 if (iold != *ipp || oold != *opp)
1195 try = 1;
1196
1197 switch (res) {
1201 case econv_after_output:
1202 return i;
1203
1206 break;
1207
1208 case econv_finished:
1209 ec->num_finished = i+1;
1210 break;
1211 }
1212 }
1213 }
1214 return -1;
1215}
1216
1217static rb_econv_result_t
1218rb_trans_conv(rb_econv_t *ec,
1219 const unsigned char **input_ptr, const unsigned char *input_stop,
1220 unsigned char **output_ptr, unsigned char *output_stop,
1221 int flags,
1222 int *result_position_ptr)
1223{
1224 int i;
1225 int needreport_index;
1226 int sweep_start;
1227
1228 unsigned char empty_buf;
1229 unsigned char *empty_ptr = &empty_buf;
1230
1231 if (!input_ptr) {
1232 input_ptr = (const unsigned char **)&empty_ptr;
1233 input_stop = empty_ptr;
1234 }
1235
1236 if (!output_ptr) {
1237 output_ptr = &empty_ptr;
1238 output_stop = empty_ptr;
1239 }
1240
1241 if (ec->elems[0].last_result == econv_after_output)
1242 ec->elems[0].last_result = econv_source_buffer_empty;
1243
1244 for (i = ec->num_trans-1; 0 <= i; i--) {
1245 switch (ec->elems[i].last_result) {
1249 case econv_after_output:
1250 case econv_finished:
1251 sweep_start = i+1;
1252 goto found_needreport;
1253
1256 break;
1257
1258 default:
1259 rb_bug("unexpected transcode last result");
1260 }
1261 }
1262
1263 /* /^[sd]+$/ is confirmed. but actually /^s*d*$/. */
1264
1265 if (ec->elems[ec->num_trans-1].last_result == econv_destination_buffer_full &&
1266 (flags & ECONV_AFTER_OUTPUT)) {
1268
1269 res = rb_trans_conv(ec, NULL, NULL, output_ptr, output_stop,
1271 result_position_ptr);
1272
1273 if (res == econv_source_buffer_empty)
1274 return econv_after_output;
1275 return res;
1276 }
1277
1278 sweep_start = 0;
1279
1280 found_needreport:
1281
1282 do {
1283 needreport_index = trans_sweep(ec, input_ptr, input_stop, output_ptr, output_stop, flags, sweep_start);
1284 sweep_start = needreport_index + 1;
1285 } while (needreport_index != -1 && needreport_index != ec->num_trans-1);
1286
1287 for (i = ec->num_trans-1; 0 <= i; i--) {
1288 if (ec->elems[i].last_result != econv_source_buffer_empty) {
1289 rb_econv_result_t res = ec->elems[i].last_result;
1290 if (res == econv_invalid_byte_sequence ||
1291 res == econv_incomplete_input ||
1293 res == econv_after_output) {
1294 ec->elems[i].last_result = econv_source_buffer_empty;
1295 }
1296 if (result_position_ptr)
1297 *result_position_ptr = i;
1298 return res;
1299 }
1300 }
1301 if (result_position_ptr)
1302 *result_position_ptr = -1;
1304}
1305
1306static rb_econv_result_t
1307rb_econv_convert0(rb_econv_t *ec,
1308 const unsigned char **input_ptr, const unsigned char *input_stop,
1309 unsigned char **output_ptr, unsigned char *output_stop,
1310 int flags)
1311{
1313 int result_position;
1314 int has_output = 0;
1315
1316 memset(&ec->last_error, 0, sizeof(ec->last_error));
1317
1318 if (ec->num_trans == 0) {
1319 size_t len;
1320 if (ec->in_buf_start && ec->in_data_start != ec->in_data_end) {
1321 if (output_stop - *output_ptr < ec->in_data_end - ec->in_data_start) {
1322 len = output_stop - *output_ptr;
1323 memcpy(*output_ptr, ec->in_data_start, len);
1324 *output_ptr = output_stop;
1325 ec->in_data_start += len;
1327 goto gotresult;
1328 }
1329 len = ec->in_data_end - ec->in_data_start;
1330 memcpy(*output_ptr, ec->in_data_start, len);
1331 *output_ptr += len;
1332 ec->in_data_start = ec->in_data_end = ec->in_buf_start;
1333 if (flags & ECONV_AFTER_OUTPUT) {
1334 res = econv_after_output;
1335 goto gotresult;
1336 }
1337 }
1338 if (output_stop - *output_ptr < input_stop - *input_ptr) {
1339 len = output_stop - *output_ptr;
1340 }
1341 else {
1342 len = input_stop - *input_ptr;
1343 }
1344 if (0 < len && (flags & ECONV_AFTER_OUTPUT)) {
1345 *(*output_ptr)++ = *(*input_ptr)++;
1346 res = econv_after_output;
1347 goto gotresult;
1348 }
1349 memcpy(*output_ptr, *input_ptr, len);
1350 *output_ptr += len;
1351 *input_ptr += len;
1352 if (*input_ptr != input_stop)
1354 else if (flags & ECONV_PARTIAL_INPUT)
1356 else
1357 res = econv_finished;
1358 goto gotresult;
1359 }
1360
1361 if (ec->elems[ec->num_trans-1].out_data_start) {
1362 unsigned char *data_start = ec->elems[ec->num_trans-1].out_data_start;
1363 unsigned char *data_end = ec->elems[ec->num_trans-1].out_data_end;
1364 if (data_start != data_end) {
1365 size_t len;
1366 if (output_stop - *output_ptr < data_end - data_start) {
1367 len = output_stop - *output_ptr;
1368 memcpy(*output_ptr, data_start, len);
1369 *output_ptr = output_stop;
1370 ec->elems[ec->num_trans-1].out_data_start += len;
1372 goto gotresult;
1373 }
1374 len = data_end - data_start;
1375 memcpy(*output_ptr, data_start, len);
1376 *output_ptr += len;
1377 ec->elems[ec->num_trans-1].out_data_start =
1378 ec->elems[ec->num_trans-1].out_data_end =
1379 ec->elems[ec->num_trans-1].out_buf_start;
1380 has_output = 1;
1381 }
1382 }
1383
1384 if (ec->in_buf_start &&
1385 ec->in_data_start != ec->in_data_end) {
1386 res = rb_trans_conv(ec, (const unsigned char **)&ec->in_data_start, ec->in_data_end, output_ptr, output_stop,
1387 (flags&~ECONV_AFTER_OUTPUT)|ECONV_PARTIAL_INPUT, &result_position);
1388 if (res != econv_source_buffer_empty)
1389 goto gotresult;
1390 }
1391
1392 if (has_output &&
1393 (flags & ECONV_AFTER_OUTPUT) &&
1394 *input_ptr != input_stop) {
1395 input_stop = *input_ptr;
1396 res = rb_trans_conv(ec, input_ptr, input_stop, output_ptr, output_stop, flags|ECONV_PARTIAL_INPUT, &result_position);
1397 if (res == econv_source_buffer_empty)
1398 res = econv_after_output;
1399 }
1400 else if ((flags & ECONV_AFTER_OUTPUT) ||
1401 ec->num_trans == 1) {
1402 res = rb_trans_conv(ec, input_ptr, input_stop, output_ptr, output_stop, flags, &result_position);
1403 }
1404 else {
1405 flags |= ECONV_AFTER_OUTPUT;
1406 do {
1407 res = rb_trans_conv(ec, input_ptr, input_stop, output_ptr, output_stop, flags, &result_position);
1408 } while (res == econv_after_output);
1409 }
1410
1411 gotresult:
1412 ec->last_error.result = res;
1413 if (res == econv_invalid_byte_sequence ||
1414 res == econv_incomplete_input ||
1416 rb_transcoding *error_tc = ec->elems[result_position].tc;
1417 ec->last_error.error_tc = error_tc;
1418 ec->last_error.source_encoding = error_tc->transcoder->src_encoding;
1419 ec->last_error.destination_encoding = error_tc->transcoder->dst_encoding;
1420 ec->last_error.error_bytes_start = TRANSCODING_READBUF(error_tc);
1421 ec->last_error.error_bytes_len = error_tc->recognized_len;
1422 ec->last_error.readagain_len = error_tc->readagain_len;
1423 }
1424
1425 return res;
1426}
1427
1428static int output_replacement_character(rb_econv_t *ec);
1429
1430static int
1431output_hex_charref(rb_econv_t *ec)
1432{
1433 int ret;
1434 unsigned char utfbuf[1024];
1435 const unsigned char *utf;
1436 size_t utf_len, utf_bufsize;
1437 int utf_allocated = 0;
1438 char charef_buf[16];
1439 const unsigned char *p;
1440
1441 if (encoding_equal(ec->last_error.source_encoding, "UTF-32BE")) {
1442 utf = ec->last_error.error_bytes_start;
1443 utf_len = ec->last_error.error_bytes_len;
1444 }
1445 else {
1446 utf = allocate_converted_string(ec->last_error.source_encoding, "UTF-32BE",
1447 ec->last_error.error_bytes_start, ec->last_error.error_bytes_len,
1448 utfbuf, sizeof(utfbuf),
1449 &utf_len, &utf_bufsize);
1450 if (!utf)
1451 return -1;
1452 if (utf != utfbuf && utf != ec->last_error.error_bytes_start)
1453 utf_allocated = 1;
1454 }
1455
1456 if (utf_len % 4 != 0)
1457 goto fail;
1458
1459 p = utf;
1460 while (4 <= utf_len) {
1461 unsigned int u = 0;
1462 u += p[0] << 24;
1463 u += p[1] << 16;
1464 u += p[2] << 8;
1465 u += p[3];
1466 snprintf(charef_buf, sizeof(charef_buf), "&#x%X;", u);
1467
1468 ret = rb_econv_insert_output(ec, (unsigned char *)charef_buf, strlen(charef_buf), "US-ASCII");
1469 if (ret == -1)
1470 goto fail;
1471
1472 p += 4;
1473 utf_len -= 4;
1474 }
1475
1476 if (utf_allocated)
1477 ruby_xfree_sized((void *)utf, utf_bufsize);
1478 return 0;
1479
1480 fail:
1481 if (utf_allocated)
1482 ruby_xfree_sized((void *)utf, utf_bufsize);
1483 return -1;
1484}
1485
1488 const unsigned char **input_ptr, const unsigned char *input_stop,
1489 unsigned char **output_ptr, unsigned char *output_stop,
1490 int flags)
1491{
1493
1494 unsigned char empty_buf;
1495 unsigned char *empty_ptr = &empty_buf;
1496
1497 ec->started = 1;
1498
1499 if (!input_ptr) {
1500 input_ptr = (const unsigned char **)&empty_ptr;
1501 input_stop = empty_ptr;
1502 }
1503
1504 if (!output_ptr) {
1505 output_ptr = &empty_ptr;
1506 output_stop = empty_ptr;
1507 }
1508
1509 resume:
1510 ret = rb_econv_convert0(ec, input_ptr, input_stop, output_ptr, output_stop, flags);
1511
1512 if (ret == econv_invalid_byte_sequence ||
1513 ret == econv_incomplete_input) {
1514 /* deal with invalid byte sequence */
1515 /* todo: add more alternative behaviors */
1516 switch (ec->flags & ECONV_INVALID_MASK) {
1518 if (output_replacement_character(ec) == 0)
1519 goto resume;
1520 }
1521 }
1522
1523 if (ret == econv_undefined_conversion) {
1524 /* valid character in source encoding
1525 * but no related character(s) in destination encoding */
1526 /* todo: add more alternative behaviors */
1527 switch (ec->flags & ECONV_UNDEF_MASK) {
1529 if (output_replacement_character(ec) == 0)
1530 goto resume;
1531 break;
1532
1534 if (output_hex_charref(ec) == 0)
1535 goto resume;
1536 break;
1537 }
1538 }
1539
1540 return ret;
1541}
1542
1543const char *
1545{
1546 rb_transcoding *tc = ec->last_tc;
1547 const rb_transcoder *tr;
1548
1549 if (tc == NULL)
1550 return "";
1551
1552 tr = tc->transcoder;
1553
1554 if (tr->asciicompat_type == asciicompat_encoder)
1555 return tr->src_encoding;
1556 return tr->dst_encoding;
1557}
1558
1559static unsigned char *
1560allocate_converted_string(const char *sname, const char *dname,
1561 const unsigned char *str, size_t len,
1562 unsigned char *caller_dst_buf, size_t caller_dst_bufsize,
1563 size_t *dst_len_ptr, size_t *dst_bufsize_ptr)
1564{
1565 unsigned char *dst_str;
1566 size_t dst_len;
1567 size_t dst_bufsize;
1568
1569 rb_econv_t *ec;
1571
1572 const unsigned char *sp;
1573 unsigned char *dp;
1574
1575 if (caller_dst_buf)
1576 dst_bufsize = caller_dst_bufsize;
1577 else if (len == 0)
1578 dst_bufsize = 1;
1579 else
1580 dst_bufsize = len;
1581
1582 ec = rb_econv_open(sname, dname, 0);
1583 if (ec == NULL)
1584 return NULL;
1585 if (caller_dst_buf)
1586 dst_str = caller_dst_buf;
1587 else
1588 dst_str = xmalloc(dst_bufsize);
1589 dst_len = 0;
1590 sp = str;
1591 dp = dst_str+dst_len;
1592 res = rb_econv_convert(ec, &sp, str+len, &dp, dst_str+dst_bufsize, 0);
1593 dst_len = dp - dst_str;
1594 while (res == econv_destination_buffer_full) {
1595 if (SIZE_MAX/2 < dst_bufsize) {
1596 goto fail;
1597 }
1598 dst_bufsize *= 2;
1599 if (dst_str == caller_dst_buf) {
1600 unsigned char *tmp;
1601 tmp = xmalloc(dst_bufsize);
1602 memcpy(tmp, dst_str, dst_bufsize/2);
1603 dst_str = tmp;
1604 }
1605 else {
1606 dst_str = ruby_xrealloc_sized(dst_str, dst_bufsize, dst_bufsize / 2);
1607 }
1608 dp = dst_str+dst_len;
1609 res = rb_econv_convert(ec, &sp, str+len, &dp, dst_str+dst_bufsize, 0);
1610 dst_len = dp - dst_str;
1611 }
1612 if (res != econv_finished) {
1613 goto fail;
1614 }
1615 rb_econv_close(ec);
1616 *dst_len_ptr = dst_len;
1617 *dst_bufsize_ptr = dst_bufsize;
1618 return dst_str;
1619
1620 fail:
1621 if (dst_str != caller_dst_buf)
1622 ruby_xfree_sized(dst_str, dst_bufsize);
1623 rb_econv_close(ec);
1624 return NULL;
1625}
1626
1627/* Inserts ptr[0, len] at start, before the data in [start, *end_p). */
1628static void
1629insert_before(unsigned char *start, unsigned char **end_p, const unsigned char *ptr, size_t len)
1630{
1631 MEMMOVE(start + len, start, unsigned char, *end_p - start);
1632 memcpy(start, ptr, len);
1633 *end_p += len;
1634}
1635
1636/* result: 0:success -1:failure */
1637int
1639 const unsigned char *str, size_t len, const char *str_encoding)
1640{
1641 const char *insert_encoding = rb_econv_encoding_to_insert_output(ec);
1642 unsigned char insert_buf[4096];
1643 const unsigned char *insert_str = NULL;
1644 size_t insert_len, insert_bufsize;
1645
1646 int last_trans_index;
1647 rb_transcoding *tc;
1648
1649 unsigned char **buf_start_p;
1650 unsigned char **data_start_p;
1651 unsigned char **data_end_p;
1652 unsigned char **buf_end_p;
1653
1654 size_t need;
1655
1656 ec->started = 1;
1657
1658 if (len == 0)
1659 return 0;
1660
1661 if (encoding_equal(insert_encoding, str_encoding)) {
1662 insert_str = str;
1663 insert_len = len;
1664 }
1665 else {
1666 insert_str = allocate_converted_string(str_encoding, insert_encoding,
1667 str, len, insert_buf, sizeof(insert_buf), &insert_len, &insert_bufsize);
1668 if (insert_str == NULL)
1669 return -1;
1670 }
1671
1672 need = insert_len;
1673
1674 last_trans_index = ec->num_trans-1;
1675 if (ec->num_trans == 0) {
1676 tc = NULL;
1677 buf_start_p = &ec->in_buf_start;
1678 data_start_p = &ec->in_data_start;
1679 data_end_p = &ec->in_data_end;
1680 buf_end_p = &ec->in_buf_end;
1681 }
1682 else if (ec->elems[last_trans_index].tc->transcoder->asciicompat_type == asciicompat_encoder) {
1683 tc = ec->elems[last_trans_index].tc;
1684 need += tc->readagain_len;
1685 if (need < insert_len)
1686 goto fail;
1687 if (last_trans_index == 0) {
1688 buf_start_p = &ec->in_buf_start;
1689 data_start_p = &ec->in_data_start;
1690 data_end_p = &ec->in_data_end;
1691 buf_end_p = &ec->in_buf_end;
1692 }
1693 else {
1694 rb_econv_elem_t *ee = &ec->elems[last_trans_index-1];
1695 buf_start_p = &ee->out_buf_start;
1696 data_start_p = &ee->out_data_start;
1697 data_end_p = &ee->out_data_end;
1698 buf_end_p = &ee->out_buf_end;
1699 }
1700 }
1701 else {
1702 rb_econv_elem_t *ee = &ec->elems[last_trans_index];
1703 buf_start_p = &ee->out_buf_start;
1704 data_start_p = &ee->out_data_start;
1705 data_end_p = &ee->out_data_end;
1706 buf_end_p = &ee->out_buf_end;
1707 tc = ec->elems[last_trans_index].tc;
1708 }
1709
1710 if (*buf_start_p == NULL) {
1711 unsigned char *buf = xmalloc(need);
1712 *buf_start_p = buf;
1713 *data_start_p = buf;
1714 *data_end_p = buf;
1715 *buf_end_p = buf+need;
1716 }
1717 else if ((size_t)(*buf_end_p - *data_end_p) < need) {
1718 MEMMOVE(*buf_start_p, *data_start_p, unsigned char, *data_end_p - *data_start_p);
1719 *data_end_p = *buf_start_p + (*data_end_p - *data_start_p);
1720 *data_start_p = *buf_start_p;
1721 if ((size_t)(*buf_end_p - *data_end_p) < need) {
1722 unsigned char *buf;
1723 size_t s = (*data_end_p - *buf_start_p) + need;
1724 if (s < need)
1725 goto fail;
1726 buf = ruby_xrealloc_sized(*buf_start_p, s, *buf_end_p - *buf_start_p);
1727 *data_start_p = buf;
1728 *data_end_p = buf + (*data_end_p - *buf_start_p);
1729 *buf_start_p = buf;
1730 *buf_end_p = buf + s;
1731 }
1732 }
1733
1734 if (tc && tc->transcoder->asciicompat_type == asciicompat_encoder) {
1735 /*
1736 * The last transcoder encodes into an ASCII-incompatible encoding,
1737 * so str goes to its input instead of the output of the converter.
1738 * The input still in the buffer comes after the bytes that caused
1739 * this insertion, so put str and the bytes that the transcoder
1740 * reads again before it, not after.
1741 */
1742 insert_before(*data_start_p, data_end_p, TRANSCODING_READBUF(tc)+tc->recognized_len, tc->readagain_len);
1743 insert_before(*data_start_p, data_end_p, insert_str, insert_len);
1744 tc->readagain_len = 0;
1745 }
1746 else {
1747 memcpy(*data_end_p, insert_str, insert_len);
1748 *data_end_p += insert_len;
1749 }
1750
1751 if (insert_str != str && insert_str != insert_buf)
1752 ruby_xfree_sized((void *)insert_str, insert_bufsize);
1753 return 0;
1754
1755 fail:
1756 if (insert_str != str && insert_str != insert_buf)
1757 ruby_xfree_sized((void *)insert_str, insert_bufsize);
1758 return -1;
1759}
1760
1761void
1763{
1764 int i;
1765
1766 if (ec->replacement_allocated) {
1767 SIZED_FREE_N((char *)ec->replacement_str, ec->replacement_bufsize);
1768 }
1769 for (i = 0; i < ec->num_trans; i++) {
1770 rb_transcoding_close(ec->elems[i].tc);
1771 ruby_xfree_sized(ec->elems[i].out_buf_start, ec->elems[i].out_buf_end - ec->elems[i].out_buf_start);
1772 }
1773 SIZED_FREE_N(ec->in_buf_start, ec->in_buf_end - ec->in_buf_start);
1774 SIZED_FREE_N(ec->elems, ec->num_allocated);
1775 SIZED_FREE(ec);
1776}
1777
1778size_t
1779rb_econv_memsize(rb_econv_t *ec)
1780{
1781 size_t size = sizeof(rb_econv_t);
1782 int i;
1783
1784 if (ec->replacement_allocated) {
1785 size += ec->replacement_len;
1786 }
1787 for (i = 0; i < ec->num_trans; i++) {
1788 size += rb_transcoding_memsize(ec->elems[i].tc);
1789
1790 if (ec->elems[i].out_buf_start) {
1791 size += ec->elems[i].out_buf_end - ec->elems[i].out_buf_start;
1792 }
1793 }
1794 size += ec->in_buf_end - ec->in_buf_start;
1795 size += sizeof(rb_econv_elem_t) * ec->num_allocated;
1796
1797 return size;
1798}
1799
1800int
1802{
1803 if (ec->num_trans == 0)
1804 return 0;
1805#if SIZEOF_SIZE_T > SIZEOF_INT
1806 if (ec->elems[0].tc->readagain_len > INT_MAX) return INT_MAX;
1807#endif
1808 return (int)ec->elems[0].tc->readagain_len;
1809}
1810
1811void
1812rb_econv_putback(rb_econv_t *ec, unsigned char *p, int n)
1813{
1814 rb_transcoding *tc;
1815 if (ec->num_trans == 0 || n == 0)
1816 return;
1817 tc = ec->elems[0].tc;
1818 memcpy(p, TRANSCODING_READBUF(tc) + tc->recognized_len + tc->readagain_len - n, n);
1819 tc->readagain_len -= n;
1820}
1821
1823 const char *ascii_compat_name;
1824 const char *ascii_incompat_name;
1825};
1826
1827static int
1828asciicompat_encoding_i(st_data_t key, st_data_t val, st_data_t arg)
1829{
1830 struct asciicompat_encoding_t *data = (struct asciicompat_encoding_t *)arg;
1831 transcoder_entry_t *entry = (transcoder_entry_t *)val;
1832 const rb_transcoder *tr;
1833
1834 if (DECORATOR_P(entry->sname, entry->dname))
1835 return ST_CONTINUE;
1836 tr = load_transcoder_entry(entry);
1837 if (tr && tr->asciicompat_type == asciicompat_decoder) {
1838 data->ascii_compat_name = tr->dst_encoding;
1839 return ST_STOP;
1840 }
1841 return ST_CONTINUE;
1842}
1843
1844const char *
1845rb_econv_asciicompat_encoding(const char *ascii_incompat_name)
1846{
1847 st_data_t v;
1848 st_table *table2;
1849 struct asciicompat_encoding_t data = {0};
1850
1851 unsigned int lev;
1852 RB_VM_LOCK_ENTER_LEV(&lev);
1853 {
1854 if (st_lookup(transcoder_table, (st_data_t)ascii_incompat_name, &v)) {
1855 table2 = (st_table *)v;
1856 /*
1857 * Assumption:
1858 * There is at most one transcoder for
1859 * converting from ASCII incompatible encoding.
1860 *
1861 * For ISO-2022-JP, there is ISO-2022-JP -> stateless-ISO-2022-JP and no others.
1862 */
1863 if (table2->num_entries == 1) {
1864 data.ascii_incompat_name = ascii_incompat_name;
1865 data.ascii_compat_name = NULL;
1866 if (rb_multi_ractor_p()) {
1867 /*
1868 * We need to unlock in case `load_transcoder_entry` actually loads the encoding
1869 * and table2 could be inserted into when we unlock.
1870 */
1871 st_table *dup_table2 = st_copy(table2);
1872 RB_VM_LOCK_LEAVE_LEV(&lev);
1873 st_foreach(dup_table2, asciicompat_encoding_i, (st_data_t)&data);
1874 st_free_table(dup_table2);
1875 RB_VM_LOCK_ENTER_LEV(&lev);
1876 }
1877 else {
1878 st_foreach(table2, asciicompat_encoding_i, (st_data_t)&data);
1879 }
1880 }
1881
1882 }
1883 }
1884 RB_VM_LOCK_LEAVE_LEV(&lev);
1885
1886 return data.ascii_compat_name; // can be NULL
1887}
1888
1889/*
1890 * Append `len` bytes pointed by `ss` to `dst` with converting with `ec`.
1891 *
1892 * If the result of the conversion is not compatible with the encoding of
1893 * `dst`, `dst` may not be valid encoding.
1894 */
1895VALUE
1896rb_econv_append(rb_econv_t *ec, const char *ss, rb_len_t len, VALUE dst, int flags)
1897{
1898 unsigned const char *sp, *se;
1899 unsigned char *ds, *dp, *de;
1901 int max_output;
1902 enum ruby_coderange_type coderange;
1903 rb_encoding *dst_enc = ec->destination_encoding;
1904
1905 if (NIL_P(dst)) {
1906 dst = rb_str_buf_new(len);
1907 if (dst_enc) {
1908 rb_enc_associate(dst, dst_enc);
1909 }
1910 coderange = ENC_CODERANGE_7BIT; // scan from the start
1911 }
1912 else {
1913 dst_enc = rb_enc_get(dst);
1914 coderange = rb_enc_str_coderange(dst);
1915 }
1916
1917 if (ec->last_tc)
1918 max_output = ec->last_tc->transcoder->max_output;
1919 else
1920 max_output = 1;
1921
1922 do {
1923 int cr;
1924 rb_len_t dlen = RSTRING_LEN(dst);
1925 if (rb_str_capacity(dst) - dlen < (size_t)len + max_output) {
1926 rb_ulen_t new_capa = (rb_ulen_t)dlen + len + max_output;
1927 if (RB_LEN_MAX < new_capa)
1928 rb_raise(rb_eArgError, "too long string");
1929 rb_str_modify_expand(dst, new_capa - dlen);
1930 }
1931 sp = (const unsigned char *)ss;
1932 se = sp + len;
1933 ds = (unsigned char *)RSTRING_PTR(dst);
1934 de = ds + rb_str_capacity(dst);
1935 dp = ds += dlen;
1936 res = rb_econv_convert(ec, &sp, se, &dp, de, flags);
1937 switch (coderange) {
1938 case ENC_CODERANGE_7BIT:
1940 cr = (int)coderange;
1941 rb_str_coderange_scan_restartable((char *)ds, (char *)dp, dst_enc, &cr);
1942 coderange = cr;
1943 ENC_CODERANGE_SET(dst, coderange);
1944 break;
1947 break;
1948 }
1949 len -= (const char *)sp - ss;
1950 ss = (const char *)sp;
1951 rb_str_set_len(dst, dlen + (dp - ds));
1953 } while (res == econv_destination_buffer_full);
1954
1955 return dst;
1956}
1957
1958VALUE
1960{
1961 src = rb_str_new_frozen(src);
1962 dst = rb_econv_append(ec, RSTRING_PTR(src) + off, len, dst, flags);
1963 RB_GC_GUARD(src);
1964 return dst;
1965}
1966
1967VALUE
1969{
1970 return rb_econv_substr_append(ec, src, 0, RSTRING_LEN(src), dst, flags);
1971}
1972
1973VALUE
1974rb_econv_substr_convert(rb_econv_t *ec, VALUE src, rb_len_t byteoff, rb_len_t bytesize, int flags)
1975{
1976 return rb_econv_substr_append(ec, src, byteoff, bytesize, Qnil, flags);
1977}
1978
1979VALUE
1981{
1982 return rb_econv_substr_append(ec, src, 0, RSTRING_LEN(src), Qnil, flags);
1983}
1984
1985static int
1986rb_econv_add_converter(rb_econv_t *ec, const char *sname, const char *dname, int n)
1987{
1988 transcoder_entry_t *entry;
1989 const rb_transcoder *tr = NULL;
1990
1991 if (ec->started != 0)
1992 return -1;
1993
1994 entry = get_transcoder_entry(sname, dname);
1995 if (entry) {
1996 tr = load_transcoder_entry(entry);
1997 }
1998
1999 return tr ? rb_econv_add_transcoder_at(ec, tr, n) : -1;
2000}
2001
2002static int
2003rb_econv_decorate_at(rb_econv_t *ec, const char *decorator_name, int n)
2004{
2005 return rb_econv_add_converter(ec, "", decorator_name, n);
2006}
2007
2008int
2009rb_econv_decorate_at_first(rb_econv_t *ec, const char *decorator_name)
2010{
2011 const rb_transcoder *tr;
2012
2013 if (ec->num_trans == 0)
2014 return rb_econv_decorate_at(ec, decorator_name, 0);
2015
2016 tr = ec->elems[0].tc->transcoder;
2017
2018 if (!DECORATOR_P(tr->src_encoding, tr->dst_encoding) &&
2019 tr->asciicompat_type == asciicompat_decoder)
2020 return rb_econv_decorate_at(ec, decorator_name, 1);
2021
2022 return rb_econv_decorate_at(ec, decorator_name, 0);
2023}
2024
2025int
2026rb_econv_decorate_at_last(rb_econv_t *ec, const char *decorator_name)
2027{
2028 const rb_transcoder *tr;
2029
2030 if (ec->num_trans == 0)
2031 return rb_econv_decorate_at(ec, decorator_name, 0);
2032
2033 tr = ec->elems[ec->num_trans-1].tc->transcoder;
2034
2035 if (!DECORATOR_P(tr->src_encoding, tr->dst_encoding) &&
2036 tr->asciicompat_type == asciicompat_encoder)
2037 return rb_econv_decorate_at(ec, decorator_name, ec->num_trans-1);
2038
2039 return rb_econv_decorate_at(ec, decorator_name, ec->num_trans);
2040}
2041
2042void
2044{
2045 const char *dname = 0;
2046
2047 switch (ec->flags & ECONV_NEWLINE_DECORATOR_MASK) {
2049 dname = "universal_newline";
2050 break;
2052 dname = "crlf_newline";
2053 break;
2055 dname = "cr_newline";
2056 break;
2058 dname = "lf_newline";
2059 break;
2060 }
2061
2062 if (dname) {
2063 const rb_transcoder *transcoder = get_transcoder_entry("", dname)->transcoder;
2064 int num_trans = ec->num_trans;
2065 int i, j = 0;
2066
2067 for (i=0; i < num_trans; i++) {
2068 if (transcoder == ec->elems[i].tc->transcoder) {
2069 rb_transcoding_close(ec->elems[i].tc);
2070 ruby_xfree_sized(ec->elems[i].out_buf_start, ec->elems[i].out_buf_end - ec->elems[i].out_buf_start);
2071 ec->num_trans--;
2072 }
2073 else
2074 ec->elems[j++] = ec->elems[i];
2075 }
2076 }
2077
2078 ec->flags &= ~ECONV_NEWLINE_DECORATOR_MASK;
2079}
2080
2081static VALUE
2082econv_description(const char *sname, const char *dname, int ecflags, VALUE mesg)
2083{
2084 int has_description = 0;
2085
2086 if (NIL_P(mesg))
2087 mesg = rb_str_new(NULL, 0);
2088
2089 if (*sname != '\0' || *dname != '\0') {
2090 if (*sname == '\0')
2091 rb_str_cat2(mesg, dname);
2092 else if (*dname == '\0')
2093 rb_str_cat2(mesg, sname);
2094 else
2095 rb_str_catf(mesg, "%s to %s", sname, dname);
2096 has_description = 1;
2097 }
2098
2099 if (ecflags & (ECONV_NEWLINE_DECORATOR_MASK|
2103 const char *pre = "";
2104 if (has_description)
2105 rb_str_cat2(mesg, " with ");
2106 if (ecflags & ECONV_UNIVERSAL_NEWLINE_DECORATOR) {
2107 rb_str_cat2(mesg, pre); pre = ",";
2108 rb_str_cat2(mesg, "universal_newline");
2109 }
2110 if (ecflags & ECONV_CRLF_NEWLINE_DECORATOR) {
2111 rb_str_cat2(mesg, pre); pre = ",";
2112 rb_str_cat2(mesg, "crlf_newline");
2113 }
2114 if (ecflags & ECONV_CR_NEWLINE_DECORATOR) {
2115 rb_str_cat2(mesg, pre); pre = ",";
2116 rb_str_cat2(mesg, "cr_newline");
2117 }
2118 if (ecflags & ECONV_LF_NEWLINE_DECORATOR) {
2119 rb_str_cat2(mesg, pre); pre = ",";
2120 rb_str_cat2(mesg, "lf_newline");
2121 }
2122 if (ecflags & ECONV_XML_TEXT_DECORATOR) {
2123 rb_str_cat2(mesg, pre); pre = ",";
2124 rb_str_cat2(mesg, "xml_text");
2125 }
2126 if (ecflags & ECONV_XML_ATTR_CONTENT_DECORATOR) {
2127 rb_str_cat2(mesg, pre); pre = ",";
2128 rb_str_cat2(mesg, "xml_attr_content");
2129 }
2130 if (ecflags & ECONV_XML_ATTR_QUOTE_DECORATOR) {
2131 rb_str_cat2(mesg, pre); pre = ",";
2132 rb_str_cat2(mesg, "xml_attr_quote");
2133 }
2134 has_description = 1;
2135 }
2136 if (!has_description) {
2137 rb_str_cat2(mesg, "no-conversion");
2138 }
2139
2140 return mesg;
2141}
2142
2143VALUE
2144rb_econv_open_exc(const char *sname, const char *dname, int ecflags)
2145{
2146 VALUE mesg, exc;
2147 mesg = rb_str_new_cstr("code converter not found (");
2148 econv_description(sname, dname, ecflags, mesg);
2149 rb_str_cat2(mesg, ")");
2150 exc = rb_exc_new3(rb_eConverterNotFoundError, mesg);
2151 return exc;
2152}
2153
2154static VALUE
2155make_econv_exception(rb_econv_t *ec)
2156{
2157 VALUE mesg, exc;
2158 if (ec->last_error.result == econv_invalid_byte_sequence ||
2159 ec->last_error.result == econv_incomplete_input) {
2160 const char *err = (const char *)ec->last_error.error_bytes_start;
2161 size_t error_len = ec->last_error.error_bytes_len;
2162 VALUE bytes = rb_str_new(err, error_len);
2163 VALUE dumped = rb_str_dump(bytes);
2164 size_t readagain_len = ec->last_error.readagain_len;
2165 VALUE bytes2 = Qnil;
2166 VALUE dumped2;
2167 if (ec->last_error.result == econv_incomplete_input) {
2168 mesg = rb_sprintf("incomplete %s on %s",
2169 StringValueCStr(dumped),
2170 ec->last_error.source_encoding);
2171 }
2172 else if (readagain_len) {
2173 bytes2 = rb_str_new(err+error_len, readagain_len);
2174 dumped2 = rb_str_dump(bytes2);
2175 mesg = rb_sprintf("%s followed by %s on %s",
2176 StringValueCStr(dumped),
2177 StringValueCStr(dumped2),
2178 ec->last_error.source_encoding);
2179 }
2180 else {
2181 mesg = rb_sprintf("%s on %s",
2182 StringValueCStr(dumped),
2183 ec->last_error.source_encoding);
2184 }
2185
2186 exc = rb_exc_new3(rb_eInvalidByteSequenceError, mesg);
2187 rb_ivar_set(exc, id_error_bytes, bytes);
2188 rb_ivar_set(exc, id_readagain_bytes, bytes2);
2189 rb_ivar_set(exc, id_incomplete_input, RBOOL(ec->last_error.result == econv_incomplete_input));
2190 goto set_encs;
2191 }
2192 if (ec->last_error.result == econv_undefined_conversion) {
2193 VALUE bytes = rb_str_new((const char *)ec->last_error.error_bytes_start,
2194 ec->last_error.error_bytes_len);
2195 VALUE dumped = Qnil;
2196 int idx;
2197 if (strcmp(ec->last_error.source_encoding, "UTF-8") == 0) {
2198 rb_encoding *utf8 = rb_utf8_encoding();
2199 const char *start, *end;
2200 int n;
2201 start = (const char *)ec->last_error.error_bytes_start;
2202 end = start + ec->last_error.error_bytes_len;
2203 n = rb_enc_precise_mbclen(start, end, utf8);
2204 if (MBCLEN_CHARFOUND_P(n) &&
2205 (size_t)MBCLEN_CHARFOUND_LEN(n) == ec->last_error.error_bytes_len) {
2206 unsigned int cc = rb_enc_mbc_to_codepoint(start, end, utf8);
2207 dumped = rb_sprintf("U+%04X", cc);
2208 }
2209 }
2210 if (NIL_P(dumped))
2211 dumped = rb_str_dump(bytes);
2212 if (strcmp(ec->last_error.source_encoding,
2213 ec->source_encoding_name) == 0 &&
2214 strcmp(ec->last_error.destination_encoding,
2215 ec->destination_encoding_name) == 0) {
2216 mesg = rb_sprintf("%s from %s to %s",
2217 StringValueCStr(dumped),
2218 ec->last_error.source_encoding,
2219 ec->last_error.destination_encoding);
2220 }
2221 else {
2222 int i;
2223 mesg = rb_sprintf("%s to %s in conversion from %s",
2224 StringValueCStr(dumped),
2225 ec->last_error.destination_encoding,
2226 ec->source_encoding_name);
2227 for (i = 0; i < ec->num_trans; i++) {
2228 const rb_transcoder *tr = ec->elems[i].tc->transcoder;
2229 if (!DECORATOR_P(tr->src_encoding, tr->dst_encoding))
2230 rb_str_catf(mesg, " to %s",
2231 ec->elems[i].tc->transcoder->dst_encoding);
2232 }
2233 }
2234 exc = rb_exc_new3(rb_eUndefinedConversionError, mesg);
2235 idx = rb_enc_find_index(ec->last_error.source_encoding);
2236 if (0 <= idx)
2237 rb_enc_associate_index(bytes, idx);
2238 rb_ivar_set(exc, id_error_char, bytes);
2239 goto set_encs;
2240 }
2241 return Qnil;
2242
2243 set_encs:
2244 rb_ivar_set(exc, id_source_encoding_name, rb_str_new2(ec->last_error.source_encoding));
2245 rb_ivar_set(exc, id_destination_encoding_name, rb_str_new2(ec->last_error.destination_encoding));
2246 int idx = rb_enc_find_index(ec->last_error.source_encoding);
2247 if (0 <= idx)
2248 rb_ivar_set(exc, id_source_encoding, rb_enc_from_encoding(rb_enc_from_index(idx)));
2249 idx = rb_enc_find_index(ec->last_error.destination_encoding);
2250 if (0 <= idx)
2251 rb_ivar_set(exc, id_destination_encoding, rb_enc_from_encoding(rb_enc_from_index(idx)));
2252 return exc;
2253}
2254
2255static void
2256more_output_buffer(
2257 VALUE destination,
2258 unsigned char *(*resize_destination)(VALUE, size_t, size_t),
2259 int max_output,
2260 unsigned char **out_start_ptr,
2261 unsigned char **out_pos,
2262 unsigned char **out_stop_ptr)
2263{
2264 size_t len = (*out_pos - *out_start_ptr);
2265 if (len > (size_t)(RB_LEN_MAX / 2 - max_output))
2266 rb_raise(rb_eArgError, "string size too big");
2267 size_t new_len = (len + max_output) * 2;
2268 *out_start_ptr = resize_destination(destination, len, new_len);
2269 *out_pos = *out_start_ptr + len;
2270 *out_stop_ptr = *out_start_ptr + new_len;
2271}
2272
2273static int
2274make_replacement(rb_econv_t *ec)
2275{
2276 rb_transcoding *tc;
2277 const rb_transcoder *tr;
2278 const unsigned char *replacement;
2279 const char *repl_enc;
2280 const char *ins_enc;
2281 size_t len;
2282
2283 if (ec->replacement_str)
2284 return 0;
2285
2287
2288 tc = ec->last_tc;
2289 if (*ins_enc) {
2290 tr = tc->transcoder;
2291 rb_enc_find(tr->dst_encoding);
2292 replacement = (const unsigned char *)get_replacement_character(ins_enc, &len, &repl_enc);
2293 }
2294 else {
2295 replacement = (unsigned char *)"?";
2296 len = 1;
2297 repl_enc = "";
2298 }
2299
2300 ec->replacement_str = replacement;
2301 ec->replacement_len = len;
2302 ec->replacement_bufsize = len;
2303 ec->replacement_enc = repl_enc;
2304 ec->replacement_allocated = 0;
2305 return 0;
2306}
2307
2308int
2310 const unsigned char *str, size_t len, const char *encname)
2311{
2312 unsigned char *str2;
2313 size_t len2, buf_size2;
2314 const char *encname2;
2315
2317
2318 if (!*encname2 || encoding_equal(encname, encname2)) {
2319 str2 = xmalloc(len);
2320 MEMCPY(str2, str, unsigned char, len); /* xxx: str may be invalid */
2321 buf_size2 = len2 = len;
2322 encname2 = encname;
2323 }
2324 else {
2325 str2 = allocate_converted_string(encname, encname2, str, len, NULL, 0, &len2, &buf_size2);
2326 if (!str2)
2327 return -1;
2328 }
2329
2330 if (ec->replacement_allocated) {
2331 SIZED_FREE_N((char *)ec->replacement_str, ec->replacement_bufsize);
2332 }
2333 ec->replacement_allocated = 1;
2334 ec->replacement_str = str2;
2335 ec->replacement_len = len2;
2336 ec->replacement_bufsize = buf_size2;
2337 ec->replacement_enc = encname2;
2338 return 0;
2339}
2340
2341static int
2342output_replacement_character(rb_econv_t *ec)
2343{
2344 int ret;
2345
2346 if (make_replacement(ec) == -1)
2347 return -1;
2348
2349 ret = rb_econv_insert_output(ec, ec->replacement_str, ec->replacement_len, ec->replacement_enc);
2350 if (ret == -1)
2351 return -1;
2352
2353 return 0;
2354}
2355
2356#if 1
2357#define hash_fallback rb_hash_aref
2358
2359static VALUE
2360proc_fallback(VALUE fallback, VALUE c)
2361{
2362 return rb_proc_call(fallback, rb_ary_new4(1, &c));
2363}
2364
2365static VALUE
2366method_fallback(VALUE fallback, VALUE c)
2367{
2368 return rb_method_call(1, &c, fallback);
2369}
2370
2371static VALUE
2372aref_fallback(VALUE fallback, VALUE c)
2373{
2374 return rb_funcallv_public(fallback, idAREF, 1, &c);
2375}
2376
2378 VALUE (*fallback_func)(VALUE, VALUE);
2379 VALUE fallback;
2380 VALUE rep;
2381};
2382
2383static VALUE
2384transcode_loop_fallback_try(VALUE a)
2385{
2387
2388 VALUE ret = args->fallback_func(args->fallback, args->rep);
2389
2390 if (!NIL_OR_UNDEF_P(ret)) {
2391 StringValue(ret);
2392 }
2393
2394 return ret;
2395}
2396
2397static void
2398transcode_loop(const unsigned char **in_pos, unsigned char **out_pos,
2399 const unsigned char *in_stop, unsigned char *out_stop,
2400 VALUE destination,
2401 unsigned char *(*resize_destination)(VALUE, size_t, size_t),
2402 const char *src_encoding,
2403 const char *dst_encoding,
2404 int ecflags,
2405 VALUE ecopts,
2406 VALUE source)
2407{
2408 rb_econv_t *ec;
2409 rb_transcoding *last_tc;
2411 unsigned char *out_start = *out_pos;
2412 int max_output;
2413 VALUE exc;
2414 VALUE fallback = Qnil;
2415 VALUE (*fallback_func)(VALUE, VALUE) = 0;
2416 const unsigned char *source_start = *in_pos;
2417 rb_len_t source_len = in_stop - *in_pos;
2418
2419 ec = rb_econv_open_opts(src_encoding, dst_encoding, ecflags, ecopts);
2420 if (!ec)
2421 rb_exc_raise(rb_econv_open_exc(src_encoding, dst_encoding, ecflags));
2422
2423 if (!NIL_P(ecopts) && RB_TYPE_P(ecopts, T_HASH)) {
2424 fallback = rb_hash_aref(ecopts, sym_fallback);
2425 if (RB_TYPE_P(fallback, T_HASH)) {
2426 fallback_func = hash_fallback;
2427 }
2428 else if (rb_obj_is_proc(fallback)) {
2429 fallback_func = proc_fallback;
2430 }
2431 else if (rb_obj_is_method(fallback)) {
2432 fallback_func = method_fallback;
2433 }
2434 else {
2435 fallback_func = aref_fallback;
2436 }
2437 }
2438 last_tc = ec->last_tc;
2439 max_output = last_tc ? last_tc->transcoder->max_output : 1;
2440
2441 resume:
2442 ret = rb_econv_convert(ec, in_pos, in_stop, out_pos, out_stop, 0);
2443
2444 if (!NIL_P(fallback) && ret == econv_undefined_conversion) {
2445 VALUE rep = rb_enc_str_new(
2446 (const char *)ec->last_error.error_bytes_start,
2447 ec->last_error.error_bytes_len,
2448 rb_enc_find(ec->last_error.source_encoding));
2449
2450
2451 struct transcode_loop_fallback_args args = {
2452 .fallback_func = fallback_func,
2453 .fallback = fallback,
2454 .rep = rep,
2455 };
2456
2457 int state;
2458 rep = rb_protect(transcode_loop_fallback_try, (VALUE)&args, &state);
2459 if (state) {
2460 rb_econv_close(ec);
2461 rb_jump_tag(state);
2462 }
2463
2464 /* Ruby code run during the conversion (e.g. the fallback) may have
2465 * modified the source string, invalidating the pointers into its
2466 * buffer. */
2467 if ((const unsigned char *)RSTRING_PTR(source) != source_start ||
2468 RSTRING_LEN(source) != source_len) {
2469 rb_econv_close(ec);
2470 rb_raise(rb_eRuntimeError, "string modified");
2471 }
2472
2473 if (!NIL_OR_UNDEF_P(rep)) {
2474 ret = rb_econv_insert_output(ec, (const unsigned char *)RSTRING_PTR(rep),
2475 RSTRING_LEN(rep), rb_enc_name(rb_enc_get(rep)));
2476 RB_GC_GUARD(rep); // insert_output may GC while reading rep's bytes
2477 if ((int)ret == -1) {
2478 rb_econv_close(ec);
2479 rb_raise(rb_eArgError, "too big fallback string");
2480 }
2481 goto resume;
2482 }
2483 }
2484
2485 if (ret == econv_invalid_byte_sequence ||
2486 ret == econv_incomplete_input ||
2488 exc = make_econv_exception(ec);
2489 rb_econv_close(ec);
2490 rb_exc_raise(exc);
2491 }
2492
2493 if (ret == econv_destination_buffer_full) {
2494 more_output_buffer(destination, resize_destination, max_output, &out_start, out_pos, &out_stop);
2495 goto resume;
2496 }
2497
2498 rb_econv_close(ec);
2499 return;
2500}
2501#else
2502/* sample transcode_loop implementation in byte-by-byte stream style */
2503static void
2504transcode_loop(const unsigned char **in_pos, unsigned char **out_pos,
2505 const unsigned char *in_stop, unsigned char *out_stop,
2506 VALUE destination,
2507 unsigned char *(*resize_destination)(VALUE, size_t, size_t),
2508 const char *src_encoding,
2509 const char *dst_encoding,
2510 int ecflags,
2511 VALUE ecopts,
2512 VALUE source)
2513{
2514 rb_econv_t *ec;
2515 rb_transcoding *last_tc;
2517 unsigned char *out_start = *out_pos;
2518 const unsigned char *ptr;
2519 int max_output;
2520 VALUE exc;
2521
2522 ec = rb_econv_open_opts(src_encoding, dst_encoding, ecflags, ecopts);
2523 if (!ec)
2524 rb_exc_raise(rb_econv_open_exc(src_encoding, dst_encoding, ecflags));
2525
2526 last_tc = ec->last_tc;
2527 max_output = last_tc ? last_tc->transcoder->max_output : 1;
2528
2530 ptr = *in_pos;
2531 while (ret != econv_finished) {
2532 unsigned char input_byte;
2533 const unsigned char *p = &input_byte;
2534
2535 if (ret == econv_source_buffer_empty) {
2536 if (ptr < in_stop) {
2537 input_byte = *ptr;
2538 ret = rb_econv_convert(ec, &p, p+1, out_pos, out_stop, ECONV_PARTIAL_INPUT);
2539 }
2540 else {
2541 ret = rb_econv_convert(ec, NULL, NULL, out_pos, out_stop, 0);
2542 }
2543 }
2544 else {
2545 ret = rb_econv_convert(ec, NULL, NULL, out_pos, out_stop, ECONV_PARTIAL_INPUT);
2546 }
2547 if (&input_byte != p)
2548 ptr += p - &input_byte;
2549 switch (ret) {
2553 exc = make_econv_exception(ec);
2554 rb_econv_close(ec);
2555 rb_exc_raise(exc);
2556 break;
2557
2559 more_output_buffer(destination, resize_destination, max_output, &out_start, out_pos, &out_stop);
2560 break;
2561
2563 break;
2564
2565 case econv_finished:
2566 break;
2567 }
2568 }
2569 rb_econv_close(ec);
2570 *in_pos = in_stop;
2571 return;
2572}
2573#endif
2574
2575
2576/*
2577 * String-specific code
2578 */
2579
2580static unsigned char *
2581str_transcoding_resize(VALUE destination, size_t len, size_t new_len)
2582{
2583 rb_str_resize(destination, new_len);
2584 return (unsigned char *)RSTRING_PTR(destination);
2585}
2586
2587static int
2588econv_opts(VALUE opt, int ecflags)
2589{
2590 VALUE v;
2591 int newlineflag = 0;
2592
2593 v = rb_hash_aref(opt, sym_invalid);
2594 if (NIL_P(v)) {
2595 }
2596 else if (v==sym_replace) {
2597 ecflags |= ECONV_INVALID_REPLACE;
2598 }
2599 else {
2600 rb_raise(rb_eArgError, "unknown value for invalid character option");
2601 }
2602
2603 v = rb_hash_aref(opt, sym_undef);
2604 if (NIL_P(v)) {
2605 }
2606 else if (v==sym_replace) {
2607 ecflags |= ECONV_UNDEF_REPLACE;
2608 }
2609 else {
2610 rb_raise(rb_eArgError, "unknown value for undefined character option");
2611 }
2612
2613 v = rb_hash_aref(opt, sym_replace);
2614 if (!NIL_P(v) && !(ecflags & ECONV_INVALID_REPLACE)) {
2615 ecflags |= ECONV_UNDEF_REPLACE;
2616 }
2617
2618 v = rb_hash_aref(opt, sym_xml);
2619 if (!NIL_P(v)) {
2620 if (v==sym_text) {
2622 }
2623 else if (v==sym_attr) {
2625 }
2626 else if (SYMBOL_P(v)) {
2627 rb_raise(rb_eArgError, "unexpected value for xml option: %"PRIsVALUE, rb_sym2str(v));
2628 }
2629 else {
2630 rb_raise(rb_eArgError, "unexpected value for xml option");
2631 }
2632 }
2633
2634#ifdef ENABLE_ECONV_NEWLINE_OPTION
2635 v = rb_hash_aref(opt, sym_newline);
2636 if (!NIL_P(v)) {
2637 newlineflag = 2;
2639 if (v == sym_universal) {
2641 }
2642 else if (v == sym_crlf) {
2644 }
2645 else if (v == sym_cr) {
2646 ecflags |= ECONV_CR_NEWLINE_DECORATOR;
2647 }
2648 else if (v == sym_lf) {
2649 ecflags |= ECONV_LF_NEWLINE_DECORATOR;
2650 }
2651 else if (SYMBOL_P(v)) {
2652 rb_raise(rb_eArgError, "unexpected value for newline option: %"PRIsVALUE,
2653 rb_sym2str(v));
2654 }
2655 else {
2656 rb_raise(rb_eArgError, "unexpected value for newline option");
2657 }
2658 }
2659#endif
2660 {
2661 int setflags = 0;
2662
2663 v = rb_hash_aref(opt, sym_universal_newline);
2664 if (RTEST(v))
2666 newlineflag |= !NIL_P(v);
2667
2668 v = rb_hash_aref(opt, sym_crlf_newline);
2669 if (RTEST(v))
2670 setflags |= ECONV_CRLF_NEWLINE_DECORATOR;
2671 newlineflag |= !NIL_P(v);
2672
2673 v = rb_hash_aref(opt, sym_cr_newline);
2674 if (RTEST(v))
2675 setflags |= ECONV_CR_NEWLINE_DECORATOR;
2676 newlineflag |= !NIL_P(v);
2677
2678 v = rb_hash_aref(opt, sym_lf_newline);
2679 if (RTEST(v))
2680 setflags |= ECONV_LF_NEWLINE_DECORATOR;
2681 newlineflag |= !NIL_P(v);
2682
2683 switch (newlineflag) {
2684 case 1:
2686 ecflags |= setflags;
2687 break;
2688
2689 case 3:
2690 rb_warning(":newline option precedes other newline options");
2691 break;
2692 }
2693 }
2694
2695 return ecflags;
2696}
2697
2698int
2699rb_econv_prepare_options(VALUE opthash, VALUE *opts, int ecflags)
2700{
2701 VALUE newhash = Qnil;
2702 VALUE v;
2703
2704 if (NIL_P(opthash)) {
2705 *opts = Qnil;
2706 return ecflags;
2707 }
2708 ecflags = econv_opts(opthash, ecflags);
2709
2710 v = rb_hash_aref(opthash, sym_replace);
2711 if (!NIL_P(v)) {
2712 StringValue(v);
2713 if (is_broken_string(v)) {
2714 VALUE dumped = rb_str_dump(v);
2715 rb_raise(rb_eArgError, "replacement string is broken: %s as %s",
2716 StringValueCStr(dumped),
2717 rb_enc_name(rb_enc_get(v)));
2718 }
2719 v = rb_str_new_frozen(v);
2720 newhash = rb_hash_new();
2721 rb_hash_aset(newhash, sym_replace, v);
2722 }
2723
2724 v = rb_hash_aref(opthash, sym_fallback);
2725 if (!NIL_P(v)) {
2726 VALUE h = rb_check_hash_type(v);
2727 if (NIL_P(h)
2728 ? (rb_obj_is_proc(v) || rb_obj_is_method(v) || rb_respond_to(v, idAREF))
2729 : (v = h, 1)) {
2730 if (NIL_P(newhash))
2731 newhash = rb_hash_new();
2732 rb_hash_aset(newhash, sym_fallback, v);
2733 }
2734 }
2735
2736 if (!NIL_P(newhash))
2737 rb_hash_freeze(newhash);
2738 *opts = newhash;
2739
2740 return ecflags;
2741}
2742
2743int
2745{
2746 return rb_econv_prepare_options(opthash, opts, 0);
2747}
2748
2749rb_econv_t *
2750rb_econv_open_opts(const char *source_encoding, const char *destination_encoding, int ecflags, VALUE opthash)
2751{
2752 rb_econv_t *ec;
2753 VALUE replacement;
2754
2755 if (NIL_P(opthash)) {
2756 replacement = Qnil;
2757 }
2758 else {
2759 if (!RB_TYPE_P(opthash, T_HASH) || !OBJ_FROZEN(opthash))
2760 rb_bug("rb_econv_open_opts called with invalid opthash");
2761 replacement = rb_hash_aref(opthash, sym_replace);
2762 }
2763
2764 ec = rb_econv_open(source_encoding, destination_encoding, ecflags);
2765 if (ec) {
2766 if (!NIL_P(replacement)) {
2767 int ret;
2768 rb_encoding *enc = rb_enc_get(replacement);
2769
2770 ret = rb_econv_set_replacement(ec,
2771 (const unsigned char *)RSTRING_PTR(replacement),
2772 RSTRING_LEN(replacement),
2773 rb_enc_name(enc));
2774 if (ret == -1) {
2775 rb_econv_close(ec);
2776 ec = NULL;
2777 }
2778 }
2779 }
2780 return ec; // can be NULL
2781}
2782
2783static int
2784enc_arg(VALUE *arg, const char **name_p, rb_encoding **enc_p)
2785{
2786 rb_encoding *enc;
2787 const char *n;
2788 int encidx;
2789 VALUE encval;
2790
2791 if (((encidx = rb_to_encoding_index(encval = *arg)) < 0) ||
2792 !(enc = rb_enc_from_index(encidx))) {
2793 enc = NULL;
2794 encidx = 0;
2795 n = StringValueCStr(*arg);
2796 }
2797 else {
2798 n = rb_enc_name(enc);
2799 }
2800
2801 *name_p = n;
2802 *enc_p = enc;
2803
2804 return encidx;
2805}
2806
2807static int
2808str_transcode_enc_args(VALUE str, VALUE *arg1, VALUE *arg2,
2809 const char **sname_p, rb_encoding **senc_p,
2810 const char **dname_p, rb_encoding **denc_p)
2811{
2812 rb_encoding *senc, *denc;
2813 const char *sname, *dname;
2814 int sencidx, dencidx;
2815
2816 dencidx = enc_arg(arg1, &dname, &denc);
2817
2818 if (NIL_P(*arg2)) {
2819 sencidx = rb_enc_get_index(str);
2820 senc = rb_enc_from_index(sencidx);
2821 sname = rb_enc_name(senc);
2822 }
2823 else {
2824 sencidx = enc_arg(arg2, &sname, &senc);
2825 }
2826
2827 *sname_p = sname;
2828 *senc_p = senc;
2829 *dname_p = dname;
2830 *denc_p = denc;
2831 return dencidx;
2832}
2833
2834static int
2835str_transcode0(int argc, VALUE *argv, VALUE *self, int ecflags, VALUE ecopts)
2836{
2837 VALUE dest;
2838 VALUE str = *self;
2839 VALUE arg1, arg2;
2840 rb_len_t blen, slen;
2841 unsigned char *buf, *bp, *sp;
2842 const unsigned char *fromp;
2843 rb_encoding *senc, *denc;
2844 const char *sname, *dname;
2845 int dencidx;
2846 int explicitly_invalid_replace = TRUE;
2847 int decorator_only = FALSE;
2848
2849 rb_check_arity(argc, 0, 2);
2850
2851 if (argc == 0) {
2852 arg1 = rb_enc_default_internal();
2853 if (NIL_P(arg1)) {
2854 if (!ecflags) return -1;
2855 arg1 = rb_obj_encoding(str);
2856 }
2857 if (!(ecflags & ECONV_INVALID_MASK)) {
2858 explicitly_invalid_replace = FALSE;
2859 }
2861 }
2862 else {
2863 arg1 = argv[0];
2864 }
2865 arg2 = argc<=1 ? Qnil : argv[1];
2866 dencidx = str_transcode_enc_args(str, &arg1, &arg2, &sname, &senc, &dname, &denc);
2867
2868 if ((ecflags & (ECONV_NEWLINE_DECORATOR_MASK|
2872 if (senc && senc == denc) {
2873 if ((ecflags & ECONV_INVALID_MASK) && explicitly_invalid_replace) {
2874 VALUE rep = Qnil;
2875 if (!NIL_P(ecopts)) {
2876 rep = rb_hash_aref(ecopts, sym_replace);
2877 }
2878 dest = rb_enc_str_scrub(senc, str, rep);
2879 if (NIL_P(dest)) dest = str;
2880 *self = dest;
2881 return dencidx;
2882 }
2883 return NIL_P(arg2) ? -1 : dencidx;
2884 }
2885 if (senc && denc && rb_enc_asciicompat(senc) && rb_enc_asciicompat(denc)) {
2886 if (is_ascii_string(str)) {
2887 return dencidx;
2888 }
2889 }
2890 if (encoding_equal(sname, dname)) {
2891 return NIL_P(arg2) ? -1 : dencidx;
2892 }
2893 }
2894 else {
2895 if (senc && denc && !rb_enc_asciicompat(senc) && !rb_enc_asciicompat(denc)) {
2896 rb_encoding *utf8 = rb_utf8_encoding();
2897 str = rb_enc_associate(rb_str_dup(str), senc);
2898 str = rb_str_encode(str, rb_enc_from_encoding(utf8),
2899 ecflags & ECONV_ERROR_HANDLER_MASK, ecopts);
2900 senc = utf8;
2901 sname = "UTF-8";
2902 }
2903 if (encoding_equal(sname, dname)) {
2904 sname = "";
2905 dname = "";
2906 decorator_only = TRUE;
2907 }
2908 }
2909
2910 fromp = sp = (unsigned char *)RSTRING_PTR(str);
2911 slen = RSTRING_LEN(str);
2912 blen = slen + 30; /* len + margin */
2913 dest = rb_str_tmp_new(blen);
2914 bp = (unsigned char *)RSTRING_PTR(dest);
2915
2916 transcode_loop(&fromp, &bp, (sp+slen), (bp+blen), dest, str_transcoding_resize, sname, dname, ecflags, ecopts, str);
2917 if (fromp != sp+slen) {
2918 rb_raise(rb_eArgError, "not fully converted, %"PRIdPTRDIFF" bytes left", sp+slen-fromp);
2919 }
2920 buf = (unsigned char *)RSTRING_PTR(dest);
2921 *bp = '\0';
2922 rb_str_set_len(dest, bp - buf);
2923
2924 if (decorator_only && senc) {
2925 /* No transcoder ran, so invalid bytes were passed through
2926 * unchecked. The decorators only add and remove ASCII bytes, which
2927 * are never part of a multibyte character in an ASCII compatible
2928 * encoding, so the result is exactly as valid as the source. */
2929 rb_enc_associate(dest, senc);
2930 if (rb_enc_get(str) == senc) {
2931 ENC_CODERANGE_SET(dest, rb_enc_str_coderange(str));
2932 }
2933 else {
2934 rb_enc_str_coderange(dest);
2935 }
2936 }
2937
2938 /* set encoding */
2939 if (!denc) {
2940 dencidx = rb_define_dummy_encoding(dname);
2941 RB_GC_GUARD(arg1);
2942 RB_GC_GUARD(arg2);
2943 }
2944 *self = dest;
2945
2946 return dencidx;
2947}
2948
2949static int
2950str_transcode(int argc, VALUE *argv, VALUE *self)
2951{
2952 VALUE opt;
2953 int ecflags = 0;
2954 VALUE ecopts = Qnil;
2955
2956 argc = rb_scan_args(argc, argv, "02:", NULL, NULL, &opt);
2957 if (!NIL_P(opt)) {
2958 ecflags = rb_econv_prepare_opts(opt, &ecopts);
2959 }
2960 return str_transcode0(argc, argv, self, ecflags, ecopts);
2961}
2962
2963static inline VALUE
2964str_encode_associate(VALUE str, int encidx)
2965{
2966 int cr = 0;
2967
2968 rb_enc_associate_index(str, encidx);
2969
2970 /* str_transcode0 sets the coderange of output that didn't come from a
2971 * transcoder. */
2972 if (ENC_CODERANGE(str) != ENC_CODERANGE_UNKNOWN) return str;
2973
2974 /* A transcoder never produces broken strings, so only check for
2975 * non-ASCII bytes. */
2976 if (rb_enc_asciicompat(rb_enc_from_index(encidx))) {
2977 rb_str_coderange_scan_restartable(RSTRING_PTR(str), RSTRING_END(str), 0, &cr);
2978 }
2979 else {
2981 }
2982 ENC_CODERANGE_SET(str, cr);
2983 return str;
2984}
2985
2986/*
2987 * call-seq:
2988 * encode!(dst_encoding = Encoding.default_internal, **enc_opts) -> self
2989 * encode!(dst_encoding, src_encoding, **enc_opts) -> self
2990 *
2991 * Like #encode, but applies encoding changes to +self+; returns +self+.
2992 *
2993 * Related: see {Modifying}[rdoc-ref:String@Modifying].
2994 */
2995
2996static VALUE
2997str_encode_bang(int argc, VALUE *argv, VALUE str)
2998{
2999 VALUE newstr;
3000 int encidx;
3001
3002 rb_check_frozen(str);
3003
3004 newstr = str;
3005 encidx = str_transcode(argc, argv, &newstr);
3006
3007 if (encidx < 0) return str;
3008 if (newstr == str) {
3009 rb_enc_associate_index(str, encidx);
3010 return str;
3011 }
3012 rb_str_shared_replace(str, newstr);
3013 return str_encode_associate(str, encidx);
3014}
3015
3016static VALUE encoded_dup(VALUE newstr, VALUE str, int encidx);
3017
3018/*
3019 * call-seq:
3020 * encode(dst_encoding = Encoding.default_internal, **enc_opts) -> string
3021 * encode(dst_encoding, src_encoding, **enc_opts) -> string
3022 *
3023 * Returns a copy of +self+ transcoded as determined by +dst_encoding+;
3024 * see {Encodings}[rdoc-ref:encodings.rdoc].
3025 *
3026 * By default, raises an exception if +self+
3027 * contains an invalid byte or a character not defined in +dst_encoding+;
3028 * that behavior may be modified by encoding options; see below.
3029 *
3030 * With no arguments:
3031 *
3032 * - Uses the same encoding if <tt>Encoding.default_internal</tt> is +nil+
3033 * (the default):
3034 *
3035 * Encoding.default_internal # => nil
3036 * s = "Ruby\x99".force_encoding('Windows-1252')
3037 * s.encoding # => #<Encoding:Windows-1252>
3038 * s.bytes # => [82, 117, 98, 121, 153]
3039 * t = s.encode # => "Ruby\x99"
3040 * t.encoding # => #<Encoding:Windows-1252>
3041 * t.bytes # => [82, 117, 98, 121, 153]
3042 *
3043 * - Otherwise, uses the encoding <tt>Encoding.default_internal</tt>:
3044 *
3045 * Encoding.default_internal = 'UTF-8'
3046 * t = s.encode # => "Rubyâ„¢"
3047 * t.encoding # => #<Encoding:UTF-8>
3048 *
3049 * With only argument +dst_encoding+ given, uses that encoding:
3050 *
3051 * s = "Ruby\x99".force_encoding('Windows-1252')
3052 * s.encoding # => #<Encoding:Windows-1252>
3053 * t = s.encode('UTF-8') # => "Rubyâ„¢"
3054 * t.encoding # => #<Encoding:UTF-8>
3055 *
3056 * With arguments +dst_encoding+ and +src_encoding+ given,
3057 * interprets +self+ using +src_encoding+, encodes the new string using +dst_encoding+:
3058 *
3059 * s = "Ruby\x99"
3060 * t = s.encode('UTF-8', 'Windows-1252') # => "Rubyâ„¢"
3061 * t.encoding # => #<Encoding:UTF-8>
3062 *
3063 * Optional keyword arguments +enc_opts+ specify encoding options;
3064 * see {Encoding Options}[rdoc-ref:encodings.rdoc@Encoding+Options].
3065 *
3066 * Please note that, unless <code>invalid: :replace</code> option is
3067 * given, conversion from an encoding +enc+ to the same encoding +enc+
3068 * (independent of whether +enc+ is given explicitly or implicitly) is a
3069 * no-op, i.e. the string is simply copied without any changes, and no
3070 * exceptions are raised, even if there are invalid bytes.
3071 *
3072 * Related: see {Converting to New String}[rdoc-ref:String@Converting+to+New+String].
3073 *
3074 */
3075
3076static VALUE
3077str_encode(int argc, VALUE *argv, VALUE str)
3078{
3079 VALUE newstr = str;
3080 int encidx = str_transcode(argc, argv, &newstr);
3081 return encoded_dup(newstr, str, encidx);
3082}
3083
3084VALUE
3085rb_str_encode(VALUE str, VALUE to, int ecflags, VALUE ecopts)
3086{
3087 int argc = 1;
3088 VALUE *argv = &to;
3089 VALUE newstr = str;
3090 int encidx = str_transcode0(argc, argv, &newstr, ecflags, ecopts);
3091 return encoded_dup(newstr, str, encidx);
3092}
3093
3094static VALUE
3095encoded_dup(VALUE newstr, VALUE str, int encidx)
3096{
3097 if (encidx < 0) return rb_str_dup(str);
3098 if (newstr == str) {
3099 newstr = rb_str_dup(str);
3100 rb_enc_associate_index(newstr, encidx);
3101 return newstr;
3102 }
3103 else {
3104 RBASIC_SET_CLASS(newstr, rb_obj_class(str));
3105 }
3106 return str_encode_associate(newstr, encidx);
3107}
3108
3109/*
3110 * Document-class: Encoding::Converter
3111 *
3112 * Encoding conversion class.
3113 */
3114static void
3115econv_free(void *ptr)
3116{
3117 rb_econv_t *ec = ptr;
3118 rb_econv_close(ec);
3119}
3120
3121static size_t
3122econv_memsize(const void *ptr)
3123{
3124 return ptr ? rb_econv_memsize((rb_econv_t *)ptr) : 0;
3125}
3126
3127static const rb_data_type_t econv_data_type = {
3128 "econv",
3129 {0, econv_free, econv_memsize,},
3130 0, 0, RUBY_TYPED_THREAD_SAFE_FREE
3131};
3132
3133static VALUE
3134econv_s_allocate(VALUE klass)
3135{
3136 return TypedData_Wrap_Struct(klass, &econv_data_type, NULL);
3137}
3138
3139static rb_encoding *
3140make_dummy_encoding(const char *name)
3141{
3142 rb_encoding *enc;
3143 int idx;
3144 idx = rb_define_dummy_encoding(name);
3145 enc = rb_enc_from_index(idx);
3146 return enc;
3147}
3148
3149static rb_encoding *
3150make_encoding(const char *name)
3151{
3152 rb_encoding *enc;
3153 enc = rb_enc_find(name);
3154 if (!enc) {
3155 RB_VM_LOCKING() {
3156 if (rb_enc_registered(name)) {
3157 enc = NULL;
3158 }
3159 else {
3160 enc = make_dummy_encoding(name);
3161 }
3162 }
3163 }
3164 return enc;
3165}
3166
3167static VALUE
3168make_encobj(const char *name)
3169{
3170 return rb_enc_from_encoding(make_encoding(name));
3171}
3172
3173/*
3174 * call-seq:
3175 * Encoding::Converter.asciicompat_encoding(string) -> encoding or nil
3176 * Encoding::Converter.asciicompat_encoding(encoding) -> encoding or nil
3177 *
3178 * Returns the corresponding ASCII compatible encoding.
3179 *
3180 * Returns nil if the argument is an ASCII compatible encoding.
3181 *
3182 * "corresponding ASCII compatible encoding" is an ASCII compatible encoding which
3183 * can represents exactly the same characters as the given ASCII incompatible encoding.
3184 * So, no conversion undefined error occurs when converting between the two encodings.
3185 *
3186 * Encoding::Converter.asciicompat_encoding("ISO-2022-JP") #=> #<Encoding:stateless-ISO-2022-JP>
3187 * Encoding::Converter.asciicompat_encoding("UTF-16BE") #=> #<Encoding:UTF-8>
3188 * Encoding::Converter.asciicompat_encoding("UTF-8") #=> nil
3189 *
3190 */
3191static VALUE
3192econv_s_asciicompat_encoding(VALUE klass, VALUE arg)
3193{
3194 const char *arg_name, *result_name;
3195 rb_encoding *arg_enc, *result_enc;
3196 VALUE enc = Qnil;
3197
3198 enc_arg(&arg, &arg_name, &arg_enc);
3199 result_name = rb_econv_asciicompat_encoding(arg_name);
3200 if (result_name) {
3201 result_enc = make_encoding(result_name);
3202 enc = rb_enc_from_encoding(result_enc);
3203 }
3204 return enc;
3205}
3206
3207static void
3208econv_args(int argc, VALUE *argv,
3209 VALUE *snamev_p, VALUE *dnamev_p,
3210 const char **sname_p, const char **dname_p,
3211 rb_encoding **senc_p, rb_encoding **denc_p,
3212 int *ecflags_p,
3213 VALUE *ecopts_p)
3214{
3215 VALUE opt, flags_v, ecopts;
3216 int sidx, didx;
3217 const char *sname, *dname;
3218 rb_encoding *senc, *denc;
3219 int ecflags;
3220
3221 argc = rb_scan_args(argc, argv, "21:", snamev_p, dnamev_p, &flags_v, &opt);
3222
3223 if (!NIL_P(flags_v)) {
3224 if (!NIL_P(opt)) {
3225 rb_error_arity(argc + 1, 2, 3);
3226 }
3227 ecflags = NUM2INT(rb_to_int(flags_v));
3228 ecopts = Qnil;
3229 }
3230 else if (!NIL_P(opt)) {
3231 ecflags = rb_econv_prepare_opts(opt, &ecopts);
3232 }
3233 else {
3234 ecflags = 0;
3235 ecopts = Qnil;
3236 }
3237
3238 senc = NULL;
3239 sidx = rb_to_encoding_index(*snamev_p);
3240 if (0 <= sidx) {
3241 senc = rb_enc_from_index(sidx);
3242 }
3243 else {
3244 StringValue(*snamev_p);
3245 }
3246
3247 denc = NULL;
3248 didx = rb_to_encoding_index(*dnamev_p);
3249 if (0 <= didx) {
3250 denc = rb_enc_from_index(didx);
3251 }
3252 else {
3253 StringValue(*dnamev_p);
3254 }
3255
3256 sname = senc ? rb_enc_name(senc) : StringValueCStr(*snamev_p);
3257 dname = denc ? rb_enc_name(denc) : StringValueCStr(*dnamev_p);
3258
3259 *sname_p = sname;
3260 *dname_p = dname;
3261 *senc_p = senc;
3262 *denc_p = denc;
3263 *ecflags_p = ecflags;
3264 *ecopts_p = ecopts;
3265}
3266
3267static int
3268decorate_convpath(VALUE convpath, int ecflags)
3269{
3270 int num_decorators;
3271 const char *decorators[MAX_ECFLAGS_DECORATORS];
3272 int i;
3273 int n, len;
3274
3275 num_decorators = decorator_names(ecflags, decorators);
3276 if (num_decorators == -1)
3277 return -1;
3278
3279 len = n = RARRAY_LENINT(convpath);
3280 if (n != 0) {
3281 VALUE pair = RARRAY_AREF(convpath, n-1);
3282 if (RB_TYPE_P(pair, T_ARRAY)) {
3283 const char *sname = rb_enc_name(rb_to_encoding(RARRAY_AREF(pair, 0)));
3284 const char *dname = rb_enc_name(rb_to_encoding(RARRAY_AREF(pair, 1)));
3285 transcoder_entry_t *entry;
3286 const rb_transcoder *tr;
3287 entry = get_transcoder_entry(sname, dname);
3288 tr = load_transcoder_entry(entry);
3289 if (!tr)
3290 return -1;
3291 if (!DECORATOR_P(tr->src_encoding, tr->dst_encoding) &&
3292 tr->asciicompat_type == asciicompat_encoder) {
3293 n--;
3294 rb_ary_store(convpath, len + num_decorators - 1, pair);
3295 }
3296 }
3297 else {
3298 rb_ary_store(convpath, len + num_decorators - 1, pair);
3299 }
3300 }
3301
3302 for (i = 0; i < num_decorators; i++)
3303 rb_ary_store(convpath, n + i, rb_str_new_cstr(decorators[i]));
3304
3305 return 0;
3306}
3307
3308static void
3309search_convpath_i(const char *sname, const char *dname, int depth, void *arg)
3310{
3311 VALUE *ary_p = arg;
3312 VALUE v;
3313
3314 if (NIL_P(*ary_p)) {
3315 *ary_p = rb_ary_new();
3316 }
3317
3318 if (DECORATOR_P(sname, dname)) {
3319 v = rb_str_new_cstr(dname);
3320 }
3321 else {
3322 v = rb_assoc_new(make_encobj(sname), make_encobj(dname));
3323 }
3324 rb_ary_store(*ary_p, depth, v);
3325}
3326
3327/*
3328 * call-seq:
3329 * Encoding::Converter.search_convpath(source_encoding, destination_encoding) -> ary
3330 * Encoding::Converter.search_convpath(source_encoding, destination_encoding, opt) -> ary
3331 *
3332 * Returns a conversion path.
3333 *
3334 * p Encoding::Converter.search_convpath("ISO-8859-1", "EUC-JP")
3335 * #=> [[#<Encoding:ISO-8859-1>, #<Encoding:UTF-8>],
3336 * # [#<Encoding:UTF-8>, #<Encoding:EUC-JP>]]
3337 *
3338 * p Encoding::Converter.search_convpath("ISO-8859-1", "EUC-JP", universal_newline: true)
3339 * or
3340 * p Encoding::Converter.search_convpath("ISO-8859-1", "EUC-JP", newline: :universal)
3341 * #=> [[#<Encoding:ISO-8859-1>, #<Encoding:UTF-8>],
3342 * # [#<Encoding:UTF-8>, #<Encoding:EUC-JP>],
3343 * # "universal_newline"]
3344 *
3345 * p Encoding::Converter.search_convpath("ISO-8859-1", "UTF-32BE", universal_newline: true)
3346 * or
3347 * p Encoding::Converter.search_convpath("ISO-8859-1", "UTF-32BE", newline: :universal)
3348 * #=> [[#<Encoding:ISO-8859-1>, #<Encoding:UTF-8>],
3349 * # "universal_newline",
3350 * # [#<Encoding:UTF-8>, #<Encoding:UTF-32BE>]]
3351 */
3352static VALUE
3353econv_s_search_convpath(int argc, VALUE *argv, VALUE klass)
3354{
3355 VALUE snamev, dnamev;
3356 const char *sname, *dname;
3357 rb_encoding *senc, *denc;
3358 int ecflags;
3359 VALUE ecopts;
3360 VALUE convpath;
3361
3362 econv_args(argc, argv, &snamev, &dnamev, &sname, &dname, &senc, &denc, &ecflags, &ecopts);
3363
3364 convpath = Qnil;
3365 transcode_search_path(sname, dname, search_convpath_i, &convpath);
3366
3367 if (NIL_P(convpath)) {
3368 VALUE exc = rb_econv_open_exc(sname, dname, ecflags);
3369 RB_GC_GUARD(snamev);
3370 RB_GC_GUARD(dnamev);
3371 rb_exc_raise(exc);
3372 }
3373
3374 if (decorate_convpath(convpath, ecflags) == -1) {
3375 VALUE exc = rb_econv_open_exc(sname, dname, ecflags);
3376 RB_GC_GUARD(snamev);
3377 RB_GC_GUARD(dnamev);
3378 rb_exc_raise(exc);
3379 }
3380
3381 return convpath;
3382}
3383
3384/*
3385 * Check the existence of a conversion path.
3386 * Returns the number of converters in the conversion path.
3387 * result: >=0:success -1:failure
3388 */
3389int
3390rb_econv_has_convpath_p(const char* from_encoding, const char* to_encoding)
3391{
3392 VALUE convpath = Qnil;
3393 transcode_search_path(from_encoding, to_encoding, search_convpath_i,
3394 &convpath);
3395 return RTEST(convpath);
3396}
3397
3399 rb_econv_t *ec;
3400 int index;
3401 int ret;
3402};
3403
3404static void
3405rb_econv_init_by_convpath_i(const char *sname, const char *dname, int depth, void *arg)
3406{
3408 int ret;
3409
3410 if (a->ret == -1)
3411 return;
3412
3413 ret = rb_econv_add_converter(a->ec, sname, dname, a->index);
3414
3415 a->ret = ret;
3416 return;
3417}
3418
3419static rb_econv_t *
3420rb_econv_init_by_convpath(VALUE self, VALUE convpath,
3421 const char **sname_p, const char **dname_p,
3422 rb_encoding **senc_p, rb_encoding**denc_p)
3423{
3424 rb_econv_t *ec;
3425 rb_len_t i;
3426 int ret, first=1;
3427 VALUE elt;
3428 rb_encoding *senc = 0, *denc = 0;
3429 const char *sname, *dname;
3430
3431 ec = rb_econv_alloc(RARRAY_LENINT(convpath));
3432 DATA_PTR(self) = ec;
3433
3434 for (i = 0; i < RARRAY_LEN(convpath); i++) {
3435 VALUE snamev, dnamev;
3436 VALUE pair;
3437 elt = rb_ary_entry(convpath, i);
3438 if (!NIL_P(pair = rb_check_array_type(elt))) {
3439 if (RARRAY_LEN(pair) != 2)
3440 rb_raise(rb_eArgError, "not a 2-element array in convpath");
3441 snamev = rb_ary_entry(pair, 0);
3442 enc_arg(&snamev, &sname, &senc);
3443 dnamev = rb_ary_entry(pair, 1);
3444 enc_arg(&dnamev, &dname, &denc);
3445 }
3446 else {
3447 sname = "";
3448 dname = StringValueCStr(elt);
3449 }
3450 if (DECORATOR_P(sname, dname)) {
3451 ret = rb_econv_add_converter(ec, sname, dname, ec->num_trans);
3452 if (ret == -1) {
3453 VALUE msg = rb_sprintf("decoration failed: %s", dname);
3454 RB_GC_GUARD(snamev);
3455 RB_GC_GUARD(dnamev);
3456 rb_exc_raise(rb_exc_new_str(rb_eArgError, msg));
3457 }
3458 }
3459 else {
3460 int j = ec->num_trans;
3461 struct rb_econv_init_by_convpath_t arg;
3462 arg.ec = ec;
3463 arg.index = ec->num_trans;
3464 arg.ret = 0;
3465 ret = transcode_search_path(sname, dname, rb_econv_init_by_convpath_i, &arg);
3466 if (ret == -1 || arg.ret == -1) {
3467 VALUE msg = rb_sprintf("adding conversion failed: %s to %s", sname, dname);
3468 RB_GC_GUARD(snamev);
3469 RB_GC_GUARD(dnamev);
3470 rb_exc_raise(rb_exc_new_str(rb_eArgError, msg));
3471 }
3472 if (first) {
3473 first = 0;
3474 *senc_p = senc;
3475 *sname_p = ec->elems[j].tc->transcoder->src_encoding;
3476 }
3477 *denc_p = denc;
3478 *dname_p = ec->elems[ec->num_trans-1].tc->transcoder->dst_encoding;
3479 }
3480 }
3481
3482 if (first) {
3483 *senc_p = NULL;
3484 *denc_p = NULL;
3485 *sname_p = "";
3486 *dname_p = "";
3487 }
3488
3489 ec->source_encoding_name = *sname_p;
3490 ec->destination_encoding_name = *dname_p;
3491
3492 return ec;
3493}
3494
3495/*
3496 * call-seq:
3497 * Encoding::Converter.new(source_encoding, destination_encoding)
3498 * Encoding::Converter.new(source_encoding, destination_encoding, opt)
3499 * Encoding::Converter.new(convpath)
3500 *
3501 * possible options elements:
3502 * hash form:
3503 * :invalid => nil # raise error on invalid byte sequence (default)
3504 * :invalid => :replace # replace invalid byte sequence
3505 * :undef => nil # raise error on undefined conversion (default)
3506 * :undef => :replace # replace undefined conversion
3507 * :replace => string # replacement string ("?" or "\uFFFD" if not specified)
3508 * :newline => :universal # decorator for converting CRLF and CR to LF
3509 * :newline => :lf # decorator for converting CRLF and CR to LF when writing
3510 * :newline => :crlf # decorator for converting LF to CRLF
3511 * :newline => :cr # decorator for converting LF to CR
3512 * :universal_newline => true # decorator for converting CRLF and CR to LF
3513 * :crlf_newline => true # decorator for converting LF to CRLF
3514 * :cr_newline => true # decorator for converting LF to CR
3515 * :lf_newline => true # decorator for converting CRLF and CR to LF when writing
3516 * :xml => :text # escape as XML CharData.
3517 * :xml => :attr # escape as XML AttValue
3518 * integer form:
3519 * Encoding::Converter::INVALID_REPLACE
3520 * Encoding::Converter::UNDEF_REPLACE
3521 * Encoding::Converter::UNDEF_HEX_CHARREF
3522 * Encoding::Converter::UNIVERSAL_NEWLINE_DECORATOR
3523 * Encoding::Converter::LF_NEWLINE_DECORATOR
3524 * Encoding::Converter::CRLF_NEWLINE_DECORATOR
3525 * Encoding::Converter::CR_NEWLINE_DECORATOR
3526 * Encoding::Converter::XML_TEXT_DECORATOR
3527 * Encoding::Converter::XML_ATTR_CONTENT_DECORATOR
3528 * Encoding::Converter::XML_ATTR_QUOTE_DECORATOR
3529 *
3530 * Encoding::Converter.new creates an instance of Encoding::Converter.
3531 *
3532 * Source_encoding and destination_encoding should be a string or
3533 * Encoding object.
3534 *
3535 * opt should be nil, a hash or an integer.
3536 *
3537 * convpath should be an array.
3538 * convpath may contain
3539 * - two-element arrays which contain encodings or encoding names, or
3540 * - strings representing decorator names.
3541 *
3542 * Encoding::Converter.new optionally takes an option.
3543 * The option should be a hash or an integer.
3544 * The option hash can contain :invalid => nil, etc.
3545 * The option integer should be logical-or of constants such as
3546 * Encoding::Converter::INVALID_REPLACE, etc.
3547 *
3548 * [:invalid => nil]
3549 * Raise error on invalid byte sequence. This is a default behavior.
3550 * [:invalid => :replace]
3551 * Replace invalid byte sequence by replacement string.
3552 * [:undef => nil]
3553 * Raise an error if a character in source_encoding is not defined in destination_encoding.
3554 * This is a default behavior.
3555 * [:undef => :replace]
3556 * Replace undefined character in destination_encoding with replacement string.
3557 * [:replace => string]
3558 * Specify the replacement string.
3559 * If not specified, "\uFFFD" is used for Unicode encodings and "?" for others.
3560 * [:universal_newline => true]
3561 * Convert CRLF and CR to LF.
3562 * [:crlf_newline => true]
3563 * Convert LF to CRLF.
3564 * [:cr_newline => true]
3565 * Convert LF to CR.
3566 * [:lf_newline => true]
3567 * Convert CRLF and CR to LF (when writing).
3568 * [:xml => :text]
3569 * Escape as XML CharData.
3570 * This form can be used as an HTML 4.0 #PCDATA.
3571 * - '&' -> '&amp;'
3572 * - '<' -> '&lt;'
3573 * - '>' -> '&gt;'
3574 * - undefined characters in destination_encoding -> hexadecimal CharRef such as &#xHH;
3575 * [:xml => :attr]
3576 * Escape as XML AttValue.
3577 * The converted result is quoted as "...".
3578 * This form can be used as an HTML 4.0 attribute value.
3579 * - '&' -> '&amp;'
3580 * - '<' -> '&lt;'
3581 * - '>' -> '&gt;'
3582 * - '"' -> '&quot;'
3583 * - undefined characters in destination_encoding -> hexadecimal CharRef such as &#xHH;
3584 *
3585 * Examples:
3586 * # UTF-16BE to UTF-8
3587 * ec = Encoding::Converter.new("UTF-16BE", "UTF-8")
3588 *
3589 * # Usually, decorators such as newline conversion are inserted last.
3590 * ec = Encoding::Converter.new("UTF-16BE", "UTF-8", :universal_newline => true)
3591 * p ec.convpath #=> [[#<Encoding:UTF-16BE>, #<Encoding:UTF-8>],
3592 * # "universal_newline"]
3593 *
3594 * # But, if the last encoding is ASCII incompatible,
3595 * # decorators are inserted before the last conversion.
3596 * ec = Encoding::Converter.new("UTF-8", "UTF-16BE", :crlf_newline => true)
3597 * p ec.convpath #=> ["crlf_newline",
3598 * # [#<Encoding:UTF-8>, #<Encoding:UTF-16BE>]]
3599 *
3600 * # Conversion path can be specified directly.
3601 * ec = Encoding::Converter.new(["universal_newline", ["EUC-JP", "UTF-8"], ["UTF-8", "UTF-16BE"]])
3602 * p ec.convpath #=> ["universal_newline",
3603 * # [#<Encoding:EUC-JP>, #<Encoding:UTF-8>],
3604 * # [#<Encoding:UTF-8>, #<Encoding:UTF-16BE>]]
3605 */
3606static VALUE
3607econv_init(int argc, VALUE *argv, VALUE self)
3608{
3609 VALUE ecopts;
3610 VALUE snamev, dnamev;
3611 const char *sname, *dname;
3612 rb_encoding *senc, *denc;
3613 rb_econv_t *ec;
3614 int ecflags;
3615 VALUE convpath;
3616
3617 if (rb_check_typeddata(self, &econv_data_type)) {
3618 rb_raise(rb_eTypeError, "already initialized");
3619 }
3620
3621 if (argc == 1 && !NIL_P(convpath = rb_check_array_type(argv[0]))) {
3622 ec = rb_econv_init_by_convpath(self, convpath, &sname, &dname, &senc, &denc);
3623 ecflags = 0;
3624 ecopts = Qnil;
3625 }
3626 else {
3627 econv_args(argc, argv, &snamev, &dnamev, &sname, &dname, &senc, &denc, &ecflags, &ecopts);
3628 ec = rb_econv_open_opts(sname, dname, ecflags, ecopts);
3629 }
3630
3631 if (!ec) {
3632 VALUE exc = rb_econv_open_exc(sname, dname, ecflags);
3633 RB_GC_GUARD(snamev);
3634 RB_GC_GUARD(dnamev);
3635 rb_exc_raise(exc);
3636 }
3637
3638 if (!DECORATOR_P(sname, dname)) {
3639 if (!senc)
3640 senc = make_dummy_encoding(sname);
3641 if (!denc)
3642 denc = make_dummy_encoding(dname);
3643 RB_GC_GUARD(snamev);
3644 RB_GC_GUARD(dnamev);
3645 }
3646
3647 ec->source_encoding = senc;
3648 ec->destination_encoding = denc;
3649
3650 DATA_PTR(self) = ec;
3651
3652 return self;
3653}
3654
3655/*
3656 * call-seq:
3657 * ec.inspect -> string
3658 *
3659 * Returns a printable version of <i>ec</i>
3660 *
3661 * ec = Encoding::Converter.new("iso-8859-1", "utf-8")
3662 * puts ec.inspect #=> #<Encoding::Converter: ISO-8859-1 to UTF-8>
3663 *
3664 */
3665static VALUE
3666econv_inspect(VALUE self)
3667{
3668 const char *cname = rb_obj_classname(self);
3669 rb_econv_t *ec;
3670
3671 TypedData_Get_Struct(self, rb_econv_t, &econv_data_type, ec);
3672 if (!ec)
3673 return rb_sprintf("#<%s: uninitialized>", cname);
3674 else {
3675 const char *sname = ec->source_encoding_name;
3676 const char *dname = ec->destination_encoding_name;
3677 VALUE str;
3678 str = rb_sprintf("#<%s: ", cname);
3679 econv_description(sname, dname, ec->flags, str);
3680 rb_str_cat2(str, ">");
3681 return str;
3682 }
3683}
3684
3685static rb_econv_t *
3686check_econv(VALUE self)
3687{
3688 rb_econv_t *ec;
3689
3690 TypedData_Get_Struct(self, rb_econv_t, &econv_data_type, ec);
3691 if (!ec) {
3692 rb_raise(rb_eTypeError, "uninitialized encoding converter");
3693 }
3694 return ec;
3695}
3696
3697static VALUE
3698econv_get_encoding(rb_encoding *encoding)
3699{
3700 if (!encoding)
3701 return Qnil;
3702 return rb_enc_from_encoding(encoding);
3703}
3704
3705/*
3706 * call-seq:
3707 * ec.source_encoding -> encoding
3708 *
3709 * Returns the source encoding as an Encoding object.
3710 */
3711static VALUE
3712econv_source_encoding(VALUE self)
3713{
3714 rb_econv_t *ec = check_econv(self);
3715 return econv_get_encoding(ec->source_encoding);
3716}
3717
3718/*
3719 * call-seq:
3720 * ec.destination_encoding -> encoding
3721 *
3722 * Returns the destination encoding as an Encoding object.
3723 */
3724static VALUE
3725econv_destination_encoding(VALUE self)
3726{
3727 rb_econv_t *ec = check_econv(self);
3728 return econv_get_encoding(ec->destination_encoding);
3729}
3730
3731/*
3732 * call-seq:
3733 * ec.convpath -> ary
3734 *
3735 * Returns the conversion path of ec.
3736 *
3737 * The result is an array of conversions.
3738 *
3739 * ec = Encoding::Converter.new("ISO-8859-1", "EUC-JP", crlf_newline: true)
3740 * p ec.convpath
3741 * #=> [[#<Encoding:ISO-8859-1>, #<Encoding:UTF-8>],
3742 * # [#<Encoding:UTF-8>, #<Encoding:EUC-JP>],
3743 * # "crlf_newline"]
3744 *
3745 * Each element of the array is a pair of encodings or a string.
3746 * A pair means an encoding conversion.
3747 * A string means a decorator.
3748 *
3749 * In the above example, [#<Encoding:ISO-8859-1>, #<Encoding:UTF-8>] means
3750 * a converter from ISO-8859-1 to UTF-8.
3751 * "crlf_newline" means newline converter from LF to CRLF.
3752 */
3753static VALUE
3754econv_convpath(VALUE self)
3755{
3756 rb_econv_t *ec = check_econv(self);
3757 VALUE result;
3758 int i;
3759
3760 result = rb_ary_new();
3761 for (i = 0; i < ec->num_trans; i++) {
3762 const rb_transcoder *tr = ec->elems[i].tc->transcoder;
3763 VALUE v;
3764 if (DECORATOR_P(tr->src_encoding, tr->dst_encoding))
3765 v = rb_str_new_cstr(tr->dst_encoding);
3766 else
3767 v = rb_assoc_new(make_encobj(tr->src_encoding), make_encobj(tr->dst_encoding));
3768 rb_ary_push(result, v);
3769 }
3770 return result;
3771}
3772
3773/*
3774 * call-seq:
3775 * ec == other -> true or false
3776 */
3777static VALUE
3778econv_equal(VALUE self, VALUE other)
3779{
3780 rb_econv_t *ec1 = check_econv(self);
3781 rb_econv_t *ec2;
3782 int i;
3783
3784 if (!rb_typeddata_is_kind_of(other, &econv_data_type)) {
3785 return Qnil;
3786 }
3787 ec2 = DATA_PTR(other);
3788 if (!ec2) return Qfalse;
3789 if (ec1->source_encoding_name != ec2->source_encoding_name &&
3790 strcmp(ec1->source_encoding_name, ec2->source_encoding_name))
3791 return Qfalse;
3792 if (ec1->destination_encoding_name != ec2->destination_encoding_name &&
3793 strcmp(ec1->destination_encoding_name, ec2->destination_encoding_name))
3794 return Qfalse;
3795 if (ec1->flags != ec2->flags) return Qfalse;
3796 if (ec1->replacement_enc != ec2->replacement_enc &&
3797 strcmp(ec1->replacement_enc, ec2->replacement_enc))
3798 return Qfalse;
3799 if (ec1->replacement_len != ec2->replacement_len) return Qfalse;
3800 if (ec1->replacement_str != ec2->replacement_str &&
3801 memcmp(ec1->replacement_str, ec2->replacement_str, ec2->replacement_len))
3802 return Qfalse;
3803
3804 if (ec1->num_trans != ec2->num_trans) return Qfalse;
3805 for (i = 0; i < ec1->num_trans; i++) {
3806 if (ec1->elems[i].tc->transcoder != ec2->elems[i].tc->transcoder)
3807 return Qfalse;
3808 }
3809 return Qtrue;
3810}
3811
3812static VALUE
3813econv_result_to_symbol(rb_econv_result_t res)
3814{
3815 switch (res) {
3816 case econv_invalid_byte_sequence: return sym_invalid_byte_sequence;
3817 case econv_incomplete_input: return sym_incomplete_input;
3818 case econv_undefined_conversion: return sym_undefined_conversion;
3819 case econv_destination_buffer_full: return sym_destination_buffer_full;
3820 case econv_source_buffer_empty: return sym_source_buffer_empty;
3821 case econv_finished: return sym_finished;
3822 case econv_after_output: return sym_after_output;
3823 default: return INT2NUM(res); /* should not be reached */
3824 }
3825}
3826
3827/*
3828 * call-seq:
3829 * ec.primitive_convert(source_buffer, destination_buffer) -> symbol
3830 * ec.primitive_convert(source_buffer, destination_buffer, destination_byteoffset) -> symbol
3831 * ec.primitive_convert(source_buffer, destination_buffer, destination_byteoffset, destination_bytesize) -> symbol
3832 * ec.primitive_convert(source_buffer, destination_buffer, destination_byteoffset, destination_bytesize, opt) -> symbol
3833 *
3834 * possible opt elements:
3835 * hash form:
3836 * :partial_input => true # source buffer may be part of larger source
3837 * :after_output => true # stop conversion after output before input
3838 * integer form:
3839 * Encoding::Converter::PARTIAL_INPUT
3840 * Encoding::Converter::AFTER_OUTPUT
3841 *
3842 * possible results:
3843 * :invalid_byte_sequence
3844 * :incomplete_input
3845 * :undefined_conversion
3846 * :after_output
3847 * :destination_buffer_full
3848 * :source_buffer_empty
3849 * :finished
3850 *
3851 * primitive_convert converts source_buffer into destination_buffer.
3852 *
3853 * source_buffer should be a string or nil.
3854 * nil means an empty string.
3855 *
3856 * destination_buffer should be a string.
3857 *
3858 * destination_byteoffset should be an integer or nil.
3859 * nil means the end of destination_buffer.
3860 * If it is omitted, nil is assumed.
3861 *
3862 * destination_bytesize should be an integer or nil.
3863 * nil means unlimited.
3864 * If it is omitted, nil is assumed.
3865 *
3866 * opt should be nil, a hash or an integer.
3867 * nil means no flags.
3868 * If it is omitted, nil is assumed.
3869 *
3870 * primitive_convert converts the content of source_buffer from beginning
3871 * and store the result into destination_buffer.
3872 *
3873 * destination_byteoffset and destination_bytesize specify the region which
3874 * the converted result is stored.
3875 * destination_byteoffset specifies the start position in destination_buffer in bytes.
3876 * If destination_byteoffset is nil,
3877 * destination_buffer.bytesize is used for appending the result.
3878 * destination_bytesize specifies maximum number of bytes.
3879 * If destination_bytesize is nil,
3880 * destination size is unlimited.
3881 * After conversion, destination_buffer is resized to
3882 * destination_byteoffset + actually produced number of bytes.
3883 * Also destination_buffer's encoding is set to destination_encoding.
3884 *
3885 * primitive_convert drops the converted part of source_buffer.
3886 * the dropped part is converted in destination_buffer or
3887 * buffered in Encoding::Converter object.
3888 *
3889 * primitive_convert stops conversion when one of following condition met.
3890 * - invalid byte sequence found in source buffer (:invalid_byte_sequence)
3891 * +primitive_errinfo+ and +last_error+ methods returns the detail of the error.
3892 * - unexpected end of source buffer (:incomplete_input)
3893 * this occur only when :partial_input is not specified.
3894 * +primitive_errinfo+ and +last_error+ methods returns the detail of the error.
3895 * - character not representable in output encoding (:undefined_conversion)
3896 * +primitive_errinfo+ and +last_error+ methods returns the detail of the error.
3897 * - after some output is generated, before input is done (:after_output)
3898 * this occur only when :after_output is specified.
3899 * - destination buffer is full (:destination_buffer_full)
3900 * this occur only when destination_bytesize is non-nil.
3901 * - source buffer is empty (:source_buffer_empty)
3902 * this occur only when :partial_input is specified.
3903 * - conversion is finished (:finished)
3904 *
3905 * example:
3906 * ec = Encoding::Converter.new("UTF-8", "UTF-16BE")
3907 * ret = ec.primitive_convert(src="pi", dst="", nil, 100)
3908 * p [ret, src, dst] #=> [:finished, "", "\x00p\x00i"]
3909 *
3910 * ec = Encoding::Converter.new("UTF-8", "UTF-16BE")
3911 * ret = ec.primitive_convert(src="pi", dst="", nil, 1)
3912 * p [ret, src, dst] #=> [:destination_buffer_full, "i", "\x00"]
3913 * ret = ec.primitive_convert(src, dst="", nil, 1)
3914 * p [ret, src, dst] #=> [:destination_buffer_full, "", "p"]
3915 * ret = ec.primitive_convert(src, dst="", nil, 1)
3916 * p [ret, src, dst] #=> [:destination_buffer_full, "", "\x00"]
3917 * ret = ec.primitive_convert(src, dst="", nil, 1)
3918 * p [ret, src, dst] #=> [:finished, "", "i"]
3919 *
3920 */
3921static VALUE
3922econv_primitive_convert(int argc, VALUE *argv, VALUE self)
3923{
3924 VALUE input, output, output_byteoffset_v, output_bytesize_v, opt, flags_v;
3925 rb_econv_t *ec = check_econv(self);
3927 const unsigned char *ip, *is;
3928 unsigned char *op, *os;
3929 rb_len_t output_byteoffset, output_bytesize;
3930 rb_ulen_t output_byteend;
3931 int flags;
3932
3933 argc = rb_scan_args(argc, argv, "23:", &input, &output, &output_byteoffset_v, &output_bytesize_v, &flags_v, &opt);
3934
3935 if (NIL_P(output_byteoffset_v))
3936 output_byteoffset = 0; /* dummy */
3937 else
3938 output_byteoffset = NUM2LEN(output_byteoffset_v);
3939
3940 if (NIL_P(output_bytesize_v))
3941 output_bytesize = 0; /* dummy */
3942 else
3943 output_bytesize = NUM2LEN(output_bytesize_v);
3944
3945 if (!NIL_P(flags_v)) {
3946 if (!NIL_P(opt)) {
3947 rb_error_arity(argc + 1, 2, 5);
3948 }
3949 flags = NUM2INT(rb_to_int(flags_v));
3950 }
3951 else if (!NIL_P(opt)) {
3952 VALUE v;
3953 flags = 0;
3954 v = rb_hash_aref(opt, sym_partial_input);
3955 if (RTEST(v))
3956 flags |= ECONV_PARTIAL_INPUT;
3957 v = rb_hash_aref(opt, sym_after_output);
3958 if (RTEST(v))
3959 flags |= ECONV_AFTER_OUTPUT;
3960 }
3961 else {
3962 flags = 0;
3963 }
3964
3965 StringValue(output);
3966 if (!NIL_P(input))
3967 StringValue(input);
3968 rb_str_modify(output);
3969 if (input == output) {
3970 rb_raise(rb_eArgError, "cannot convert into the source string");
3971 }
3972
3973 if (NIL_P(output_bytesize_v)) {
3974 output_bytesize = rb_str_capacity(output);
3975
3976 if (!NIL_P(input) && output_bytesize < RSTRING_LEN(input))
3977 output_bytesize = RSTRING_LEN(input);
3978 }
3979
3980 retry:
3981
3982 if (NIL_P(output_byteoffset_v))
3983 output_byteoffset = RSTRING_LEN(output);
3984
3985 if (output_byteoffset < 0)
3986 rb_raise(rb_eArgError, "negative output_byteoffset");
3987
3988 if (RSTRING_LEN(output) < output_byteoffset)
3989 rb_raise(rb_eArgError, "output_byteoffset too big");
3990
3991 if (output_bytesize < 0)
3992 rb_raise(rb_eArgError, "negative output_bytesize");
3993
3994 output_byteend = (rb_ulen_t)output_byteoffset +
3995 (rb_ulen_t)output_bytesize;
3996
3997 if (output_byteend < (rb_ulen_t)output_byteoffset ||
3998 RB_LEN_MAX < output_byteend)
3999 rb_raise(rb_eArgError, "output_byteoffset+output_bytesize too big");
4000
4001 if (rb_str_capacity(output) < output_byteend)
4002 rb_str_resize(output, output_byteend);
4003
4004 if (NIL_P(input)) {
4005 ip = is = NULL;
4006 }
4007 else {
4008 ip = (const unsigned char *)RSTRING_PTR(input);
4009 is = ip + RSTRING_LEN(input);
4010 }
4011
4012 op = (unsigned char *)RSTRING_PTR(output) + output_byteoffset;
4013 os = op + output_bytesize;
4014
4015 res = rb_econv_convert(ec, &ip, is, &op, os, flags);
4016 rb_str_set_len(output, op-(unsigned char *)RSTRING_PTR(output));
4017 if (!NIL_P(input)) {
4018 rb_str_drop_bytes(input, ip - (unsigned char *)RSTRING_PTR(input));
4019 }
4020
4021 if (NIL_P(output_bytesize_v) && res == econv_destination_buffer_full) {
4022 if (RB_LEN_MAX / 2 < output_bytesize)
4023 rb_raise(rb_eArgError, "too long conversion result");
4024 output_bytesize *= 2;
4025 output_byteoffset_v = Qnil;
4026 goto retry;
4027 }
4028
4029 if (ec->destination_encoding) {
4030 rb_enc_associate(output, ec->destination_encoding);
4031 }
4032
4033 return econv_result_to_symbol(res);
4034}
4035
4036/*
4037 * call-seq:
4038 * ec.convert(source_string) -> destination_string
4039 *
4040 * Convert source_string and return destination_string.
4041 *
4042 * source_string is assumed as a part of source.
4043 * i.e. :partial_input=>true is specified internally.
4044 * finish method should be used last.
4045 *
4046 * ec = Encoding::Converter.new("utf-8", "euc-jp")
4047 * puts ec.convert("\u3042").dump #=> "\xA4\xA2"
4048 * puts ec.finish.dump #=> ""
4049 *
4050 * ec = Encoding::Converter.new("euc-jp", "utf-8")
4051 * puts ec.convert("\xA4").dump #=> ""
4052 * puts ec.convert("\xA2").dump #=> "\xE3\x81\x82"
4053 * puts ec.finish.dump #=> ""
4054 *
4055 * ec = Encoding::Converter.new("utf-8", "iso-2022-jp")
4056 * puts ec.convert("\xE3").dump #=> "".force_encoding("ISO-2022-JP")
4057 * puts ec.convert("\x81").dump #=> "".force_encoding("ISO-2022-JP")
4058 * puts ec.convert("\x82").dump #=> "\e$B$\"".force_encoding("ISO-2022-JP")
4059 * puts ec.finish.dump #=> "\e(B".force_encoding("ISO-2022-JP")
4060 *
4061 * If a conversion error occur,
4062 * Encoding::UndefinedConversionError or
4063 * Encoding::InvalidByteSequenceError is raised.
4064 * Encoding::Converter#convert doesn't supply methods to recover or restart
4065 * from these exceptions.
4066 * When you want to handle these conversion errors,
4067 * use Encoding::Converter#primitive_convert.
4068 *
4069 */
4070static VALUE
4071econv_convert(VALUE self, VALUE source_string)
4072{
4073 VALUE ret, dst;
4074 VALUE av[5];
4075 int ac;
4076 rb_econv_t *ec = check_econv(self);
4077
4078 StringValue(source_string);
4079
4080 dst = rb_str_new(NULL, 0);
4081
4082 av[0] = rb_str_dup(source_string);
4083 av[1] = dst;
4084 av[2] = Qnil;
4085 av[3] = Qnil;
4087 ac = 5;
4088
4089 ret = econv_primitive_convert(ac, av, self);
4090
4091 if (ret == sym_invalid_byte_sequence ||
4092 ret == sym_undefined_conversion ||
4093 ret == sym_incomplete_input) {
4094 VALUE exc = make_econv_exception(ec);
4095 rb_exc_raise(exc);
4096 }
4097
4098 if (ret == sym_finished) {
4099 rb_raise(rb_eArgError, "converter already finished");
4100 }
4101
4102 if (ret != sym_source_buffer_empty) {
4103 rb_bug("unexpected result of econv_primitive_convert");
4104 }
4105
4106 return dst;
4107}
4108
4109/*
4110 * call-seq:
4111 * ec.finish -> string
4112 *
4113 * Finishes the converter.
4114 * It returns the last part of the converted string.
4115 *
4116 * ec = Encoding::Converter.new("utf-8", "iso-2022-jp")
4117 * p ec.convert("\u3042") #=> "\e$B$\""
4118 * p ec.finish #=> "\e(B"
4119 */
4120static VALUE
4121econv_finish(VALUE self)
4122{
4123 VALUE ret, dst;
4124 VALUE av[5];
4125 int ac;
4126 rb_econv_t *ec = check_econv(self);
4127
4128 dst = rb_str_new(NULL, 0);
4129
4130 av[0] = Qnil;
4131 av[1] = dst;
4132 av[2] = Qnil;
4133 av[3] = Qnil;
4134 av[4] = INT2FIX(0);
4135 ac = 5;
4136
4137 ret = econv_primitive_convert(ac, av, self);
4138
4139 if (ret == sym_invalid_byte_sequence ||
4140 ret == sym_undefined_conversion ||
4141 ret == sym_incomplete_input) {
4142 VALUE exc = make_econv_exception(ec);
4143 rb_exc_raise(exc);
4144 }
4145
4146 if (ret != sym_finished) {
4147 rb_bug("unexpected result of econv_primitive_convert");
4148 }
4149
4150 return dst;
4151}
4152
4153/*
4154 * call-seq:
4155 * ec.primitive_errinfo -> array
4156 *
4157 * primitive_errinfo returns important information regarding the last error
4158 * as a 5-element array:
4159 *
4160 * [result, enc1, enc2, error_bytes, readagain_bytes]
4161 *
4162 * result is the last result of primitive_convert.
4163 *
4164 * Other elements are only meaningful when result is
4165 * :invalid_byte_sequence, :incomplete_input or :undefined_conversion.
4166 *
4167 * enc1 and enc2 indicate a conversion step as a pair of strings.
4168 * For example, a converter from EUC-JP to ISO-8859-1 converts
4169 * a string as follows: EUC-JP -> UTF-8 -> ISO-8859-1.
4170 * So [enc1, enc2] is either ["EUC-JP", "UTF-8"] or ["UTF-8", "ISO-8859-1"].
4171 *
4172 * error_bytes and readagain_bytes indicate the byte sequences which caused the error.
4173 * error_bytes is discarded portion.
4174 * readagain_bytes is buffered portion which is read again on next conversion.
4175 *
4176 * Example:
4177 *
4178 * # \xff is invalid as EUC-JP.
4179 * ec = Encoding::Converter.new("EUC-JP", "Shift_JIS")
4180 * ec.primitive_convert(src="\xff", dst="", nil, 10)
4181 * p ec.primitive_errinfo
4182 * #=> [:invalid_byte_sequence, "EUC-JP", "Shift_JIS", "\xFF", ""]
4183 *
4184 * # HIRAGANA LETTER A (\xa4\xa2 in EUC-JP) is not representable in ISO-8859-1.
4185 * # Since this error is occur in UTF-8 to ISO-8859-1 conversion,
4186 * # error_bytes is HIRAGANA LETTER A in UTF-8 (\xE3\x81\x82).
4187 * ec = Encoding::Converter.new("EUC-JP", "ISO-8859-1")
4188 * ec.primitive_convert(src="\xa4\xa2", dst="", nil, 10)
4189 * p ec.primitive_errinfo
4190 * #=> [:undefined_conversion, "UTF-8", "ISO-8859-1", "\xE3\x81\x82", ""]
4191 *
4192 * # partial character is invalid
4193 * ec = Encoding::Converter.new("EUC-JP", "ISO-8859-1")
4194 * ec.primitive_convert(src="\xa4", dst="", nil, 10)
4195 * p ec.primitive_errinfo
4196 * #=> [:incomplete_input, "EUC-JP", "UTF-8", "\xA4", ""]
4197 *
4198 * # Encoding::Converter::PARTIAL_INPUT prevents invalid errors by
4199 * # partial characters.
4200 * ec = Encoding::Converter.new("EUC-JP", "ISO-8859-1")
4201 * ec.primitive_convert(src="\xa4", dst="", nil, 10, Encoding::Converter::PARTIAL_INPUT)
4202 * p ec.primitive_errinfo
4203 * #=> [:source_buffer_empty, nil, nil, nil, nil]
4204 *
4205 * # \xd8\x00\x00@ is invalid as UTF-16BE because
4206 * # no low surrogate after high surrogate (\xd8\x00).
4207 * # It is detected by 3rd byte (\00) which is part of next character.
4208 * # So the high surrogate (\xd8\x00) is discarded and
4209 * # the 3rd byte is read again later.
4210 * # Since the byte is buffered in ec, it is dropped from src.
4211 * ec = Encoding::Converter.new("UTF-16BE", "UTF-8")
4212 * ec.primitive_convert(src="\xd8\x00\x00@", dst="", nil, 10)
4213 * p ec.primitive_errinfo
4214 * #=> [:invalid_byte_sequence, "UTF-16BE", "UTF-8", "\xD8\x00", "\x00"]
4215 * p src
4216 * #=> "@"
4217 *
4218 * # Similar to UTF-16BE, \x00\xd8@\x00 is invalid as UTF-16LE.
4219 * # The problem is detected by 4th byte.
4220 * ec = Encoding::Converter.new("UTF-16LE", "UTF-8")
4221 * ec.primitive_convert(src="\x00\xd8@\x00", dst="", nil, 10)
4222 * p ec.primitive_errinfo
4223 * #=> [:invalid_byte_sequence, "UTF-16LE", "UTF-8", "\x00\xD8", "@\x00"]
4224 * p src
4225 * #=> ""
4226 *
4227 */
4228static VALUE
4229econv_primitive_errinfo(VALUE self)
4230{
4231 rb_econv_t *ec = check_econv(self);
4232
4233 VALUE ary;
4234
4235 ary = rb_ary_new2(5);
4236
4237 rb_ary_store(ary, 0, econv_result_to_symbol(ec->last_error.result));
4238 rb_ary_store(ary, 4, Qnil);
4239
4240 if (ec->last_error.source_encoding)
4241 rb_ary_store(ary, 1, rb_str_new2(ec->last_error.source_encoding));
4242
4243 if (ec->last_error.destination_encoding)
4244 rb_ary_store(ary, 2, rb_str_new2(ec->last_error.destination_encoding));
4245
4246 if (ec->last_error.error_bytes_start) {
4247 rb_ary_store(ary, 3, rb_str_new((const char *)ec->last_error.error_bytes_start, ec->last_error.error_bytes_len));
4248 rb_ary_store(ary, 4, rb_str_new((const char *)ec->last_error.error_bytes_start + ec->last_error.error_bytes_len, ec->last_error.readagain_len));
4249 }
4250
4251 return ary;
4252}
4253
4254/*
4255 * call-seq:
4256 * ec.insert_output(string) -> nil
4257 *
4258 * Inserts string into the encoding converter.
4259 * The string will be converted to the destination encoding and
4260 * output on later conversions.
4261 *
4262 * If the destination encoding is stateful,
4263 * string is converted according to the state and the state is updated.
4264 *
4265 * This method should be used only when a conversion error occurs.
4266 *
4267 * ec = Encoding::Converter.new("utf-8", "iso-8859-1")
4268 * src = "HIRAGANA LETTER A is \u{3042}."
4269 * dst = ""
4270 * p ec.primitive_convert(src, dst) #=> :undefined_conversion
4271 * puts "[#{dst.dump}, #{src.dump}]" #=> ["HIRAGANA LETTER A is ", "."]
4272 * ec.insert_output("<err>")
4273 * p ec.primitive_convert(src, dst) #=> :finished
4274 * puts "[#{dst.dump}, #{src.dump}]" #=> ["HIRAGANA LETTER A is <err>.", ""]
4275 *
4276 * ec = Encoding::Converter.new("utf-8", "iso-2022-jp")
4277 * src = "\u{306F 3041 3068 2661 3002}" # U+2661 is not representable in iso-2022-jp
4278 * dst = ""
4279 * p ec.primitive_convert(src, dst) #=> :undefined_conversion
4280 * puts "[#{dst.dump}, #{src.dump}]" #=> ["\e$B$O$!$H".force_encoding("ISO-2022-JP"), "\xE3\x80\x82"]
4281 * ec.insert_output "?" # state change required to output "?".
4282 * p ec.primitive_convert(src, dst) #=> :finished
4283 * puts "[#{dst.dump}, #{src.dump}]" #=> ["\e$B$O$!$H\e(B?\e$B!#\e(B".force_encoding("ISO-2022-JP"), ""]
4284 *
4285 */
4286static VALUE
4287econv_insert_output(VALUE self, VALUE string)
4288{
4289 const char *insert_enc;
4290
4291 int ret;
4292
4293 rb_econv_t *ec = check_econv(self);
4294
4295 StringValue(string);
4296 insert_enc = rb_econv_encoding_to_insert_output(ec);
4297 string = rb_str_encode(string, rb_enc_from_encoding(rb_enc_find(insert_enc)), 0, Qnil);
4298
4299 ret = rb_econv_insert_output(ec, (const unsigned char *)RSTRING_PTR(string), RSTRING_LEN(string), insert_enc);
4300 if (ret == -1) {
4301 rb_raise(rb_eArgError, "too big string");
4302 }
4303
4304 return Qnil;
4305}
4306
4307/*
4308 * call-seq:
4309 * ec.putback -> string
4310 * ec.putback(max_numbytes) -> string
4311 *
4312 * Put back the bytes which will be converted.
4313 *
4314 * The bytes are caused by invalid_byte_sequence error.
4315 * When invalid_byte_sequence error, some bytes are discarded and
4316 * some bytes are buffered to be converted later.
4317 * The latter bytes can be put back.
4318 * It can be observed by
4319 * Encoding::InvalidByteSequenceError#readagain_bytes and
4320 * Encoding::Converter#primitive_errinfo.
4321 *
4322 * ec = Encoding::Converter.new("utf-16le", "iso-8859-1")
4323 * src = "\x00\xd8\x61\x00"
4324 * dst = ""
4325 * p ec.primitive_convert(src, dst) #=> :invalid_byte_sequence
4326 * p ec.primitive_errinfo #=> [:invalid_byte_sequence, "UTF-16LE", "UTF-8", "\x00\xD8", "a\x00"]
4327 * p ec.putback #=> "a\x00"
4328 * p ec.putback #=> "" # no more bytes to put back
4329 *
4330 */
4331static VALUE
4332econv_putback(int argc, VALUE *argv, VALUE self)
4333{
4334 rb_econv_t *ec = check_econv(self);
4335 int n;
4336 int putbackable;
4337 VALUE str, max;
4338
4339 if (!rb_check_arity(argc, 0, 1) || NIL_P(max = argv[0])) {
4340 n = rb_econv_putbackable(ec);
4341 }
4342 else {
4343 n = NUM2INT(max);
4344 putbackable = rb_econv_putbackable(ec);
4345 if (putbackable < n)
4346 n = putbackable;
4347 }
4348
4349 str = rb_str_new(NULL, n);
4350 rb_econv_putback(ec, (unsigned char *)RSTRING_PTR(str), n);
4351
4352 if (ec->source_encoding) {
4353 rb_enc_associate(str, ec->source_encoding);
4354 }
4355
4356 return str;
4357}
4358
4359/*
4360 * call-seq:
4361 * ec.last_error -> exception or nil
4362 *
4363 * Returns an exception object for the last conversion.
4364 * Returns nil if the last conversion did not produce an error.
4365 *
4366 * "error" means that
4367 * Encoding::InvalidByteSequenceError and Encoding::UndefinedConversionError for
4368 * Encoding::Converter#convert and
4369 * :invalid_byte_sequence, :incomplete_input and :undefined_conversion for
4370 * Encoding::Converter#primitive_convert.
4371 *
4372 * ec = Encoding::Converter.new("utf-8", "iso-8859-1")
4373 * p ec.primitive_convert(src="\xf1abcd", dst="") #=> :invalid_byte_sequence
4374 * p ec.last_error #=> #<Encoding::InvalidByteSequenceError: "\xF1" followed by "a" on UTF-8>
4375 * p ec.primitive_convert(src, dst, nil, 1) #=> :destination_buffer_full
4376 * p ec.last_error #=> nil
4377 *
4378 */
4379static VALUE
4380econv_last_error(VALUE self)
4381{
4382 rb_econv_t *ec = check_econv(self);
4383 VALUE exc;
4384
4385 exc = make_econv_exception(ec);
4386 if (NIL_P(exc))
4387 return Qnil;
4388 return exc;
4389}
4390
4391/*
4392 * call-seq:
4393 * ec.replacement -> string
4394 *
4395 * Returns the replacement string.
4396 *
4397 * ec = Encoding::Converter.new("euc-jp", "us-ascii")
4398 * p ec.replacement #=> "?"
4399 *
4400 * ec = Encoding::Converter.new("euc-jp", "utf-8")
4401 * p ec.replacement #=> "\uFFFD"
4402 */
4403static VALUE
4404econv_get_replacement(VALUE self)
4405{
4406 rb_econv_t *ec = check_econv(self);
4407 int ret;
4408 rb_encoding *enc;
4409
4410 ret = make_replacement(ec);
4411 if (ret == -1) {
4412 rb_raise(rb_eUndefinedConversionError, "replacement character setup failed");
4413 }
4414
4415 enc = rb_enc_find(ec->replacement_enc);
4416 return rb_enc_str_new((const char *)ec->replacement_str, (rb_len_t)ec->replacement_len, enc);
4417}
4418
4419/*
4420 * call-seq:
4421 * ec.replacement = string
4422 *
4423 * Sets the replacement string.
4424 *
4425 * ec = Encoding::Converter.new("utf-8", "us-ascii", :undef => :replace)
4426 * ec.replacement = "<undef>"
4427 * p ec.convert("a \u3042 b") #=> "a <undef> b"
4428 */
4429static VALUE
4430econv_set_replacement(VALUE self, VALUE arg)
4431{
4432 rb_econv_t *ec = check_econv(self);
4433 VALUE string = arg;
4434 int ret;
4435 rb_encoding *enc;
4436
4437 StringValue(string);
4438 enc = rb_enc_get(string);
4439
4440 ret = rb_econv_set_replacement(ec,
4441 (const unsigned char *)RSTRING_PTR(string),
4442 RSTRING_LEN(string),
4443 rb_enc_name(enc));
4444
4445 if (ret == -1) {
4446 /* xxx: rb_eInvalidByteSequenceError? */
4447 rb_raise(rb_eUndefinedConversionError, "replacement character setup failed");
4448 }
4449
4450 return arg;
4451}
4452
4453VALUE
4455{
4456 return make_econv_exception(ec);
4457}
4458
4459void
4461{
4462 VALUE exc;
4463
4464 exc = make_econv_exception(ec);
4465 if (NIL_P(exc))
4466 return;
4467 rb_exc_raise(exc);
4468}
4469
4470/*
4471 * call-seq:
4472 * ecerr.source_encoding_name -> string
4473 *
4474 * Returns the source encoding name as a string.
4475 */
4476static VALUE
4477ecerr_source_encoding_name(VALUE self)
4478{
4479 return rb_attr_get(self, id_source_encoding_name);
4480}
4481
4482/*
4483 * call-seq:
4484 * ecerr.source_encoding -> encoding
4485 *
4486 * Returns the source encoding as an encoding object.
4487 *
4488 * Note that the result may not be equal to the source encoding of
4489 * the encoding converter if the conversion has multiple steps.
4490 *
4491 * ec = Encoding::Converter.new("ISO-8859-1", "EUC-JP") # ISO-8859-1 -> UTF-8 -> EUC-JP
4492 * begin
4493 * ec.convert("\xa0") # NO-BREAK SPACE, which is available in UTF-8 but not in EUC-JP.
4494 * rescue Encoding::UndefinedConversionError
4495 * p $!.source_encoding #=> #<Encoding:UTF-8>
4496 * p $!.destination_encoding #=> #<Encoding:EUC-JP>
4497 * p $!.source_encoding_name #=> "UTF-8"
4498 * p $!.destination_encoding_name #=> "EUC-JP"
4499 * end
4500 *
4501 */
4502static VALUE
4503ecerr_source_encoding(VALUE self)
4504{
4505 return rb_attr_get(self, id_source_encoding);
4506}
4507
4508/*
4509 * call-seq:
4510 * ecerr.destination_encoding_name -> string
4511 *
4512 * Returns the destination encoding name as a string.
4513 */
4514static VALUE
4515ecerr_destination_encoding_name(VALUE self)
4516{
4517 return rb_attr_get(self, id_destination_encoding_name);
4518}
4519
4520/*
4521 * call-seq:
4522 * ecerr.destination_encoding -> string
4523 *
4524 * Returns the destination encoding as an encoding object.
4525 */
4526static VALUE
4527ecerr_destination_encoding(VALUE self)
4528{
4529 return rb_attr_get(self, id_destination_encoding);
4530}
4531
4532/*
4533 * call-seq:
4534 * ecerr.error_char -> string
4535 *
4536 * Returns the one-character string which cause Encoding::UndefinedConversionError.
4537 *
4538 * ec = Encoding::Converter.new("ISO-8859-1", "EUC-JP")
4539 * begin
4540 * ec.convert("\xa0")
4541 * rescue Encoding::UndefinedConversionError
4542 * puts $!.error_char.dump #=> "\xC2\xA0"
4543 * p $!.error_char.encoding #=> #<Encoding:UTF-8>
4544 * end
4545 *
4546 */
4547static VALUE
4548ecerr_error_char(VALUE self)
4549{
4550 return rb_attr_get(self, id_error_char);
4551}
4552
4553/*
4554 * call-seq:
4555 * ecerr.error_bytes -> string
4556 *
4557 * Returns the discarded bytes when Encoding::InvalidByteSequenceError occurs.
4558 *
4559 * ec = Encoding::Converter.new("EUC-JP", "ISO-8859-1")
4560 * begin
4561 * ec.convert("abc\xA1\xFFdef")
4562 * rescue Encoding::InvalidByteSequenceError
4563 * p $! #=> #<Encoding::InvalidByteSequenceError: "\xA1" followed by "\xFF" on EUC-JP>
4564 * puts $!.error_bytes.dump #=> "\xA1"
4565 * puts $!.readagain_bytes.dump #=> "\xFF"
4566 * end
4567 */
4568static VALUE
4569ecerr_error_bytes(VALUE self)
4570{
4571 return rb_attr_get(self, id_error_bytes);
4572}
4573
4574/*
4575 * call-seq:
4576 * ecerr.readagain_bytes -> string
4577 *
4578 * Returns the bytes to be read again when Encoding::InvalidByteSequenceError occurs.
4579 */
4580static VALUE
4581ecerr_readagain_bytes(VALUE self)
4582{
4583 return rb_attr_get(self, id_readagain_bytes);
4584}
4585
4586/*
4587 * call-seq:
4588 * ecerr.incomplete_input? -> true or false
4589 *
4590 * Returns true if the invalid byte sequence error is caused by
4591 * premature end of string.
4592 *
4593 * ec = Encoding::Converter.new("EUC-JP", "ISO-8859-1")
4594 *
4595 * begin
4596 * ec.convert("abc\xA1z")
4597 * rescue Encoding::InvalidByteSequenceError
4598 * p $! #=> #<Encoding::InvalidByteSequenceError: "\xA1" followed by "z" on EUC-JP>
4599 * p $!.incomplete_input? #=> false
4600 * end
4601 *
4602 * begin
4603 * ec.convert("abc\xA1")
4604 * ec.finish
4605 * rescue Encoding::InvalidByteSequenceError
4606 * p $! #=> #<Encoding::InvalidByteSequenceError: incomplete "\xA1" on EUC-JP>
4607 * p $!.incomplete_input? #=> true
4608 * end
4609 */
4610static VALUE
4611ecerr_incomplete_input(VALUE self)
4612{
4613 return rb_attr_get(self, id_incomplete_input);
4614}
4615
4616/*
4617 * Document-class: Encoding::UndefinedConversionError
4618 *
4619 * Raised by Encoding and String methods when a transcoding operation
4620 * fails.
4621 */
4622
4623/*
4624 * Document-class: Encoding::InvalidByteSequenceError
4625 *
4626 * Raised by Encoding and String methods when the string being
4627 * transcoded contains a byte invalid for the either the source or
4628 * target encoding.
4629 */
4630
4631/*
4632 * Document-class: Encoding::ConverterNotFoundError
4633 *
4634 * Raised by transcoding methods when a named encoding does not
4635 * correspond with a known converter.
4636 */
4637
4638void
4639Init_transcode(void)
4640{
4641 transcoder_table = st_init_strcasetable();
4642
4643 id_destination_encoding = rb_intern_const("destination_encoding");
4644 id_destination_encoding_name = rb_intern_const("destination_encoding_name");
4645 id_error_bytes = rb_intern_const("error_bytes");
4646 id_error_char = rb_intern_const("error_char");
4647 id_incomplete_input = rb_intern_const("incomplete_input");
4648 id_readagain_bytes = rb_intern_const("readagain_bytes");
4649 id_source_encoding = rb_intern_const("source_encoding");
4650 id_source_encoding_name = rb_intern_const("source_encoding_name");
4651
4652 sym_invalid = ID2SYM(rb_intern_const("invalid"));
4653 sym_undef = ID2SYM(rb_intern_const("undef"));
4654 sym_replace = ID2SYM(rb_intern_const("replace"));
4655 sym_fallback = ID2SYM(rb_intern_const("fallback"));
4656 sym_xml = ID2SYM(rb_intern_const("xml"));
4657 sym_text = ID2SYM(rb_intern_const("text"));
4658 sym_attr = ID2SYM(rb_intern_const("attr"));
4659
4660 sym_invalid_byte_sequence = ID2SYM(rb_intern_const("invalid_byte_sequence"));
4661 sym_undefined_conversion = ID2SYM(rb_intern_const("undefined_conversion"));
4662 sym_destination_buffer_full = ID2SYM(rb_intern_const("destination_buffer_full"));
4663 sym_source_buffer_empty = ID2SYM(rb_intern_const("source_buffer_empty"));
4664 sym_finished = ID2SYM(rb_intern_const("finished"));
4665 sym_after_output = ID2SYM(rb_intern_const("after_output"));
4666 sym_incomplete_input = ID2SYM(rb_intern_const("incomplete_input"));
4667 sym_universal_newline = ID2SYM(rb_intern_const("universal_newline"));
4668 sym_crlf_newline = ID2SYM(rb_intern_const("crlf_newline"));
4669 sym_cr_newline = ID2SYM(rb_intern_const("cr_newline"));
4670 sym_lf_newline = ID2SYM(rb_intern("lf_newline"));
4671 sym_partial_input = ID2SYM(rb_intern_const("partial_input"));
4672
4673#ifdef ENABLE_ECONV_NEWLINE_OPTION
4674 sym_newline = ID2SYM(rb_intern_const("newline"));
4675 sym_universal = ID2SYM(rb_intern_const("universal"));
4676 sym_crlf = ID2SYM(rb_intern_const("crlf"));
4677 sym_cr = ID2SYM(rb_intern_const("cr"));
4678 sym_lf = ID2SYM(rb_intern_const("lf"));
4679#endif
4680
4681 InitVM(transcode);
4682}
4683
4684void
4685InitVM_transcode(void)
4686{
4687 rb_eUndefinedConversionError = rb_define_class_under(rb_cEncoding, "UndefinedConversionError", rb_eEncodingError);
4688 rb_eInvalidByteSequenceError = rb_define_class_under(rb_cEncoding, "InvalidByteSequenceError", rb_eEncodingError);
4689 rb_eConverterNotFoundError = rb_define_class_under(rb_cEncoding, "ConverterNotFoundError", rb_eEncodingError);
4690
4691 rb_define_method(rb_cString, "encode", str_encode, -1);
4692 rb_define_method(rb_cString, "encode!", str_encode_bang, -1);
4693
4694 rb_cEncodingConverter = rb_define_class_under(rb_cEncoding, "Converter", rb_cObject);
4695 rb_define_alloc_func(rb_cEncodingConverter, econv_s_allocate);
4696 rb_define_singleton_method(rb_cEncodingConverter, "asciicompat_encoding", econv_s_asciicompat_encoding, 1);
4697 rb_define_singleton_method(rb_cEncodingConverter, "search_convpath", econv_s_search_convpath, -1);
4698 rb_define_method(rb_cEncodingConverter, "initialize", econv_init, -1);
4699 rb_define_method(rb_cEncodingConverter, "inspect", econv_inspect, 0);
4700 rb_define_method(rb_cEncodingConverter, "convpath", econv_convpath, 0);
4701 rb_define_method(rb_cEncodingConverter, "source_encoding", econv_source_encoding, 0);
4702 rb_define_method(rb_cEncodingConverter, "destination_encoding", econv_destination_encoding, 0);
4703 rb_define_method(rb_cEncodingConverter, "primitive_convert", econv_primitive_convert, -1);
4704 rb_define_method(rb_cEncodingConverter, "convert", econv_convert, 1);
4705 rb_define_method(rb_cEncodingConverter, "finish", econv_finish, 0);
4706 rb_define_method(rb_cEncodingConverter, "primitive_errinfo", econv_primitive_errinfo, 0);
4707 rb_define_method(rb_cEncodingConverter, "insert_output", econv_insert_output, 1);
4708 rb_define_method(rb_cEncodingConverter, "putback", econv_putback, -1);
4709 rb_define_method(rb_cEncodingConverter, "last_error", econv_last_error, 0);
4710 rb_define_method(rb_cEncodingConverter, "replacement", econv_get_replacement, 0);
4711 rb_define_method(rb_cEncodingConverter, "replacement=", econv_set_replacement, 1);
4712 rb_define_method(rb_cEncodingConverter, "==", econv_equal, 1);
4713
4714 /*
4715 *Mask for invalid byte sequences
4716 */
4717 rb_define_const(rb_cEncodingConverter, "INVALID_MASK", INT2FIX(ECONV_INVALID_MASK));
4718
4719 /*
4720 * Replace invalid byte sequences
4721 */
4722 rb_define_const(rb_cEncodingConverter, "INVALID_REPLACE", INT2FIX(ECONV_INVALID_REPLACE));
4723
4724 /*
4725 * Mask for a valid character in the source encoding but no related
4726 * character(s) in destination encoding.
4727 */
4728 rb_define_const(rb_cEncodingConverter, "UNDEF_MASK", INT2FIX(ECONV_UNDEF_MASK));
4729
4730 /*
4731 * Replace byte sequences that are undefined in the destination encoding.
4732 */
4733 rb_define_const(rb_cEncodingConverter, "UNDEF_REPLACE", INT2FIX(ECONV_UNDEF_REPLACE));
4734
4735 /*
4736 * Replace byte sequences that are undefined in the destination encoding
4737 * with an XML hexadecimal character reference. This is valid for XML
4738 * conversion.
4739 */
4740 rb_define_const(rb_cEncodingConverter, "UNDEF_HEX_CHARREF", INT2FIX(ECONV_UNDEF_HEX_CHARREF));
4741
4742 /*
4743 * Indicates the source may be part of a larger string. See
4744 * primitive_convert for an example.
4745 */
4746 rb_define_const(rb_cEncodingConverter, "PARTIAL_INPUT", INT2FIX(ECONV_PARTIAL_INPUT));
4747
4748 /*
4749 * Stop converting after some output is complete but before all of the
4750 * input was consumed. See primitive_convert for an example.
4751 */
4752 rb_define_const(rb_cEncodingConverter, "AFTER_OUTPUT", INT2FIX(ECONV_AFTER_OUTPUT));
4753
4754 /*
4755 * Decorator for converting CRLF and CR to LF
4756 */
4757 rb_define_const(rb_cEncodingConverter, "UNIVERSAL_NEWLINE_DECORATOR", INT2FIX(ECONV_UNIVERSAL_NEWLINE_DECORATOR));
4758
4759 /*
4760 * Decorator for converting CRLF and CR to LF when writing
4761 */
4762 rb_define_const(rb_cEncodingConverter, "LF_NEWLINE_DECORATOR", INT2FIX(ECONV_LF_NEWLINE_DECORATOR));
4763
4764 /*
4765 * Decorator for converting LF to CRLF
4766 */
4767 rb_define_const(rb_cEncodingConverter, "CRLF_NEWLINE_DECORATOR", INT2FIX(ECONV_CRLF_NEWLINE_DECORATOR));
4768
4769 /*
4770 * Decorator for converting LF to CR
4771 */
4772 rb_define_const(rb_cEncodingConverter, "CR_NEWLINE_DECORATOR", INT2FIX(ECONV_CR_NEWLINE_DECORATOR));
4773
4774 /*
4775 * Escape as XML CharData
4776 */
4777 rb_define_const(rb_cEncodingConverter, "XML_TEXT_DECORATOR", INT2FIX(ECONV_XML_TEXT_DECORATOR));
4778
4779 /*
4780 * Escape as XML AttValue
4781 */
4782 rb_define_const(rb_cEncodingConverter, "XML_ATTR_CONTENT_DECORATOR", INT2FIX(ECONV_XML_ATTR_CONTENT_DECORATOR));
4783
4784 /*
4785 * Escape as XML AttValue
4786 */
4787 rb_define_const(rb_cEncodingConverter, "XML_ATTR_QUOTE_DECORATOR", INT2FIX(ECONV_XML_ATTR_QUOTE_DECORATOR));
4788
4789 rb_define_method(rb_eUndefinedConversionError, "source_encoding_name", ecerr_source_encoding_name, 0);
4790 rb_define_method(rb_eUndefinedConversionError, "destination_encoding_name", ecerr_destination_encoding_name, 0);
4791 rb_define_method(rb_eUndefinedConversionError, "source_encoding", ecerr_source_encoding, 0);
4792 rb_define_method(rb_eUndefinedConversionError, "destination_encoding", ecerr_destination_encoding, 0);
4793 rb_define_method(rb_eUndefinedConversionError, "error_char", ecerr_error_char, 0);
4794
4795 rb_define_method(rb_eInvalidByteSequenceError, "source_encoding_name", ecerr_source_encoding_name, 0);
4796 rb_define_method(rb_eInvalidByteSequenceError, "destination_encoding_name", ecerr_destination_encoding_name, 0);
4797 rb_define_method(rb_eInvalidByteSequenceError, "source_encoding", ecerr_source_encoding, 0);
4798 rb_define_method(rb_eInvalidByteSequenceError, "destination_encoding", ecerr_destination_encoding, 0);
4799 rb_define_method(rb_eInvalidByteSequenceError, "error_bytes", ecerr_error_bytes, 0);
4800 rb_define_method(rb_eInvalidByteSequenceError, "readagain_bytes", ecerr_readagain_bytes, 0);
4801 rb_define_method(rb_eInvalidByteSequenceError, "incomplete_input?", ecerr_incomplete_input, 0);
4802
4803 Init_newline();
4804}
ruby_coderange_type
What rb_enc_str_coderange() returns.
Definition coderange.h:33
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3407
#define ECONV_XML_ATTR_QUOTE_DECORATOR
Old name of RUBY_ECONV_XML_ATTR_QUOTE_DECORATOR.
Definition transcode.h:539
#define ECONV_AFTER_OUTPUT
Old name of RUBY_ECONV_AFTER_OUTPUT.
Definition transcode.h:555
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1700
#define ENC_CODERANGE_7BIT
Old name of RUBY_ENC_CODERANGE_7BIT.
Definition coderange.h:180
#define ENC_CODERANGE_VALID
Old name of RUBY_ENC_CODERANGE_VALID.
Definition coderange.h:181
#define ECONV_UNIVERSAL_NEWLINE_DECORATOR
Old name of RUBY_ECONV_UNIVERSAL_NEWLINE_DECORATOR.
Definition transcode.h:532
#define ALLOC
Old name of RB_ALLOC.
Definition memory.h:403
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define OBJ_FROZEN
Old name of RB_OBJ_FROZEN.
Definition fl_type.h:133
#define ECONV_XML_ATTR_CONTENT_DECORATOR
Old name of RUBY_ECONV_XML_ATTR_CONTENT_DECORATOR.
Definition transcode.h:537
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1708
#define ECONV_INVALID_MASK
Old name of RUBY_ECONV_INVALID_MASK.
Definition transcode.h:523
#define ECONV_CRLF_NEWLINE_DECORATOR
Old name of RUBY_ECONV_CRLF_NEWLINE_DECORATOR.
Definition transcode.h:533
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:131
#define ECONV_UNDEF_REPLACE
Old name of RUBY_ECONV_UNDEF_REPLACE.
Definition transcode.h:526
#define ECONV_XML_TEXT_DECORATOR
Old name of RUBY_ECONV_XML_TEXT_DECORATOR.
Definition transcode.h:536
#define ENC_CODERANGE(obj)
Old name of RB_ENC_CODERANGE.
Definition coderange.h:184
#define rb_ary_new4
Old name of rb_ary_new_from_values.
Definition array.h:659
#define ENC_CODERANGE_UNKNOWN
Old name of RUBY_ENC_CODERANGE_UNKNOWN.
Definition coderange.h:179
#define ECONV_CR_NEWLINE_DECORATOR
Old name of RUBY_ECONV_CR_NEWLINE_DECORATOR.
Definition transcode.h:534
#define xmalloc
Old name of ruby_xmalloc.
Definition xmalloc.h:53
#define ECONV_INVALID_REPLACE
Old name of RUBY_ECONV_INVALID_REPLACE.
Definition transcode.h:524
#define T_HASH
Old name of RUBY_T_HASH.
Definition value_type.h:65
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:402
#define MBCLEN_CHARFOUND_LEN(ret)
Old name of ONIGENC_MBCLEN_CHARFOUND_LEN.
Definition encoding.h:517
#define rb_exc_new3
Old name of rb_exc_new_str.
Definition error.h:38
#define ECONV_UNDEF_MASK
Old name of RUBY_ECONV_UNDEF_MASK.
Definition transcode.h:525
#define Qtrue
Old name of RUBY_Qtrue.
#define ECONV_PARTIAL_INPUT
Old name of RUBY_ECONV_PARTIAL_INPUT.
Definition transcode.h:554
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#define ECONV_ERROR_HANDLER_MASK
Old name of RUBY_ECONV_ERROR_HANDLER_MASK.
Definition transcode.h:522
#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 ENC_CODERANGE_BROKEN
Old name of RUBY_ENC_CODERANGE_BROKEN.
Definition coderange.h:182
#define ECONV_LF_NEWLINE_DECORATOR
Old name of RUBY_ECONV_LF_NEWLINE_DECORATOR.
Definition transcode.h:535
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#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 ECONV_UNDEF_HEX_CHARREF
Old name of RUBY_ECONV_UNDEF_HEX_CHARREF.
Definition transcode.h:527
#define NUM2LEN
Old name of RB_NUM2LEN.
Definition len_t.h:34
#define ECONV_NEWLINE_DECORATOR_MASK
Old name of RUBY_ECONV_NEWLINE_DECORATOR_MASK.
Definition transcode.h:529
#define rb_ary_new2
Old name of rb_ary_new_capa.
Definition array.h:657
#define ENC_CODERANGE_SET(obj, cr)
Old name of RB_ENC_CODERANGE_SET.
Definition coderange.h:186
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:679
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1457
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1455
void * rb_check_typeddata(VALUE obj, const rb_data_type_t *data_type)
Identical to rb_typeddata_is_kind_of(), except it raises exceptions instead of returning false.
Definition error.c:1443
VALUE rb_exc_new_str(VALUE etype, VALUE str)
Identical to rb_exc_new_cstr(), except it takes a Ruby's string instead of C's.
Definition error.c:1508
VALUE rb_eEncodingError
EncodingError exception.
Definition error.c:1463
void rb_warning(const char *fmt,...)
Issues a warning.
Definition error.c:495
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:230
VALUE rb_cEncoding
Encoding class.
Definition encoding.c:60
VALUE rb_cString
String class.
Definition string.c:86
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3337
Encoding relates APIs.
rb_encoding * rb_utf8_encoding(void)
Queries the encoding that represents UTF-8.
Definition encoding.c:1638
VALUE rb_enc_default_internal(void)
Identical to rb_default_internal_encoding(), except it returns the Ruby-level counterpart instance of...
Definition encoding.c:1856
int rb_econv_prepare_options(VALUE opthash, VALUE *ecopts, int ecflags)
Identical to rb_econv_prepare_opts(), except it additionally takes the initial value of flags.
Definition transcode.c:2699
VALUE rb_econv_substr_convert(rb_econv_t *ec, VALUE src, rb_len_t byteoff, rb_len_t bytesize, int flags)
Identical to rb_econv_str_convert(), except it converts only a part of the passed string.
Definition transcode.c:1974
VALUE rb_econv_open_exc(const char *senc, const char *denc, int ecflags)
Creates a rb_eConverterNotFoundError exception object (but does not raise).
Definition transcode.c:2144
const char * rb_econv_encoding_to_insert_output(rb_econv_t *ec)
Queries an encoding name which best suits for rb_econv_insert_output()'s last parameter.
Definition transcode.c:1544
int rb_econv_prepare_opts(VALUE opthash, VALUE *ecopts)
Splits a keyword arguments hash (that for instance String#encode took) into a set of enum ruby_econv_...
Definition transcode.c:2744
VALUE rb_econv_substr_append(rb_econv_t *ec, VALUE src, rb_len_t byteoff, rb_len_t bytesize, VALUE dst, int flags)
Identical to rb_econv_str_append(), except it appends only a part of the passed string with conversio...
Definition transcode.c:1959
rb_econv_result_t rb_econv_convert(rb_econv_t *ec, const unsigned char **source_buffer_ptr, const unsigned char *source_buffer_end, unsigned char **destination_buffer_ptr, unsigned char *destination_buffer_end, int flags)
Converts a string from an encoding to another.
Definition transcode.c:1487
rb_econv_result_t
return value of rb_econv_convert()
Definition transcode.h:30
@ econv_incomplete_input
The conversion stopped in middle of reading a character, possibly due to a partial read of a socket e...
Definition transcode.h:69
@ econv_finished
The conversion stopped after converting everything.
Definition transcode.h:57
@ econv_undefined_conversion
The conversion stopped when it found a character in the input which cannot be representable in the ou...
Definition transcode.h:41
@ econv_after_output
The conversion stopped after writing something to somewhere, before reading everything.
Definition transcode.h:63
@ econv_source_buffer_empty
The conversion stopped because there is no input.
Definition transcode.h:51
@ econv_destination_buffer_full
The conversion stopped because there is no destination.
Definition transcode.h:46
@ econv_invalid_byte_sequence
The conversion stopped when it found an invalid sequence.
Definition transcode.h:35
int rb_econv_putbackable(rb_econv_t *ec)
Queries if rb_econv_putback() makes sense, i.e.
Definition transcode.c:1801
int rb_econv_has_convpath_p(const char *from_encoding, const char *to_encoding)
Queries if there is more than one way to convert between the passed two encodings.
Definition transcode.c:3390
rb_econv_t * rb_econv_open(const char *source_encoding, const char *destination_encoding, int ecflags)
Creates a new instance of struct rb_econv_t.
Definition transcode.c:1108
VALUE rb_econv_str_append(rb_econv_t *ec, VALUE src, VALUE dst, int flags)
Identical to rb_econv_str_convert(), except it appends the conversion result to the additionally pass...
Definition transcode.c:1968
const char * rb_econv_asciicompat_encoding(const char *encname)
Queries the passed encoding's corresponding ASCII compatible encoding.
Definition transcode.c:1845
int rb_econv_insert_output(rb_econv_t *ec, const unsigned char *str, size_t len, const char *str_encoding)
Appends the passed string to the passed converter's output buffer.
Definition transcode.c:1638
VALUE rb_econv_str_convert(rb_econv_t *ec, VALUE src, int flags)
Identical to rb_econv_convert(), except it takes Ruby's string instead of C's pointer.
Definition transcode.c:1980
rb_econv_t * rb_econv_open_opts(const char *source_encoding, const char *destination_encoding, int ecflags, VALUE ecopts)
Identical to rb_econv_open(), except it additionally takes a hash of optional strings.
Definition transcode.c:2750
VALUE rb_econv_append(rb_econv_t *ec, const char *bytesrc, rb_len_t bytesize, VALUE dst, int flags)
Converts the passed C's pointer according to the passed converter, then append the conversion result ...
Definition transcode.c:1896
int rb_econv_decorate_at_last(rb_econv_t *ec, const char *decorator_name)
Identical to rb_econv_decorate_at_first(), except it adds to the opposite direction.
Definition transcode.c:2026
void rb_econv_binmode(rb_econv_t *ec)
This badly named function does not set the destination encoding to binary, but instead just nullifies...
Definition transcode.c:2043
int rb_econv_decorate_at_first(rb_econv_t *ec, const char *decorator_name)
"Decorate"s a converter.
Definition transcode.c:2009
VALUE rb_str_encode(VALUE str, VALUE to, int ecflags, VALUE ecopts)
Converts the contents of the passed string from its encoding to the passed one.
Definition transcode.c:3085
VALUE rb_econv_make_exception(rb_econv_t *ec)
This function makes sense right after rb_econv_convert() returns.
Definition transcode.c:4454
void rb_econv_check_error(rb_econv_t *ec)
This is a rb_econv_make_exception() + rb_exc_raise() combo.
Definition transcode.c:4460
void rb_econv_close(rb_econv_t *ec)
Destructs a converter.
Definition transcode.c:1762
void rb_econv_putback(rb_econv_t *ec, unsigned char *p, int n)
Puts back the bytes.
Definition transcode.c:1812
int rb_econv_set_replacement(rb_econv_t *ec, const unsigned char *str, size_t len, const char *encname)
Assigns the replacement string.
Definition transcode.c:2309
VALUE rb_funcallv_public(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcallv(), except it only takes public methods into account.
Definition vm_eval.c:1213
VALUE rb_ary_entry(VALUE ary, rb_len_t off)
Queries an element of an array.
void rb_ary_store(VALUE ary, rb_len_t key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
VALUE rb_check_array_type(VALUE obj)
Try converting an object to its array representation using its to_ary method, if any.
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_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
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_hash_new(void)
Creates a new, empty hash object.
Definition hash.c:1670
VALUE rb_proc_call(VALUE recv, VALUE args)
Evaluates the passed proc with the passed arguments.
Definition proc.c:1751
VALUE rb_obj_is_method(VALUE recv)
Queries if the given object is a method.
Definition proc.c:2477
VALUE rb_method_call(int argc, const VALUE *argv, VALUE recv)
Evaluates the passed method with the passed arguments.
Definition proc.c:3433
VALUE rb_obj_is_proc(VALUE recv)
Queries if the given object is a proc.
Definition proc.c:392
void rb_str_modify_expand(VALUE str, rb_len_t capa)
Identical to rb_str_modify(), except it additionally expands the capacity of the receiver.
Definition string.c:2875
VALUE rb_str_tmp_new(rb_len_t len)
Allocates a "temporary" string.
Definition string.c:1846
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1523
void rb_str_shared_replace(VALUE dst, VALUE src)
Replaces the contents of the former with the latter.
Definition string.c:1888
size_t rb_str_capacity(VALUE str)
Queries the capacity of the given string.
Definition string.c:1048
VALUE rb_str_new_frozen(VALUE str)
Creates a frozen copy of the string, if necessary.
Definition string.c:1602
void rb_str_set_len(VALUE str, rb_len_t len)
Overwrites the length of the string.
Definition string.c:3605
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition string.c:2087
VALUE rb_str_drop_bytes(VALUE str, rb_len_t len)
Shrinks the given string for the given number of bytes.
Definition string.c:6302
VALUE rb_str_buf_new(rb_len_t capa)
Allocates a "string buffer".
Definition string.c:1818
VALUE rb_str_dump(VALUE str)
"Inverse" of rb_eval_string().
Definition string.c:9669
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1539
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:2186
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition vm_method.c:3772
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:285
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:1191
int off
Offset inside of ptr.
Definition io.h:5
int len
Length of the buffer.
Definition io.h:8
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:375
#define ALLOCA_N(type, n)
Definition memory.h:295
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:170
#define MEMMOVE(p1, p2, type, n)
Handy macro to call memmove.
Definition memory.h:387
int st_foreach(st_table *q, int_type *w, st_data_t e)
Iteration over the given table.
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
Definition rarray.h:256
#define RARRAY_AREF(a, i)
References an object in an array.
Definition rarray.h:398
#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:409
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
Definition rstring.h:89
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:773
#define DATA_PTR(obj)
Convenient casting macro for backward compatibility.
Definition rtypeddata.h:439
#define TypedData_Wrap_Struct(klass, data_type, sval)
Converts sval, a pointer to your struct, into a Ruby object.
Definition rtypeddata.h:557
struct rb_data_type_struct rb_data_type_t
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:239
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition variable.c:532
#define InitVM(ext)
This macro is for internal use.
Definition ruby.h:231
#define RTEST
This is an old name of RB_TEST.
Definition st.h:79
Definition string.c:10701
Definition transcode.c:179
long rb_len_t
A signed integer type for lengths and indices of objects such as String and Array.
Definition value.h:142
#define RB_LEN_MAX
Maximum possible value that a rb_len_t can take.
Definition value.h:156
unsigned long rb_ulen_t
An unsigned integer type that has the same width with rb_len_t.
Definition value.h:145
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