Debian Codegraph @

vendor/mruby-source/src/string.c

raw
1 /*
2 ** string.c - String class
3 **
4 ** See Copyright Notice in mruby.h
5 */
6
7 #ifdef _MSC_VER
8 # define _CRT_NONSTDC_NO_DEPRECATE
9 #endif
10
11 #include <mruby.h>
12 #include <mruby/array.h>
13 #include <mruby/class.h>
14 #include <mruby/range.h>
15 #include <mruby/string.h>
16 #include <mruby/numeric.h>
17 #include <mruby/internal.h>
18 #include <mruby/presym.h>
19 #include <string.h>
20
21 typedef struct mrb_shared_string {
22 int refcnt;
23 mrb_int capa;
24 char *ptr;
25 } mrb_shared_string;
26
27 const char mrb_digitmap[] = "0123456789abcdefghijklmnopqrstuvwxyz";
28
29 #define mrb_obj_alloc_string(mrb) MRB_OBJ_ALLOC((mrb), MRB_TT_STRING, (mrb)->string_class)
30
31 #ifndef MRB_STR_LENGTH_MAX
32 #if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__)
33 #define MRB_STR_LENGTH_MAX 0
34 #else
35 #define MRB_STR_LENGTH_MAX 1048576
36 #endif
37 #endif
38
39 static void
40 str_check_length(mrb_state *mrb, mrb_int len)
41 {
42 if (len < 0) {
43 mrb_raise(mrb, E_ARGUMENT_ERROR, "negative (or overflowed) string size");
44 }
45 #if MRB_STR_LENGTH_MAX != 0
46 if (len > MRB_STR_LENGTH_MAX-1) {
47 mrb_raisef(mrb, E_ARGUMENT_ERROR, "string too long (len=%i max=" MRB_STRINGIZE(MRB_STR_LENGTH_MAX) ")", len);
48 }
49 #endif
50 }
51
52 static struct RString*
53 str_init_normal_capa(mrb_state *mrb, struct RString *s,
54 const char *p, mrb_int len, mrb_int capa)
55 {
56 str_check_length(mrb, capa);
57 char *dst = (char*)mrb_malloc(mrb, capa + 1);
58 if (p) memcpy(dst, p, len);
59 dst[len] = '\0';
60 s->as.heap.ptr = dst;
61 s->as.heap.len = len;
62 s->as.heap.aux.capa = capa;
63 RSTR_UNSET_TYPE_FLAG(s);
64 return s;
65 }
66
67 static struct RString*
68 str_init_normal(mrb_state *mrb, struct RString *s, const char *p, mrb_int len)
69 {
70 return str_init_normal_capa(mrb, s, p, len, len);
71 }
72
73 static struct RString*
74 str_init_embed(struct RString *s, const char *p, mrb_int len)
75 {
76 mrb_assert(len >= 0);
77 if (p) memcpy(RSTR_EMBED_PTR(s), p, len);
78 RSTR_EMBED_PTR(s)[len] = '\0';
79 RSTR_SET_TYPE_FLAG(s, EMBED);
80 RSTR_SET_EMBED_LEN(s, len);
81 return s;
82 }
83
84 static struct RString*
85 str_init_nofree(struct RString *s, const char *p, mrb_int len)
86 {
87 s->as.heap.ptr = (char*)p;
88 s->as.heap.len = len;
89 s->as.heap.aux.capa = 0; /* nofree */
90 RSTR_SET_TYPE_FLAG(s, NOFREE);
91 return s;
92 }
93
94 static struct RString*
95 str_init_shared(mrb_state *mrb, const struct RString *orig, struct RString *s, mrb_shared_string *shared)
96 {
97 if (shared) {
98 shared->refcnt++;
99 }
100 else {
101 shared = (mrb_shared_string*)mrb_malloc(mrb, sizeof(mrb_shared_string));
102 shared->refcnt = 1;
103 shared->ptr = orig->as.heap.ptr;
104 shared->capa = orig->as.heap.aux.capa;
105 }
106 s->as.heap.ptr = orig->as.heap.ptr;
107 s->as.heap.len = orig->as.heap.len;
108 s->as.heap.aux.shared = shared;
109 RSTR_SET_TYPE_FLAG(s, SHARED);
110 return s;
111 }
112
113 static struct RString*
114 str_init_fshared(const struct RString *orig, struct RString *s, struct RString *fshared)
115 {
116 s->as.heap.ptr = orig->as.heap.ptr;
117 s->as.heap.len = orig->as.heap.len;
118 s->as.heap.aux.fshared = fshared;
119 RSTR_SET_TYPE_FLAG(s, FSHARED);
120 return s;
121 }
122
123 static struct RString*
124 str_init_modifiable(mrb_state *mrb, struct RString *s, const char *p, mrb_int len)
125 {
126 if (RSTR_EMBEDDABLE_P(len)) {
127 return str_init_embed(s, p, len);
128 }
129 return str_init_normal(mrb, s, p, len);
130 }
131
132 static struct RString*
133 str_new_static(mrb_state *mrb, const char *p, mrb_int len)
134 {
135 if (RSTR_EMBEDDABLE_P(len)) {
136 return str_init_embed(mrb_obj_alloc_string(mrb), p, len);
137 }
138 return str_init_nofree(mrb_obj_alloc_string(mrb), p, len);
139 }
140
141 static struct RString*
142 str_new(mrb_state *mrb, const char *p, mrb_int len)
143 {
144 str_check_length(mrb, len);
145 if (RSTR_EMBEDDABLE_P(len)) {
146 return str_init_embed(mrb_obj_alloc_string(mrb), p, len);
147 }
148 if (p && mrb_ro_data_p(p)) {
149 return str_init_nofree(mrb_obj_alloc_string(mrb), p, len);
150 }
151 return str_init_normal(mrb, mrb_obj_alloc_string(mrb), p, len);
152 }
153
154 MRB_API mrb_value
155 mrb_str_new_capa(mrb_state *mrb, mrb_int capa)
156 {
157 struct RString *s = mrb_obj_alloc_string(mrb);
158
159 if (RSTR_EMBEDDABLE_P(capa)) {
160 s = str_init_embed(s, NULL, 0);
161 }
162 else {
163 s = str_init_normal_capa(mrb, s, NULL, 0, capa);
164 }
165 return mrb_obj_value(s);
166 }
167
168 static void
169 resize_capa(mrb_state *mrb, struct RString *s, mrb_int capacity)
170 {
171 if (RSTR_EMBED_P(s)) {
172 if (!RSTR_EMBEDDABLE_P(capacity)) {
173 str_init_normal_capa(mrb, s, RSTR_EMBED_PTR(s), RSTR_EMBED_LEN(s), capacity);
174 }
175 }
176 else {
177 str_check_length(mrb, capacity);
178 s->as.heap.ptr = (char*)mrb_realloc(mrb, RSTR_PTR(s), capacity+1);
179 s->as.heap.aux.capa = (mrb_ssize)capacity;
180 }
181 }
182
183 MRB_API mrb_value
184 mrb_str_new(mrb_state *mrb, const char *p, mrb_int len)
185 {
186 return mrb_obj_value(str_new(mrb, p, len));
187 }
188
189 MRB_API mrb_value
190 mrb_str_new_cstr(mrb_state *mrb, const char *p)
191 {
192 struct RString *s;
193 mrb_int len;
194
195 if (p) {
196 len = strlen(p);
197 }
198 else {
199 len = 0;
200 }
201
202 s = str_new(mrb, p, len);
203
204 return mrb_obj_value(s);
205 }
206
207 MRB_API mrb_value
208 mrb_str_new_static(mrb_state *mrb, const char *p, mrb_int len)
209 {
210 struct RString *s = str_new_static(mrb, p, len);
211 return mrb_obj_value(s);
212 }
213
214 static void
215 str_decref(mrb_state *mrb, mrb_shared_string *shared)
216 {
217 shared->refcnt--;
218 if (shared->refcnt == 0) {
219 mrb_free(mrb, shared->ptr);
220 mrb_free(mrb, shared);
221 }
222 }
223
224 static void
225 str_modify_keep_ascii(mrb_state *mrb, struct RString *s)
226 {
227 if (RSTR_SHARED_P(s)) {
228 mrb_shared_string *shared = s->as.heap.aux.shared;
229
230 if (shared->refcnt == 1 && s->as.heap.ptr == shared->ptr) {
231 s->as.heap.aux.capa = shared->capa;
232 s->as.heap.ptr[s->as.heap.len] = '\0';
233 RSTR_UNSET_SHARED_FLAG(s);
234 mrb_free(mrb, shared);
235 }
236 else {
237 str_init_modifiable(mrb, s, s->as.heap.ptr, s->as.heap.len);
238 str_decref(mrb, shared);
239 }
240 }
241 else if (RSTR_NOFREE_P(s) || RSTR_FSHARED_P(s)) {
242 str_init_modifiable(mrb, s, s->as.heap.ptr, s->as.heap.len);
243 }
244 }
245
246 static void
247 check_null_byte(mrb_state *mrb, struct RString *str)
248 {
249 const char *p = RSTR_PTR(str);
250 if (p && memchr(p, '\0', RSTR_LEN(str))) {
251 mrb_raise(mrb, E_ARGUMENT_ERROR, "string contains null byte");
252 }
253 }
254
255 void
256 mrb_gc_free_str(mrb_state *mrb, struct RString *str)
257 {
258 if (RSTR_EMBED_P(str))
259 /* no code */;
260 else if (RSTR_SHARED_P(str))
261 str_decref(mrb, str->as.heap.aux.shared);
262 else if (!RSTR_NOFREE_P(str) && !RSTR_FSHARED_P(str))
263 mrb_free(mrb, str->as.heap.ptr);
264 }
265
266 #ifdef MRB_UTF8_STRING
267 #define utf8_islead(c) ((unsigned char)((c)&0xc0) != 0x80)
268
269 extern const char mrb_utf8len_table[];
270 const char mrb_utf8len_table[] = {
271 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
272 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0
273 };
274
275 mrb_int
276 mrb_utf8len(const char* p, const char* e)
277 {
278 mrb_int len = mrb_utf8len_table[(unsigned char)p[0] >> 3];
279 if (len > e - p) return 1;
280 switch (len) {
281 case 1:
282 return 1;
283 case 4:
284 if (utf8_islead(p[3])) return 1;
285 case 3:
286 if (utf8_islead(p[2])) return 1;
287 case 2:
288 if (utf8_islead(p[1])) return 1;
289 }
290 return len;
291 }
292
293 mrb_int
294 mrb_utf8_strlen(const char *str, mrb_int byte_len)
295 {
296 mrb_int len = 0;
297 const char *p = str;
298 const char *e = p + byte_len;
299 while (p < e) {
300 if (utf8_islead(*p)) len++;
301 p++;
302 }
303 return len;
304 }
305
306 static mrb_int
307 utf8_strlen(mrb_value str)
308 {
309 struct RString *s = mrb_str_ptr(str);
310 mrb_int byte_len = RSTR_LEN(s);
311
312 if (RSTR_ASCII_P(s)) {
313 return byte_len;
314 }
315 else {
316 mrb_int utf8_len = mrb_utf8_strlen(RSTR_PTR(s), byte_len);
317 if (byte_len == utf8_len) RSTR_SET_ASCII_FLAG(s);
318 return utf8_len;
319 }
320 }
321
322 #define RSTRING_CHAR_LEN(s) utf8_strlen(s)
323
324 /* map character index to byte offset index */
325 static mrb_int
326 chars2bytes(mrb_value s, mrb_int off, mrb_int idx)
327 {
328 if (RSTR_ASCII_P(mrb_str_ptr(s))) {
329 return idx;
330 }
331 else {
332 mrb_int i, b, n;
333 const char *p = RSTRING_PTR(s) + off;
334 const char *e = RSTRING_END(s);
335
336 for (b=i=0; p<e && i<idx; i++) {
337 n = mrb_utf8len(p, e);
338 b += n;
339 p += n;
340 }
341 return b;
342 }
343 }
344
345 /* map byte offset to character index */
346 static mrb_int
347 bytes2chars(char *p, mrb_int len, mrb_int bi)
348 {
349 const char *e = p + (size_t)len;
350 const char *pivot = p + bi;
351 mrb_int i;
352
353 for (i = 0; p < pivot; i++) {
354 p += mrb_utf8len(p, e);
355 }
356 if (p != pivot) return -1;
357 return i;
358 }
359
360 static const char*
361 char_adjust(const char *beg, const char *end, const char *ptr)
362 {
363 ptrdiff_t len = end - ptr;
364 if (len < 1 || utf8_islead(ptr[0])) return ptr;
365 if (len > 1 && utf8_islead(ptr[1])) return ptr+1;
366 if (len > 2 && utf8_islead(ptr[2])) return ptr+2;
367 if (len > 3 && utf8_islead(ptr[3])) return ptr+3;
368 return ptr;
369 }
370
371 static const char*
372 char_backtrack(const char *ptr, const char *end)
373 {
374 ptrdiff_t len = end - ptr;
375 if (len < 1 || utf8_islead(end[-1])) return end-1;
376 if (len > 1 && utf8_islead(end[-2])) return end-2;
377 if (len > 2 && utf8_islead(end[-3])) return end-3;
378 if (len > 3 && utf8_islead(end[-4])) return end-4;
379 return end - 1;
380 }
381
382 static mrb_int
383 str_index_str_by_char_search(mrb_state *mrb, const char *p, const char *pend, const char *s, const mrb_int slen, mrb_int off)
384 {
385 /* Based on Quick Search algorithm (Boyer-Moore-Horspool algorithm) */
386
387 ptrdiff_t qstable[1 << CHAR_BIT];
388
389 /* Preprocessing */
390 {
391 mrb_int i;
392
393 for (i = 0; i < 1 << CHAR_BIT; i++) {
394 qstable[i] = slen;
395 }
396 for (i = 0; i < slen; i++) {
397 qstable[(unsigned char)s[i]] = slen - (i + 1);
398 }
399 }
400
401 /* Searching */
402 while (p < pend && pend - p >= slen) {
403 const char *pivot;
404
405 if (memcmp(p, s, slen) == 0) {
406 return off;
407 }
408
409 pivot = p + qstable[(unsigned char)p[slen - 1]];
410 if (pivot >= pend || pivot < p /* overflowed */) { return -1; }
411
412 do {
413 p += mrb_utf8len(p, pend);
414 off++;
415 } while (p < pivot);
416 }
417
418 return -1;
419 }
420
421 static mrb_int
422 str_index_str_by_char(mrb_state *mrb, mrb_value str, mrb_value sub, mrb_int pos)
423 {
424 const char *p = RSTRING_PTR(str);
425 const char *pend = p + RSTRING_LEN(str);
426 const char *s = RSTRING_PTR(sub);
427 const mrb_int slen = RSTRING_LEN(sub);
428 mrb_int off = pos;
429
430 for (; pos > 0; pos --) {
431 if (pend - p < 1) { return -1; }
432 p += mrb_utf8len(p, pend);
433 }
434
435 if (slen < 1) { return off; }
436
437 return str_index_str_by_char_search(mrb, p, pend, s, slen, off);
438 }
439
440 #define BYTES_ALIGN_CHECK(pos) if (pos < 0) return mrb_nil_value();
441 #else
442 #define RSTRING_CHAR_LEN(s) RSTRING_LEN(s)
443 #define chars2bytes(p, off, ci) (ci)
444 #define bytes2chars(p, end, bi) (bi)
445 #define char_adjust(beg, end, ptr) (ptr)
446 #define char_backtrack(ptr, end) ((end) - 1)
447 #define BYTES_ALIGN_CHECK(pos)
448 #define str_index_str_by_char(mrb, str, sub, pos) str_index_str(mrb, str, sub, pos)
449 #endif
450
451 #ifndef MRB_QS_SHORT_STRING_LENGTH
452 #define MRB_QS_SHORT_STRING_LENGTH 2048
453 #endif
454
455 static inline mrb_int
456 mrb_memsearch_qs(const unsigned char *xs, mrb_int m, const unsigned char *ys, mrb_int n)
457 {
458 if (n + m < MRB_QS_SHORT_STRING_LENGTH) {
459 const unsigned char *y = ys;
460 const unsigned char *ye = ys+n-m+1;
461
462 for (;;) {
463 y = (const unsigned char*)memchr(y, xs[0], (size_t)(ye-y));
464 if (y == NULL) return -1;
465 if (memcmp(xs, y, m) == 0) {
466 return (mrb_int)(y - ys);
467 }
468 y++;
469 }
470 return -1;
471 }
472 else {
473 const unsigned char *x = xs, *xe = xs + m;
474 const unsigned char *y = ys;
475 ptrdiff_t qstable[256];
476
477 /* Preprocessing */
478 for (int i = 0; i < 256; i++)
479 qstable[i] = m + 1;
480 for (; x < xe; x++)
481 qstable[*x] = xe - x;
482 /* Searching */
483 for (; y + m <= ys + n; y += *(qstable + y[m])) {
484 if (*xs == *y && memcmp(xs, y, m) == 0)
485 return (mrb_int)(y - ys);
486 }
487 return -1;
488 }
489 }
490
491 static mrb_int
492 mrb_memsearch(const void *x0, mrb_int m, const void *y0, mrb_int n)
493 {
494 const unsigned char *x = (const unsigned char*)x0, *y = (const unsigned char*)y0;
495
496 if (m > n) return -1;
497 else if (m == n) {
498 return memcmp(x0, y0, m) == 0 ? 0 : -1;
499 }
500 else if (m < 1) {
501 return 0;
502 }
503 else if (m == 1) {
504 const unsigned char *ys = (const unsigned char*)memchr(y, *x, n);
505
506 if (ys)
507 return (mrb_int)(ys - y);
508 else
509 return -1;
510 }
511 return mrb_memsearch_qs((const unsigned char*)x0, m, (const unsigned char*)y0, n);
512 }
513
514 static void
515 str_share(mrb_state *mrb, struct RString *orig, struct RString *s)
516 {
517 size_t len = (size_t)orig->as.heap.len;
518
519 mrb_assert(!RSTR_EMBED_P(orig));
520 if (RSTR_NOFREE_P(orig)) {
521 str_init_nofree(s, orig->as.heap.ptr, len);
522 }
523 else if (RSTR_SHARED_P(orig)) {
524 str_init_shared(mrb, orig, s, orig->as.heap.aux.shared);
525 }
526 else if (RSTR_FSHARED_P(orig)) {
527 str_init_fshared(orig, s, orig->as.heap.aux.fshared);
528 }
529 else {
530 if (orig->as.heap.aux.capa > orig->as.heap.len) {
531 orig->as.heap.ptr = (char*)mrb_realloc(mrb, orig->as.heap.ptr, len+1);
532 orig->as.heap.aux.capa = (mrb_ssize)len;
533 }
534 str_init_shared(mrb, orig, s, NULL);
535 str_init_shared(mrb, orig, orig, s->as.heap.aux.shared);
536 }
537 }
538
539 mrb_value
540 mrb_str_byte_subseq(mrb_state *mrb, mrb_value str, mrb_int beg, mrb_int len)
541 {
542 struct RString *orig, *s;
543
544 orig = mrb_str_ptr(str);
545 s = mrb_obj_alloc_string(mrb);
546 if (RSTR_EMBEDDABLE_P(len)) {
547 str_init_embed(s, RSTR_PTR(orig)+beg, len);
548 }
549 else {
550 str_share(mrb, orig, s);
551 s->as.heap.ptr += (mrb_ssize)beg;
552 s->as.heap.len = (mrb_ssize)len;
553 }
554 RSTR_COPY_ASCII_FLAG(s, orig);
555 return mrb_obj_value(s);
556 }
557
558 static void
559 str_range_to_bytes(mrb_value str, mrb_int *pos, mrb_int *len)
560 {
561 *pos = chars2bytes(str, 0, *pos);
562 *len = chars2bytes(str, *pos, *len);
563 }
564 #ifdef MRB_UTF8_STRING
565 static inline mrb_value
566 str_subseq(mrb_state *mrb, mrb_value str, mrb_int beg, mrb_int len)
567 {
568 str_range_to_bytes(str, &beg, &len);
569 return mrb_str_byte_subseq(mrb, str, beg, len);
570 }
571 #else
572 #define str_subseq(mrb, str, beg, len) mrb_str_byte_subseq(mrb, str, beg, len)
573 #endif
574
575 mrb_bool
576 mrb_str_beg_len(mrb_int str_len, mrb_int *begp, mrb_int *lenp)
577 {
578 if (str_len < *begp || *lenp < 0) return FALSE;
579 if (*begp < 0) {
580 *begp += str_len;
581 if (*begp < 0) return FALSE;
582 }
583 if (*lenp > str_len - *begp)
584 *lenp = str_len - *begp;
585 if (*lenp <= 0) {
586 *lenp = 0;
587 }
588 return TRUE;
589 }
590
591 static mrb_value
592 str_substr(mrb_state *mrb, mrb_value str, mrb_int beg, mrb_int len)
593 {
594 return mrb_str_beg_len(RSTRING_CHAR_LEN(str), &beg, &len) ?
595 str_subseq(mrb, str, beg, len) : mrb_nil_value();
596 }
597
598 MRB_API mrb_int
599 mrb_str_index(mrb_state *mrb, mrb_value str, const char *sptr, mrb_int slen, mrb_int offset)
600 {
601 mrb_int pos;
602 char *s;
603 mrb_int len;
604
605 len = RSTRING_LEN(str);
606 if (offset < 0) {
607 offset += len;
608 if (offset < 0) return -1;
609 }
610 if (len - offset < slen) return -1;
611 s = RSTRING_PTR(str);
612 if (offset) {
613 s += offset;
614 }
615 if (slen == 0) return offset;
616 /* need proceed one character at a time */
617 len = RSTRING_LEN(str) - offset;
618 pos = mrb_memsearch(sptr, slen, s, len);
619 if (pos < 0) return pos;
620 return pos + offset;
621 }
622
623 static mrb_int
624 str_index_str(mrb_state *mrb, mrb_value str, mrb_value str2, mrb_int offset)
625 {
626 const char *ptr;
627 mrb_int len;
628
629 ptr = RSTRING_PTR(str2);
630 len = RSTRING_LEN(str2);
631
632 return mrb_str_index(mrb, str, ptr, len, offset);
633 }
634
635 static mrb_value
636 str_replace(mrb_state *mrb, struct RString *s1, struct RString *s2)
637 {
638 size_t len;
639
640 mrb_check_frozen(mrb, s1);
641 if (s1 == s2) return mrb_obj_value(s1);
642 RSTR_COPY_ASCII_FLAG(s1, s2);
643 if (RSTR_SHARED_P(s1)) {
644 str_decref(mrb, s1->as.heap.aux.shared);
645 }
646 else if (!RSTR_EMBED_P(s1) && !RSTR_NOFREE_P(s1) && !RSTR_FSHARED_P(s1)
647 && s1->as.heap.ptr) {
648 mrb_free(mrb, s1->as.heap.ptr);
649 }
650
651 len = (size_t)RSTR_LEN(s2);
652 if (RSTR_EMBEDDABLE_P(len)) {
653 str_init_embed(s1, RSTR_PTR(s2), len);
654 }
655 else {
656 str_share(mrb, s2, s1);
657 }
658
659 return mrb_obj_value(s1);
660 }
661
662 static mrb_int
663 str_rindex(mrb_state *mrb, mrb_value str, mrb_value sub, mrb_int pos)
664 {
665 const char *s, *sbeg, *send, *t;
666 struct RString *ps = mrb_str_ptr(str);
667 mrb_int len = RSTRING_LEN(sub);
668 mrb_int slen = RSTR_LEN(ps);
669
670 /* substring longer than string */
671 if (slen < len) return -1;
672 if (slen - pos < len) {
673 pos = slen - len;
674 }
675 sbeg = RSTR_PTR(ps);
676 send = sbeg + slen;
677 s = sbeg + pos;
678 t = RSTRING_PTR(sub);
679 if (len) {
680 s = char_adjust(sbeg, send, s);
681 while (sbeg <= s) {
682 if ((mrb_int)(send - s) >= len && memcmp(s, t, len) == 0) {
683 return (mrb_int)(s - sbeg);
684 }
685 s = char_backtrack(sbeg, s);
686 }
687 return -1;
688 }
689 else {
690 return pos;
691 }
692 }
693
694 #ifdef _WIN32
695 #include <windows.h>
696
697 char*
698 mrb_utf8_from_locale(const char *str, int len)
699 {
700 wchar_t* wcsp;
701 char* mbsp;
702 int mbssize, wcssize;
703
704 if (len == 0)
705 return strdup("");
706 if (len == -1)
707 len = (int)strlen(str);
708 wcssize = MultiByteToWideChar(GetACP(), 0, str, len, NULL, 0);
709 wcsp = (wchar_t*) malloc((wcssize + 1) * sizeof(wchar_t));
710 if (!wcsp)
711 return NULL;
712 wcssize = MultiByteToWideChar(GetACP(), 0, str, len, wcsp, wcssize + 1);
713 wcsp[wcssize] = 0;
714
715 mbssize = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR) wcsp, -1, NULL, 0, NULL, NULL);
716 mbsp = (char*) malloc((mbssize + 1));
717 if (!mbsp) {
718 free(wcsp);
719 return NULL;
720 }
721 mbssize = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR) wcsp, -1, mbsp, mbssize, NULL, NULL);
722 mbsp[mbssize] = 0;
723 free(wcsp);
724 return mbsp;
725 }
726
727 char*
728 mrb_locale_from_utf8(const char *utf8, int len)
729 {
730 wchar_t* wcsp;
731 char* mbsp;
732 int mbssize, wcssize;
733
734 if (len == 0)
735 return strdup("");
736 if (len == -1)
737 len = (int)strlen(utf8);
738 wcssize = MultiByteToWideChar(CP_UTF8, 0, utf8, len, NULL, 0);
739 wcsp = (wchar_t*) malloc((wcssize + 1) * sizeof(wchar_t));
740 if (!wcsp)
741 return NULL;
742 wcssize = MultiByteToWideChar(CP_UTF8, 0, utf8, len, wcsp, wcssize + 1);
743 wcsp[wcssize] = 0;
744 mbssize = WideCharToMultiByte(GetACP(), 0, (LPCWSTR) wcsp, -1, NULL, 0, NULL, NULL);
745 mbsp = (char*) malloc((mbssize + 1));
746 if (!mbsp) {
747 free(wcsp);
748 return NULL;
749 }
750 mbssize = WideCharToMultiByte(GetACP(), 0, (LPCWSTR) wcsp, -1, mbsp, mbssize, NULL, NULL);
751 mbsp[mbssize] = 0;
752 free(wcsp);
753 return mbsp;
754 }
755 #endif
756
757 MRB_API void
758 mrb_str_modify_keep_ascii(mrb_state *mrb, struct RString *s)
759 {
760 mrb_check_frozen(mrb, s);
761 str_modify_keep_ascii(mrb, s);
762 }
763
764 MRB_API void
765 mrb_str_modify(mrb_state *mrb, struct RString *s)
766 {
767 mrb_str_modify_keep_ascii(mrb, s);
768 RSTR_UNSET_ASCII_FLAG(s);
769 }
770
771 MRB_API mrb_value
772 mrb_str_resize(mrb_state *mrb, mrb_value str, mrb_int len)
773 {
774 mrb_int slen;
775 struct RString *s = mrb_str_ptr(str);
776
777 str_check_length(mrb, len);
778 mrb_str_modify(mrb, s);
779 slen = RSTR_LEN(s);
780 if (len != slen) {
781 if (slen < len || slen - len > 256) {
782 resize_capa(mrb, s, len);
783 }
784 RSTR_SET_LEN(s, len);
785 RSTR_PTR(s)[len] = '\0'; /* sentinel */
786 }
787 return str;
788 }
789
790 MRB_API char*
791 mrb_str_to_cstr(mrb_state *mrb, mrb_value str0)
792 {
793 struct RString *s;
794
795 const char *p = RSTRING_PTR(str0);
796 mrb_int len = RSTRING_LEN(str0);
797 check_null_byte(mrb, RSTRING(str0));
798 s = str_init_modifiable(mrb, mrb_obj_alloc_string(mrb), p, len);
799 return RSTR_PTR(s);
800 }
801
802 MRB_API void
803 mrb_str_concat(mrb_state *mrb, mrb_value self, mrb_value other)
804 {
805 other = mrb_obj_as_string(mrb, other);
806 mrb_str_cat_str(mrb, self, other);
807 }
808
809 MRB_API mrb_value
810 mrb_str_plus(mrb_state *mrb, mrb_value a, mrb_value b)
811 {
812 struct RString *s = mrb_str_ptr(a);
813 struct RString *s2 = mrb_str_ptr(b);
814 struct RString *t;
815 mrb_int slen = RSTR_LEN(s);
816 mrb_int s2len = RSTR_LEN(s2);
817 const char *p = RSTR_PTR(s);
818 const char *p2 = RSTR_PTR(s2);
819
820 t = str_new(mrb, 0, slen + s2len);
821 char *pt = RSTR_PTR(t);
822 memcpy(pt, p, slen);
823 memcpy(pt + slen, p2, s2len);
824
825 return mrb_obj_value(t);
826 }
827
828 /* 15.2.10.5.2 */
829
830 /*
831 * call-seq:
832 * str + other_str -> new_str
833 *
834 * Concatenation---Returns a new <code>String</code> containing
835 * <i>other_str</i> concatenated to <i>str</i>.
836 *
837 * "Hello from " + self.to_s #=> "Hello from main"
838 */
839 static mrb_value
840 mrb_str_plus_m(mrb_state *mrb, mrb_value self)
841 {
842 mrb_value str;
843
844 mrb_get_args(mrb, "S", &str);
845 return mrb_str_plus(mrb, self, str);
846 }
847
848 /* 15.2.10.5.26 */
849 /* 15.2.10.5.33 */
850 /*
851 * call-seq:
852 * "abcd".size => int
853 *
854 * Returns the length of string.
855 */
856 static mrb_value
857 mrb_str_size(mrb_state *mrb, mrb_value self)
858 {
859 mrb_int len = RSTRING_CHAR_LEN(self);
860 return mrb_int_value(mrb, len);
861 }
862
863 static mrb_value
864 mrb_str_bytesize(mrb_state *mrb, mrb_value self)
865 {
866 mrb_int len = RSTRING_LEN(self);
867 return mrb_int_value(mrb, len);
868 }
869
870 /* 15.2.10.5.1 */
871 /*
872 * call-seq:
873 * str * integer => new_str
874 *
875 * Copy---Returns a new <code>String</code> containing <i>integer</i> copies of
876 * the receiver.
877 *
878 * "Ho! " * 3 #=> "Ho! Ho! Ho! "
879 */
880 static mrb_value
881 mrb_str_times(mrb_state *mrb, mrb_value self)
882 {
883 mrb_int n, len, times;
884 struct RString *str2;
885 char *p;
886
887 mrb_get_args(mrb, "i", &times);
888 if (times < 0) {
889 mrb_raise(mrb, E_ARGUMENT_ERROR, "negative argument");
890 }
891 if (mrb_int_mul_overflow(RSTRING_LEN(self), times, &len)) {
892 mrb_raise(mrb, E_ARGUMENT_ERROR, "argument too big");
893 }
894 str2 = str_new(mrb, 0, len);
895 p = RSTR_PTR(str2);
896 if (len > 0) {
897 n = RSTRING_LEN(self);
898 memcpy(p, RSTRING_PTR(self), n);
899 while (n <= len/2) {
900 memcpy(p + n, p, n);
901 n *= 2;
902 }
903 memcpy(p + n, p, len-n);
904 }
905 p[RSTR_LEN(str2)] = '\0';
906 RSTR_COPY_ASCII_FLAG(str2, mrb_str_ptr(self));
907
908 return mrb_obj_value(str2);
909 }
910 /* -------------------------------------------------------------- */
911
912 #define lesser(a,b) (((a)>(b))?(b):(a))
913
914 /* ---------------------------*/
915 /*
916 * call-seq:
917 * mrb_value str1 <=> mrb_value str2 => int
918 * > 1
919 * = 0
920 * < -1
921 */
922 MRB_API int
923 mrb_str_cmp(mrb_state *mrb, mrb_value str1, mrb_value str2)
924 {
925 mrb_int len, len1, len2;
926 mrb_int retval;
927 struct RString *s1 = mrb_str_ptr(str1);
928 struct RString *s2 = mrb_str_ptr(str2);
929
930 len1 = RSTR_LEN(s1);
931 len2 = RSTR_LEN(s2);
932 len = lesser(len1, len2);
933 retval = memcmp(RSTR_PTR(s1), RSTR_PTR(s2), len);
934 if (retval == 0) {
935 if (len1 == len2) return 0;
936 if (len1 > len2) return 1;
937 return -1;
938 }
939 if (retval > 0) return 1;
940 return -1;
941 }
942
943 /* 15.2.10.5.3 */
944
945 /*
946 * call-seq:
947 * str <=> other_str => -1, 0, +1
948 *
949 * Comparison---Returns -1 if <i>other_str</i> is less than, 0 if
950 * <i>other_str</i> is equal to, and +1 if <i>other_str</i> is greater than
951 * <i>str</i>. If the strings are of different lengths, and the strings are
952 * equal when compared up to the shortest length, then the longer string is
953 * considered greater than the shorter one. If the variable <code>$=</code> is
954 * <code>false</code>, the comparison is based on comparing the binary values
955 * of each character in the string. In older versions of Ruby, setting
956 * <code>$=</code> allowed case-insensitive comparisons; this is now deprecated
957 * in favor of using <code>String#casecmp</code>.
958 *
959 * <code><=></code> is the basis for the methods <code><</code>,
960 * <code><=</code>, <code>></code>, <code>>=</code>, and <code>between?</code>,
961 * included from module <code>Comparable</code>. The method
962 * <code>String#==</code> does not use <code>Comparable#==</code>.
963 *
964 * "abcdef" <=> "abcde" #=> 1
965 * "abcdef" <=> "abcdef" #=> 0
966 * "abcdef" <=> "abcdefg" #=> -1
967 * "abcdef" <=> "ABCDEF" #=> 1
968 */
969 static mrb_value
970 mrb_str_cmp_m(mrb_state *mrb, mrb_value str1)
971 {
972 mrb_value str2 = mrb_get_arg1(mrb);
973 mrb_int result;
974
975 if (!mrb_string_p(str2)) {
976 return mrb_nil_value();
977 }
978 else {
979 result = mrb_str_cmp(mrb, str1, str2);
980 }
981 return mrb_int_value(mrb, result);
982 }
983
984 static mrb_bool
985 str_eql(mrb_state *mrb, const mrb_value str1, const mrb_value str2)
986 {
987 const mrb_int len = RSTRING_LEN(str1);
988
989 if (len != RSTRING_LEN(str2)) return FALSE;
990 if (memcmp(RSTRING_PTR(str1), RSTRING_PTR(str2), (size_t)len) == 0)
991 return TRUE;
992 return FALSE;
993 }
994
995 MRB_API mrb_bool
996 mrb_str_equal(mrb_state *mrb, mrb_value str1, mrb_value str2)
997 {
998 if (!mrb_string_p(str2)) return FALSE;
999 return str_eql(mrb, str1, str2);
1000 }
1001
1002 /* 15.2.10.5.4 */
1003 /*
1004 * call-seq:
1005 * str == obj => true or false
1006 *
1007 * Equality---
1008 * If <i>obj</i> is not a <code>String</code>, returns <code>false</code>.
1009 * Otherwise, returns <code>false</code> or <code>true</code>
1010 *
1011 * caution:if <i>str</i> <code><=></code> <i>obj</i> returns zero.
1012 */
1013 static mrb_value
1014 mrb_str_equal_m(mrb_state *mrb, mrb_value str1)
1015 {
1016 mrb_value str2 = mrb_get_arg1(mrb);
1017
1018 return mrb_bool_value(mrb_str_equal(mrb, str1, str2));
1019 }
1020 /* ---------------------------------- */
1021
1022 MRB_API mrb_value
1023 mrb_str_dup(mrb_state *mrb, mrb_value str)
1024 {
1025 struct RString *s = mrb_str_ptr(str);
1026 struct RString *dup = str_new(mrb, 0, 0);
1027
1028 return str_replace(mrb, dup, s);
1029 }
1030
1031 enum str_convert_range {
1032 /* `beg` and `len` are byte unit in `0 ... str.bytesize` */
1033 STR_BYTE_RANGE_CORRECTED = 1,
1034
1035 /* `beg` and `len` are char unit in any range */
1036 STR_CHAR_RANGE = 2,
1037
1038 /* `beg` and `len` are char unit in `0 ... str.size` */
1039 STR_CHAR_RANGE_CORRECTED = 3,
1040
1041 /* `beg` is out of range */
1042 STR_OUT_OF_RANGE = -1
1043 };
1044
1045 static enum str_convert_range
1046 str_convert_range(mrb_state *mrb, mrb_value str, mrb_value indx, mrb_value alen, mrb_int *beg, mrb_int *len)
1047 {
1048 if (!mrb_undef_p(alen)) {
1049 *beg = mrb_as_int(mrb, indx);
1050 *len = mrb_as_int(mrb, alen);
1051 return STR_CHAR_RANGE;
1052 }
1053 else {
1054 switch (mrb_type(indx)) {
1055 default:
1056 indx = mrb_ensure_int_type(mrb, indx);
1057 /* fall through */
1058 case MRB_TT_INTEGER:
1059 *beg = mrb_integer(indx);
1060 *len = 1;
1061 return STR_CHAR_RANGE;
1062
1063 case MRB_TT_STRING:
1064 *beg = str_index_str(mrb, str, indx, 0);
1065 if (*beg < 0) { break; }
1066 *len = RSTRING_LEN(indx);
1067 return STR_BYTE_RANGE_CORRECTED;
1068
1069 case MRB_TT_RANGE:
1070 *len = RSTRING_CHAR_LEN(str);
1071 switch (mrb_range_beg_len(mrb, indx, beg, len, *len, TRUE)) {
1072 case MRB_RANGE_OK:
1073 return STR_CHAR_RANGE_CORRECTED;
1074 case MRB_RANGE_OUT:
1075 return STR_OUT_OF_RANGE;
1076 default:
1077 break;
1078 }
1079 }
1080 }
1081 return STR_OUT_OF_RANGE;
1082 }
1083
1084 mrb_value
1085 mrb_str_aref(mrb_state *mrb, mrb_value str, mrb_value indx, mrb_value alen)
1086 {
1087 mrb_int beg, len;
1088
1089 switch (str_convert_range(mrb, str, indx, alen, &beg, &len)) {
1090 case STR_CHAR_RANGE_CORRECTED:
1091 return str_subseq(mrb, str, beg, len);
1092 case STR_CHAR_RANGE:
1093 str = str_substr(mrb, str, beg, len);
1094 if (mrb_undef_p(alen) && !mrb_nil_p(str) && RSTRING_LEN(str) == 0) return mrb_nil_value();
1095 return str;
1096 case STR_BYTE_RANGE_CORRECTED:
1097 if (mrb_string_p(indx)) {
1098 return mrb_str_dup(mrb, indx);
1099 }
1100 else {
1101 return mrb_str_byte_subseq(mrb, str, beg, len);
1102 }
1103 case STR_OUT_OF_RANGE:
1104 default:
1105 return mrb_nil_value();
1106 }
1107 }
1108
1109 /* 15.2.10.5.6 */
1110 /* 15.2.10.5.34 */
1111 /*
1112 * call-seq:
1113 * str[int] => int or nil
1114 * str[int, int] => new_str or nil
1115 * str[range] => new_str or nil
1116 * str[other_str] => new_str or nil
1117 * str.slice(int) => int or nil
1118 * str.slice(int, int) => new_str or nil
1119 * str.slice(range) => new_str or nil
1120 * str.slice(other_str) => new_str or nil
1121 *
1122 * Element Reference---If passed a single <code>Integer</code>, returns the code
1123 * of the character at that position. If passed two <code>Integer</code>
1124 * objects, returns a substring starting at the offset given by the first, and
1125 * a length given by the second. If given a range, a substring containing
1126 * characters at offsets given by the range is returned. In all three cases, if
1127 * an offset is negative, it is counted from the end of <i>str</i>. Returns
1128 * <code>nil</code> if the initial offset falls outside the string, the length
1129 * is negative, or the beginning of the range is greater than the end.
1130 *
1131 * If a <code>String</code> is given, that string is returned if it occurs in
1132 * <i>str</i>. In both cases, <code>nil</code> is returned if there is no
1133 * match.
1134 *
1135 * a = "hello there"
1136 * a[1] #=> 101(1.8.7) "e"(1.9.2)
1137 * a[1.1] #=> "e"(1.9.2)
1138 * a[1,3] #=> "ell"
1139 * a[1..3] #=> "ell"
1140 * a[-3,2] #=> "er"
1141 * a[-4..-2] #=> "her"
1142 * a[12..-1] #=> nil
1143 * a[-2..-4] #=> ""
1144 * a["lo"] #=> "lo"
1145 * a["bye"] #=> nil
1146 */
1147 static mrb_value
1148 mrb_str_aref_m(mrb_state *mrb, mrb_value str)
1149 {
1150 mrb_value a1, a2;
1151
1152 if (mrb_get_args(mrb, "o|o", &a1, &a2) == 1) {
1153 a2 = mrb_undef_value();
1154 }
1155
1156 return mrb_str_aref(mrb, str, a1, a2);
1157 }
1158
1159 static mrb_noreturn void
1160 str_out_of_index(mrb_state *mrb, mrb_value index)
1161 {
1162 mrb_raisef(mrb, E_INDEX_ERROR, "index %v out of string", index);
1163 }
1164
1165 static mrb_value
1166 str_replace_partial(mrb_state *mrb, mrb_value src, mrb_int pos, mrb_int end, mrb_value rep)
1167 {
1168 const mrb_int shrink_threshold = 256;
1169 struct RString *str = mrb_str_ptr(src);
1170 mrb_int len = RSTR_LEN(str);
1171 mrb_int replen, newlen;
1172 char *strp;
1173
1174 if (end > len) { end = len; }
1175
1176 if (pos < 0 || pos > len) {
1177 str_out_of_index(mrb, mrb_int_value(mrb, pos));
1178 }
1179
1180 replen = (mrb_nil_p(rep) ? 0 : RSTRING_LEN(rep));
1181 if (mrb_int_add_overflow(replen, len - (end - pos), &newlen)) {
1182 mrb_raise(mrb, E_RUNTIME_ERROR, "string size too big");
1183 }
1184
1185 mrb_str_modify(mrb, str);
1186
1187 if (len < newlen) {
1188 resize_capa(mrb, str, newlen);
1189 }
1190
1191 strp = RSTR_PTR(str);
1192
1193 memmove(strp + newlen - (len - end), strp + end, len - end);
1194 if (!mrb_nil_p(rep)) {
1195 memmove(strp + pos, RSTRING_PTR(rep), replen);
1196 }
1197 RSTR_SET_LEN(str, newlen);
1198 strp[newlen] = '\0';
1199
1200 if (len - newlen >= shrink_threshold) {
1201 resize_capa(mrb, str, newlen);
1202 }
1203
1204 return src;
1205 }
1206
1207 #define IS_EVSTR(p,e) ((p) < (e) && (*(p) == '$' || *(p) == '@' || *(p) == '{'))
1208
1209 static mrb_value
1210 str_escape(mrb_state *mrb, mrb_value str, mrb_bool inspect)
1211 {
1212 const char *p, *pend;
1213 char buf[4]; /* `\x??` or UTF-8 character */
1214 mrb_value result = mrb_str_new_lit(mrb, "\"");
1215 #ifdef MRB_UTF8_STRING
1216 uint32_t ascii_flag = MRB_STR_ASCII;
1217 #endif
1218
1219 p = RSTRING_PTR(str); pend = RSTRING_END(str);
1220 for (;p < pend; p++) {
1221 unsigned char c, cc;
1222 #ifdef MRB_UTF8_STRING
1223 if (inspect) {
1224 mrb_int clen = mrb_utf8len(p, pend);
1225 if (clen > 1) {
1226 mrb_str_cat(mrb, result, p, clen);
1227 p += clen-1;
1228 ascii_flag = 0;
1229 continue;
1230 }
1231 }
1232 #endif
1233 c = *p;
1234 if (c == '"'|| c == '\\' || (c == '#' && IS_EVSTR(p+1, pend))) {
1235 buf[0] = '\\'; buf[1] = c;
1236 mrb_str_cat(mrb, result, buf, 2);
1237 continue;
1238 }
1239 if (ISPRINT(c)) {
1240 buf[0] = c;
1241 mrb_str_cat(mrb, result, buf, 1);
1242 continue;
1243 }
1244 switch (c) {
1245 case '\n': cc = 'n'; break;
1246 case '\r': cc = 'r'; break;
1247 case '\t': cc = 't'; break;
1248 case '\f': cc = 'f'; break;
1249 case '\013': cc = 'v'; break;
1250 case '\010': cc = 'b'; break;
1251 case '\007': cc = 'a'; break;
1252 case 033: cc = 'e'; break;
1253 default: cc = 0; break;
1254 }
1255 buf[0] = '\\';
1256 if (cc) {
1257 buf[1] = (char)cc;
1258 mrb_str_cat(mrb, result, buf, 2);
1259 }
1260 else {
1261 buf[1] = 'x';
1262 buf[3] = mrb_digitmap[c % 16]; c /= 16;
1263 buf[2] = mrb_digitmap[c % 16];
1264 mrb_str_cat(mrb, result, buf, 4);
1265 }
1266 }
1267 mrb_str_cat_lit(mrb, result, "\"");
1268 #ifdef MRB_UTF8_STRING
1269 if (inspect) {
1270 mrb_str_ptr(str)->flags |= ascii_flag;
1271 mrb_str_ptr(result)->flags |= ascii_flag;
1272 }
1273 else {
1274 RSTR_SET_ASCII_FLAG(mrb_str_ptr(result));
1275 }
1276 #endif
1277
1278 return result;
1279 }
1280
1281 static void
1282 mrb_str_aset(mrb_state *mrb, mrb_value str, mrb_value indx, mrb_value alen, mrb_value replace)
1283 {
1284 mrb_int beg, len, charlen;
1285
1286 mrb_ensure_string_type(mrb, replace);
1287 switch (str_convert_range(mrb, str, indx, alen, &beg, &len)) {
1288 case STR_OUT_OF_RANGE:
1289 default:
1290 mrb_raise(mrb, E_INDEX_ERROR, "string not matched");
1291 case STR_CHAR_RANGE:
1292 if (len < 0) {
1293 mrb_raisef(mrb, E_INDEX_ERROR, "negative length %v", alen);
1294 }
1295 charlen = RSTRING_CHAR_LEN(str);
1296 if (beg < 0) { beg += charlen; }
1297 if (beg < 0 || beg > charlen) { str_out_of_index(mrb, indx); }
1298 /* fall through */
1299 case STR_CHAR_RANGE_CORRECTED:
1300 str_range_to_bytes(str, &beg, &len);
1301 /* fall through */
1302 case STR_BYTE_RANGE_CORRECTED:
1303 if (mrb_int_add_overflow(beg, len, &len)) {
1304 mrb_raise(mrb, E_RUNTIME_ERROR, "string index too big");
1305 }
1306 str_replace_partial(mrb, str, beg, len, replace);
1307 }
1308 }
1309
1310 /*
1311 * call-seq:
1312 * str[int] = replace
1313 * str[int, int] = replace
1314 * str[range] = replace
1315 * str[other_str] = replace
1316 *
1317 * Modify +self+ by replacing the content of +self+.
1318 * The portion of the string affected is determined using the same criteria as +String#[]+.
1319 */
1320 static mrb_value
1321 mrb_str_aset_m(mrb_state *mrb, mrb_value str)
1322 {
1323 mrb_value indx, alen, replace;
1324
1325 switch (mrb_get_args(mrb, "oo|S!", &indx, &alen, &replace)) {
1326 case 2:
1327 replace = alen;
1328 alen = mrb_undef_value();
1329 break;
1330 case 3:
1331 break;
1332 }
1333 mrb_str_aset(mrb, str, indx, alen, replace);
1334 return str;
1335 }
1336
1337 /* 15.2.10.5.8 */
1338 /*
1339 * call-seq:
1340 * str.capitalize! => str or nil
1341 *
1342 * Modifies <i>str</i> by converting the first character to uppercase and the
1343 * remainder to lowercase. Returns <code>nil</code> if no changes are made.
1344 *
1345 * a = "hello"
1346 * a.capitalize! #=> "Hello"
1347 * a #=> "Hello"
1348 * a.capitalize! #=> nil
1349 */
1350 static mrb_value
1351 mrb_str_capitalize_bang(mrb_state *mrb, mrb_value str)
1352 {
1353 mrb_bool modify = FALSE;
1354 struct RString *s = mrb_str_ptr(str);
1355 mrb_int len = RSTR_LEN(s);
1356
1357 mrb_str_modify_keep_ascii(mrb, s);
1358 char *p = RSTR_PTR(s);
1359 char *pend = RSTR_PTR(s) + len;
1360 if (len == 0 || p == NULL) return mrb_nil_value();
1361 if (ISLOWER(*p)) {
1362 *p = TOUPPER(*p);
1363 modify = TRUE;
1364 }
1365 while (++p < pend) {
1366 if (ISUPPER(*p)) {
1367 *p = TOLOWER(*p);
1368 modify = TRUE;
1369 }
1370 }
1371 if (modify) return str;
1372 return mrb_nil_value();
1373 }
1374
1375 /* 15.2.10.5.7 */
1376 /*
1377 * call-seq:
1378 * str.capitalize => new_str
1379 *
1380 * Returns a copy of <i>str</i> with the first character converted to uppercase
1381 * and the remainder to lowercase.
1382 *
1383 * "hello".capitalize #=> "Hello"
1384 * "HELLO".capitalize #=> "Hello"
1385 * "123ABC".capitalize #=> "123abc"
1386 */
1387 static mrb_value
1388 mrb_str_capitalize(mrb_state *mrb, mrb_value self)
1389 {
1390 mrb_value str;
1391
1392 str = mrb_str_dup(mrb, self);
1393 mrb_str_capitalize_bang(mrb, str);
1394 return str;
1395 }
1396
1397 /* 15.2.10.5.10 */
1398 /*
1399 * call-seq:
1400 * str.chomp!(separator="\n") => str or nil
1401 *
1402 * Modifies <i>str</i> in place as described for <code>String#chomp</code>,
1403 * returning <i>str</i>, or <code>nil</code> if no modifications were made.
1404 */
1405 static mrb_value
1406 mrb_str_chomp_bang(mrb_state *mrb, mrb_value str)
1407 {
1408 mrb_value rs;
1409 mrb_int newline;
1410 char *p, *pp;
1411 mrb_int rslen;
1412 mrb_int len;
1413 mrb_int argc;
1414 struct RString *s = mrb_str_ptr(str);
1415
1416 argc = mrb_get_args(mrb, "|S", &rs);
1417 mrb_str_modify_keep_ascii(mrb, s);
1418 len = RSTR_LEN(s);
1419 if (argc == 0) {
1420 if (len == 0) return mrb_nil_value();
1421 smart_chomp:
1422 if (RSTR_PTR(s)[len-1] == '\n') {
1423 RSTR_SET_LEN(s, RSTR_LEN(s) - 1);
1424 if (RSTR_LEN(s) > 0 &&
1425 RSTR_PTR(s)[RSTR_LEN(s)-1] == '\r') {
1426 RSTR_SET_LEN(s, RSTR_LEN(s) - 1);
1427 }
1428 }
1429 else if (RSTR_PTR(s)[len-1] == '\r') {
1430 RSTR_SET_LEN(s, RSTR_LEN(s) - 1);
1431 }
1432 else {
1433 return mrb_nil_value();
1434 }
1435 RSTR_PTR(s)[RSTR_LEN(s)] = '\0';
1436 return str;
1437 }
1438
1439 if (len == 0 || mrb_nil_p(rs)) return mrb_nil_value();
1440 p = RSTR_PTR(s);
1441 rslen = RSTRING_LEN(rs);
1442 if (rslen == 0) {
1443 while (len>0 && p[len-1] == '\n') {
1444 len--;
1445 if (len>0 && p[len-1] == '\r')
1446 len--;
1447 }
1448 if (len < RSTR_LEN(s)) {
1449 RSTR_SET_LEN(s, len);
1450 p[len] = '\0';
1451 return str;
1452 }
1453 return mrb_nil_value();
1454 }
1455 if (rslen > len) return mrb_nil_value();
1456 newline = RSTRING_PTR(rs)[rslen-1];
1457 if (rslen == 1 && newline == '\n')
1458 newline = RSTRING_PTR(rs)[rslen-1];
1459 if (rslen == 1 && newline == '\n')
1460 goto smart_chomp;
1461
1462 pp = p + len - rslen;
1463 if (p[len-1] == newline &&
1464 (rslen <= 1 ||
1465 memcmp(RSTRING_PTR(rs), pp, rslen) == 0)) {
1466 RSTR_SET_LEN(s, len - rslen);
1467 p[RSTR_LEN(s)] = '\0';
1468 return str;
1469 }
1470 return mrb_nil_value();
1471 }
1472
1473 /* 15.2.10.5.9 */
1474 /*
1475 * call-seq:
1476 * str.chomp(separator="\n") => new_str
1477 *
1478 * Returns a new <code>String</code> with the given record separator removed
1479 * from the end of <i>str</i> (if present). <code>chomp</code> also removes
1480 * carriage return characters (that is it will remove <code>\n</code>,
1481 * <code>\r</code>, and <code>\r\n</code>).
1482 *
1483 * "hello".chomp #=> "hello"
1484 * "hello\n".chomp #=> "hello"
1485 * "hello\r\n".chomp #=> "hello"
1486 * "hello\n\r".chomp #=> "hello\n"
1487 * "hello\r".chomp #=> "hello"
1488 * "hello \n there".chomp #=> "hello \n there"
1489 * "hello".chomp("llo") #=> "he"
1490 */
1491 static mrb_value
1492 mrb_str_chomp(mrb_state *mrb, mrb_value self)
1493 {
1494 mrb_value str;
1495
1496 str = mrb_str_dup(mrb, self);
1497 mrb_str_chomp_bang(mrb, str);
1498 return str;
1499 }
1500
1501 /* 15.2.10.5.12 */
1502 /*
1503 * call-seq:
1504 * str.chop! => str or nil
1505 *
1506 * Processes <i>str</i> as for <code>String#chop</code>, returning <i>str</i>,
1507 * or <code>nil</code> if <i>str</i> is the empty string. See also
1508 * <code>String#chomp!</code>.
1509 */
1510 static mrb_value
1511 mrb_str_chop_bang(mrb_state *mrb, mrb_value str)
1512 {
1513 struct RString *s = mrb_str_ptr(str);
1514
1515 mrb_str_modify_keep_ascii(mrb, s);
1516 if (RSTR_LEN(s) > 0) {
1517 mrb_int len;
1518 #ifdef MRB_UTF8_STRING
1519 const char* t = RSTR_PTR(s), *p = t;
1520 const char* e = p + RSTR_LEN(s);
1521 while (p<e) {
1522 mrb_int clen = mrb_utf8len(p, e);
1523 if (p + clen>=e) break;
1524 p += clen;
1525 }
1526 len = p - t;
1527 #else
1528 len = RSTR_LEN(s) - 1;
1529 #endif
1530 if (RSTR_PTR(s)[len] == '\n') {
1531 if (len > 0 &&
1532 RSTR_PTR(s)[len-1] == '\r') {
1533 len--;
1534 }
1535 }
1536 RSTR_SET_LEN(s, len);
1537 RSTR_PTR(s)[len] = '\0';
1538 return str;
1539 }
1540 return mrb_nil_value();
1541 }
1542
1543 /* 15.2.10.5.11 */
1544 /*
1545 * call-seq:
1546 * str.chop => new_str
1547 *
1548 * Returns a new <code>String</code> with the last character removed. If the
1549 * string ends with <code>\r\n</code>, both characters are removed. Applying
1550 * <code>chop</code> to an empty string returns an empty
1551 * string. <code>String#chomp</code> is often a safer alternative, as it leaves
1552 * the string unchanged if it doesn't end in a record separator.
1553 *
1554 * "string\r\n".chop #=> "string"
1555 * "string\n\r".chop #=> "string\n"
1556 * "string\n".chop #=> "string"
1557 * "string".chop #=> "strin"
1558 * "x".chop #=> ""
1559 */
1560 static mrb_value
1561 mrb_str_chop(mrb_state *mrb, mrb_value self)
1562 {
1563 mrb_value str;
1564 str = mrb_str_dup(mrb, self);
1565 mrb_str_chop_bang(mrb, str);
1566 return str;
1567 }
1568
1569 /* 15.2.10.5.14 */
1570 /*
1571 * call-seq:
1572 * str.downcase! => str or nil
1573 *
1574 * Downcases the contents of <i>str</i>, returning <code>nil</code> if no
1575 * changes were made.
1576 */
1577 static mrb_value
1578 mrb_str_downcase_bang(mrb_state *mrb, mrb_value str)
1579 {
1580 char *p, *pend;
1581 mrb_bool modify = FALSE;
1582 struct RString *s = mrb_str_ptr(str);
1583
1584 mrb_str_modify_keep_ascii(mrb, s);
1585 p = RSTR_PTR(s);
1586 pend = RSTR_PTR(s) + RSTR_LEN(s);
1587 while (p < pend) {
1588 if (ISUPPER(*p)) {
1589 *p = TOLOWER(*p);
1590 modify = TRUE;
1591 }
1592 p++;
1593 }
1594
1595 if (modify) return str;
1596 return mrb_nil_value();
1597 }
1598
1599 /* 15.2.10.5.13 */
1600 /*
1601 * call-seq:
1602 * str.downcase => new_str
1603 *
1604 * Returns a copy of <i>str</i> with all uppercase letters replaced with their
1605 * lowercase counterparts. The operation is locale insensitive---only
1606 * characters 'A' to 'Z' are affected.
1607 *
1608 * "hEllO".downcase #=> "hello"
1609 */
1610 static mrb_value
1611 mrb_str_downcase(mrb_state *mrb, mrb_value self)
1612 {
1613 mrb_value str;
1614
1615 str = mrb_str_dup(mrb, self);
1616 mrb_str_downcase_bang(mrb, str);
1617 return str;
1618 }
1619
1620 /* 15.2.10.5.16 */
1621 /*
1622 * call-seq:
1623 * str.empty? => true or false
1624 *
1625 * Returns <code>true</code> if <i>str</i> has a length of zero.
1626 *
1627 * "hello".empty? #=> false
1628 * "".empty? #=> true
1629 */
1630 static mrb_value
1631 mrb_str_empty_p(mrb_state *mrb, mrb_value self)
1632 {
1633 struct RString *s = mrb_str_ptr(self);
1634
1635 return mrb_bool_value(RSTR_LEN(s) == 0);
1636 }
1637
1638 /* 15.2.10.5.17 */
1639 /*
1640 * call-seq:
1641 * str.eql?(other) => true or false
1642 *
1643 * Two strings are equal if the have the same length and content.
1644 */
1645 static mrb_value
1646 mrb_str_eql(mrb_state *mrb, mrb_value self)
1647 {
1648 mrb_value str2 = mrb_get_arg1(mrb);
1649 mrb_bool eql_p;
1650
1651 eql_p = (mrb_string_p(str2)) && str_eql(mrb, self, str2);
1652
1653 return mrb_bool_value(eql_p);
1654 }
1655
1656 MRB_API mrb_value
1657 mrb_str_substr(mrb_state *mrb, mrb_value str, mrb_int beg, mrb_int len)
1658 {
1659 return str_substr(mrb, str, beg, len);
1660 }
1661
1662 /*
1663 * 32 bit magic FNV-0 and FNV-1 prime
1664 b */
1665 #define FNV_32_PRIME ((uint32_t)0x01000193)
1666 #define FNV1_32_INIT ((uint32_t)0x811c9dc5)
1667
1668 uint32_t
1669 mrb_byte_hash_step(const uint8_t *s, mrb_int len, uint32_t hval)
1670 {
1671 const uint8_t *send = s + len;
1672
1673 /*
1674 * FNV-1 hash each octet in the buffer
1675 */
1676 while (s < send) {
1677 /* multiply by the 32 bit FNV magic prime mod 2^32 */
1678 #if defined(NO_FNV_GCC_OPTIMIZATION)
1679 hval *= FNV_32_PRIME;
1680 #else
1681 hval += (hval<<1) + (hval<<4) + (hval<<7) + (hval<<8) + (hval<<24);
1682 #endif
1683
1684 /* xor the bottom with the current octet */
1685 hval ^= (uint32_t)*s++;
1686 }
1687
1688 /* return our new hash value */
1689 return hval;
1690 }
1691
1692 uint32_t
1693 mrb_byte_hash(const uint8_t *s, mrb_int len)
1694 {
1695 return mrb_byte_hash_step(s, len, FNV1_32_INIT);
1696 }
1697
1698 uint32_t
1699 mrb_str_hash(mrb_state *mrb, mrb_value str)
1700 {
1701 struct RString *s = mrb_str_ptr(str);
1702 return mrb_byte_hash((uint8_t*)RSTR_PTR(s), RSTR_LEN(s));
1703 }
1704
1705 /* 15.2.10.5.20 */
1706 /*
1707 * call-seq:
1708 * str.hash => int
1709 *
1710 * Return a hash based on the string's length and content.
1711 */
1712 static mrb_value
1713 mrb_str_hash_m(mrb_state *mrb, mrb_value self)
1714 {
1715 mrb_int key = mrb_str_hash(mrb, self);
1716 return mrb_int_value(mrb, key);
1717 }
1718
1719 /* 15.2.10.5.21 */
1720 /*
1721 * call-seq:
1722 * str.include? other_str => true or false
1723 * str.include? int => true or false
1724 *
1725 * Returns <code>true</code> if <i>str</i> contains the given string or
1726 * character.
1727 *
1728 * "hello".include? "lo" #=> true
1729 * "hello".include? "ol" #=> false
1730 * "hello".include? ?h #=> true
1731 */
1732 static mrb_value
1733 mrb_str_include(mrb_state *mrb, mrb_value self)
1734 {
1735 mrb_value str2;
1736
1737 mrb_get_args(mrb, "S", &str2);
1738 if (str_index_str(mrb, self, str2, 0) < 0)
1739 return mrb_bool_value(FALSE);
1740 return mrb_bool_value(TRUE);
1741 }
1742
1743 /*
1744 * call-seq:
1745 * str.byteindex(substring, offset = 0) -> integer or nil
1746 *
1747 * Returns the \Integer byte-based index of the first occurrence of the given +substring+,
1748 * or +nil+ if none found:
1749 *
1750 * 'foo'.byteindex('f') # => 0
1751 * 'foo'.byteindex('oo') # => 1
1752 * 'foo'.byteindex('ooo') # => nil
1753 */
1754 static mrb_value
1755 mrb_str_byteindex_m(mrb_state *mrb, mrb_value str)
1756 {
1757 mrb_value sub;
1758 mrb_int pos;
1759
1760 if (mrb_get_args(mrb, "S|i", &sub, &pos) == 1) {
1761 pos = 0;
1762 }
1763 else if (pos < 0) {
1764 pos += RSTRING_LEN(str);
1765 if (pos < 0) {
1766 return mrb_nil_value();
1767 }
1768 }
1769 pos = str_index_str(mrb, str, sub, pos);
1770
1771 if (pos == -1) return mrb_nil_value();
1772 return mrb_int_value(mrb, pos);
1773 }
1774
1775 /* 15.2.10.5.22 */
1776 /*
1777 * call-seq:
1778 * str.index(substring [, offset]) => int or nil
1779 *
1780 * Returns the index of the first occurrence of the given
1781 * <i>substring</i>. Returns <code>nil</code> if not found.
1782 * If the second parameter is present, it
1783 * specifies the position in the string to begin the search.
1784 *
1785 * "hello".index('l') #=> 2
1786 * "hello".index('lo') #=> 3
1787 * "hello".index('a') #=> nil
1788 * "hello".index('l', -2) #=> 3
1789 */
1790 #ifdef MRB_UTF8_STRING
1791 static mrb_value
1792 mrb_str_index_m(mrb_state *mrb, mrb_value str)
1793 {
1794 if (RSTR_ASCII_P(mrb_str_ptr(str))) {
1795 return mrb_str_byteindex_m(mrb, str);
1796 }
1797
1798 mrb_value sub;
1799 mrb_int pos;
1800
1801 if (mrb_get_args(mrb, "S|i", &sub, &pos) == 1) {
1802 pos = 0;
1803 }
1804 else if (pos < 0) {
1805 mrb_int clen = RSTRING_CHAR_LEN(str);
1806 pos += clen;
1807 if (pos < 0) {
1808 return mrb_nil_value();
1809 }
1810 }
1811 pos = str_index_str_by_char(mrb, str, sub, pos);
1812
1813 if (pos == -1) return mrb_nil_value();
1814 return mrb_int_value(mrb, pos);
1815 }
1816 #else
1817 #define mrb_str_index_m mrb_str_byteindex_m
1818 #endif
1819
1820 /* 15.2.10.5.24 */
1821 /* 15.2.10.5.28 */
1822 /*
1823 * call-seq:
1824 * str.replace(other_str) => str
1825 *
1826 * s = "hello" #=> "hello"
1827 * s.replace "world" #=> "world"
1828 */
1829 static mrb_value
1830 mrb_str_replace(mrb_state *mrb, mrb_value str)
1831 {
1832 mrb_value str2;
1833
1834 mrb_get_args(mrb, "S", &str2);
1835 return str_replace(mrb, mrb_str_ptr(str), mrb_str_ptr(str2));
1836 }
1837
1838 /* 15.2.10.5.23 */
1839 /*
1840 * call-seq:
1841 * String.new(str="") => new_str
1842 *
1843 * Returns a new string object containing a copy of <i>str</i>.
1844 */
1845 static mrb_value
1846 mrb_str_init(mrb_state *mrb, mrb_value self)
1847 {
1848 mrb_value str2;
1849
1850 if (mrb_get_args(mrb, "|S", &str2) == 0) {
1851 struct RString *s = str_new(mrb, 0, 0);
1852 str2 = mrb_obj_value(s);
1853 }
1854 str_replace(mrb, mrb_str_ptr(self), mrb_str_ptr(str2));
1855 return self;
1856 }
1857
1858 /* 15.2.10.5.25 */
1859 /* 15.2.10.5.41 */
1860 /*
1861 * call-seq:
1862 * str.intern => symbol
1863 * str.to_sym => symbol
1864 *
1865 * Returns the <code>Symbol</code> corresponding to <i>str</i>, creating the
1866 * symbol if it did not previously exist.
1867 *
1868 * "Koala".intern #=> :Koala
1869 * s = 'cat'.to_sym #=> :cat
1870 * s == :cat #=> true
1871 * s = '@cat'.to_sym #=> :@cat
1872 * s == :@cat #=> true
1873 *
1874 * This can also be used to create symbols that cannot be represented using the
1875 * <code>:xxx</code> notation.
1876 *
1877 * 'cat and dog'.to_sym #=> :"cat and dog"
1878 */
1879 MRB_API mrb_value
1880 mrb_str_intern(mrb_state *mrb, mrb_value self)
1881 {
1882 return mrb_symbol_value(mrb_intern_str(mrb, self));
1883 }
1884 /* ---------------------------------- */
1885 MRB_API mrb_value
1886 mrb_obj_as_string(mrb_state *mrb, mrb_value obj)
1887 {
1888 switch (mrb_type(obj)) {
1889 case MRB_TT_STRING:
1890 return obj;
1891 case MRB_TT_SYMBOL:
1892 return mrb_sym_str(mrb, mrb_symbol(obj));
1893 case MRB_TT_INTEGER:
1894 return mrb_integer_to_str(mrb, obj, 10);
1895 case MRB_TT_SCLASS:
1896 case MRB_TT_CLASS:
1897 case MRB_TT_MODULE:
1898 return mrb_mod_to_s(mrb, obj);
1899 default:
1900 return mrb_type_convert(mrb, obj, MRB_TT_STRING, MRB_SYM(to_s));
1901 }
1902 }
1903
1904 MRB_API mrb_value
1905 mrb_ptr_to_str(mrb_state *mrb, void *p)
1906 {
1907 struct RString *p_str;
1908 char *p1;
1909 char *p2;
1910 uintptr_t n = (uintptr_t)p;
1911
1912 p_str = str_new(mrb, NULL, 2 + sizeof(uintptr_t) * CHAR_BIT / 4);
1913 p1 = RSTR_PTR(p_str);
1914 *p1++ = '0';
1915 *p1++ = 'x';
1916 p2 = p1;
1917
1918 do {
1919 *p2++ = mrb_digitmap[n % 16];
1920 n /= 16;
1921 } while (n > 0);
1922 *p2 = '\0';
1923 RSTR_SET_LEN(p_str, (mrb_int)(p2 - RSTR_PTR(p_str)));
1924
1925 while (p1 < p2) {
1926 const char c = *p1;
1927 *p1++ = *--p2;
1928 *p2 = c;
1929 }
1930
1931 return mrb_obj_value(p_str);
1932 }
1933
1934 static inline void
1935 str_reverse(char *p, char *e)
1936 {
1937 char c;
1938
1939 while (p < e) {
1940 c = *p;
1941 *p++ = *e;
1942 *e-- = c;
1943 }
1944 }
1945
1946 /* 15.2.10.5.30 */
1947 /*
1948 * call-seq:
1949 * str.reverse! => str
1950 *
1951 * Reverses <i>str</i> in place.
1952 */
1953 static mrb_value
1954 mrb_str_reverse_bang(mrb_state *mrb, mrb_value str)
1955 {
1956 struct RString *s = mrb_str_ptr(str);
1957 char *p, *e;
1958
1959 #ifdef MRB_UTF8_STRING
1960 mrb_int utf8_len = RSTRING_CHAR_LEN(str);
1961 mrb_int len = RSTR_LEN(s);
1962
1963 if (utf8_len < 2) return str;
1964 if (utf8_len < len) {
1965 mrb_str_modify(mrb, s);
1966 p = RSTR_PTR(s);
1967 e = p + RSTR_LEN(s);
1968 while (p<e) {
1969 mrb_int clen = mrb_utf8len(p, e);
1970 str_reverse(p, p + clen - 1);
1971 p += clen;
1972 }
1973 goto bytes;
1974 }
1975 #endif
1976
1977 if (RSTR_LEN(s) > 1) {
1978 mrb_str_modify(mrb, s);
1979 goto bytes;
1980 }
1981 return str;
1982
1983 bytes:
1984 p = RSTR_PTR(s);
1985 e = p + RSTR_LEN(s) - 1;
1986 str_reverse(p, e);
1987 return str;
1988 }
1989
1990 /* ---------------------------------- */
1991 /* 15.2.10.5.29 */
1992 /*
1993 * call-seq:
1994 * str.reverse => new_str
1995 *
1996 * Returns a new string with the characters from <i>str</i> in reverse order.
1997 *
1998 * "stressed".reverse #=> "desserts"
1999 */
2000 static mrb_value
2001 mrb_str_reverse(mrb_state *mrb, mrb_value str)
2002 {
2003 mrb_value str2 = mrb_str_dup(mrb, str);
2004 mrb_str_reverse_bang(mrb, str2);
2005 return str2;
2006 }
2007
2008 /*
2009 * call-seq:
2010 * byterindex(substring, offset = self.bytesize) -> integer or nil
2011 *
2012 * Returns the \Integer byte-based index of the _last_ occurrence of the given +substring+,
2013 * or +nil+ if none found:
2014 *
2015 * 'foo'.byterindex('f') # => 0
2016 * 'foo'.byterindex('o') # => 2
2017 * 'foo'.byterindex('oo') # => 1
2018 * 'foo'.byterindex('ooo') # => nil
2019 */
2020 static mrb_value
2021 mrb_str_byterindex_m(mrb_state *mrb, mrb_value str)
2022 {
2023 mrb_value sub;
2024 mrb_int pos;
2025 mrb_int len = RSTRING_LEN(str);
2026
2027 if (mrb_get_args(mrb, "S|i", &sub, &pos) == 1) {
2028 pos = len;
2029 }
2030 else {
2031 if (pos < 0) {
2032 pos += len;
2033 if (pos < 0) {
2034 return mrb_nil_value();
2035 }
2036 }
2037 if (pos > len) pos = len;
2038 }
2039 pos = str_rindex(mrb, str, sub, pos);
2040 if (pos < 0) {
2041 return mrb_nil_value();
2042 }
2043 return mrb_int_value(mrb, pos);
2044 }
2045
2046 /* 15.2.10.5.31 */
2047 /*
2048 * call-seq:
2049 * str.rindex(substring [, offset]) => int or nil
2050 *
2051 * Returns the index of the last occurrence of the given <i>substring</i>.
2052 * Returns <code>nil</code> if not found. If the second parameter is
2053 * present, it specifies the position in the string to end the
2054 * search---characters beyond this point will not be considered.
2055 *
2056 * "hello".rindex('e') #=> 1
2057 * "hello".rindex('l') #=> 3
2058 * "hello".rindex('a') #=> nil
2059 * "hello".rindex('l', 2) #=> 2
2060 */
2061 #ifdef MRB_UTF8_STRING
2062 static mrb_value
2063 mrb_str_rindex_m(mrb_state *mrb, mrb_value str)
2064 {
2065 if (RSTR_ASCII_P(mrb_str_ptr(str))) {
2066 return mrb_str_byterindex_m(mrb, str);
2067 }
2068
2069 mrb_value sub;
2070 mrb_int pos;
2071
2072 if (mrb_get_args(mrb, "S|i", &sub, &pos) == 1) {
2073 pos = RSTRING_CHAR_LEN(str);
2074 pos = chars2bytes(str, 0, pos);
2075 }
2076 else if (pos >= 0) {
2077 pos = chars2bytes(str, 0, pos);
2078 }
2079 else {
2080 const char *p = RSTRING_PTR(str);
2081 const char *e = RSTRING_END(str);
2082 while (pos++ < 0 && p < e) {
2083 e = char_backtrack(p, e);
2084 }
2085 if (p == e) return mrb_nil_value();
2086 pos = (mrb_int)(e - p);
2087 }
2088 pos = str_rindex(mrb, str, sub, pos);
2089 if (pos >= 0) {
2090 pos = bytes2chars(RSTRING_PTR(str), RSTRING_LEN(str), pos);
2091 BYTES_ALIGN_CHECK(pos);
2092 return mrb_int_value(mrb, pos);
2093 }
2094 return mrb_nil_value();
2095 }
2096 #else
2097 #define mrb_str_rindex_m mrb_str_byterindex_m
2098 #endif
2099
2100 /* 15.2.10.5.35 */
2101
2102 /*
2103 * call-seq:
2104 * str.split(separator=nil, [limit]) => anArray
2105 *
2106 * Divides <i>str</i> into substrings based on a delimiter, returning an array
2107 * of these substrings.
2108 *
2109 * If <i>separator</i> is a <code>String</code>, then its contents are used as
2110 * the delimiter when splitting <i>str</i>. If <i>separator</i> is a single
2111 * space, <i>str</i> is split on whitespace, with leading whitespace and runs
2112 * of contiguous whitespace characters ignored.
2113 *
2114 * If <i>separator</i> is omitted or <code>nil</code> (which is the default),
2115 * <i>str</i> is split on whitespace as if ' ' were specified.
2116 *
2117 * If the <i>limit</i> parameter is omitted, trailing null fields are
2118 * suppressed. If <i>limit</i> is a positive number, at most that number of
2119 * fields will be returned (if <i>limit</i> is <code>1</code>, the entire
2120 * string is returned as the only entry in an array). If negative, there is no
2121 * limit to the number of fields returned, and trailing null fields are not
2122 * suppressed.
2123 *
2124 * " now's the time".split #=> ["now's", "the", "time"]
2125 * " now's the time".split(' ') #=> ["now's", "the", "time"]
2126 *
2127 * "mellow yellow".split("ello") #=> ["m", "w y", "w"]
2128 * "1,2,,3,4,,".split(',') #=> ["1", "2", "", "3", "4"]
2129 * "1,2,,3,4,,".split(',', 4) #=> ["1", "2", "", "3,4,,"]
2130 * "1,2,,3,4,,".split(',', -4) #=> ["1", "2", "", "3", "4", "", ""]
2131 */
2132
2133 static mrb_value
2134 mrb_str_split_m(mrb_state *mrb, mrb_value str)
2135 {
2136 mrb_int argc;
2137 mrb_value spat = mrb_nil_value();
2138 enum {awk, string} split_type = string;
2139 mrb_int i = 0;
2140 mrb_int beg;
2141 mrb_int end;
2142 mrb_int lim = 0;
2143 mrb_bool lim_p;
2144 mrb_value result, tmp;
2145
2146 argc = mrb_get_args(mrb, "|oi", &spat, &lim);
2147 lim_p = (lim > 0 && argc == 2);
2148 if (argc == 2) {
2149 if (lim == 1) {
2150 if (RSTRING_LEN(str) == 0)
2151 return mrb_ary_new_capa(mrb, 0);
2152 return mrb_ary_new_from_values(mrb, 1, &str);
2153 }
2154 i = 1;
2155 }
2156
2157 if (argc == 0 || mrb_nil_p(spat)) {
2158 split_type = awk;
2159 }
2160 else if (!mrb_string_p(spat)) {
2161 mrb_raise(mrb, E_TYPE_ERROR, "expected String");
2162 }
2163 else if (RSTRING_LEN(spat) == 1 && RSTRING_PTR(spat)[0] == ' ') {
2164 split_type = awk;
2165 }
2166
2167 result = mrb_ary_new(mrb);
2168 beg = 0;
2169 if (split_type == awk) {
2170 mrb_bool skip = TRUE;
2171 mrb_int idx = 0;
2172 mrb_int str_len = RSTRING_LEN(str);
2173 unsigned int c;
2174 int ai = mrb_gc_arena_save(mrb);
2175
2176 idx = end = beg;
2177 while (idx < str_len) {
2178 c = (unsigned char)RSTRING_PTR(str)[idx++];
2179 if (skip) {
2180 if (ISSPACE(c)) {
2181 beg = idx;
2182 }
2183 else {
2184 end = idx;
2185 skip = FALSE;
2186 if (lim_p && lim <= i) break;
2187 }
2188 }
2189 else if (ISSPACE(c)) {
2190 mrb_ary_push(mrb, result, mrb_str_byte_subseq(mrb, str, beg, end-beg));
2191 mrb_gc_arena_restore(mrb, ai);
2192 skip = TRUE;
2193 beg = idx;
2194 if (lim_p) i++;
2195 }
2196 else {
2197 end = idx;
2198 }
2199 }
2200 }
2201 else { /* split_type == string */
2202 mrb_int str_len = RSTRING_LEN(str);
2203 mrb_int pat_len = RSTRING_LEN(spat);
2204 mrb_int idx = 0;
2205 int ai = mrb_gc_arena_save(mrb);
2206
2207 while (idx < str_len) {
2208 if (pat_len > 0) {
2209 end = mrb_memsearch(RSTRING_PTR(spat), pat_len, RSTRING_PTR(str)+idx, str_len - idx);
2210 if (end < 0) break;
2211 }
2212 else {
2213 end = chars2bytes(str, idx, 1);
2214 }
2215 mrb_ary_push(mrb, result, mrb_str_byte_subseq(mrb, str, idx, end));
2216 mrb_gc_arena_restore(mrb, ai);
2217 idx += end + pat_len;
2218 if (lim_p && lim <= ++i) break;
2219 }
2220 beg = idx;
2221 }
2222 if (RSTRING_LEN(str) > 0 && (lim_p || RSTRING_LEN(str) > beg || lim < 0)) {
2223 if (RSTRING_LEN(str) == beg) {
2224 tmp = mrb_str_new(mrb, 0, 0);
2225 }
2226 else {
2227 tmp = mrb_str_byte_subseq(mrb, str, beg, RSTRING_LEN(str)-beg);
2228 }
2229 mrb_ary_push(mrb, result, tmp);
2230 }
2231 if (!lim_p && lim == 0) {
2232 mrb_int len;
2233 while ((len = RARRAY_LEN(result)) > 0 &&
2234 (tmp = RARRAY_PTR(result)[len-1], RSTRING_LEN(tmp) == 0))
2235 mrb_ary_pop(mrb, result);
2236 }
2237
2238 return result;
2239 }
2240
2241 static mrb_bool
2242 trailingbad(const char *str, const char *p, const char *pend)
2243 {
2244 if (p == str) return TRUE; /* no number */
2245 if (*(p - 1) == '_') return TRUE; /* trailing '_' */
2246 while (p<pend && ISSPACE(*p)) p++;
2247 if (p<pend) return TRUE; /* trailing garbage */
2248 return FALSE;
2249 }
2250
2251 static mrb_value
2252 mrb_str_len_to_integer(mrb_state *mrb, const char *str, size_t len, mrb_int base, int badcheck)
2253 {
2254 const char *p = str;
2255 const char *pend = str + len;
2256 #ifdef MRB_USE_BIGINT
2257 const char *p2 = NULL;
2258 #endif
2259 char sign = 1;
2260 int c;
2261 mrb_int n = 0;
2262 mrb_int val;
2263
2264 #define conv_digit(c) \
2265 (ISDIGIT(c) ? ((c) - '0') : \
2266 ISLOWER(c) ? ((c) - 'a' + 10) : \
2267 ISUPPER(c) ? ((c) - 'A' + 10) : \
2268 -1)
2269
2270 if (!p) {
2271 if (badcheck) goto bad;
2272 return mrb_fixnum_value(0);
2273 }
2274 while (p<pend && ISSPACE(*p))
2275 p++;
2276
2277 if (p[0] == '+') {
2278 p++;
2279 }
2280 else if (p[0] == '-') {
2281 p++;
2282 sign = 0;
2283 }
2284 if (base <= 0) {
2285 if (p[0] == '0') {
2286 switch (p[1]) {
2287 case 'x': case 'X':
2288 base = 16;
2289 break;
2290 case 'b': case 'B':
2291 base = 2;
2292 break;
2293 case 'o': case 'O':
2294 base = 8;
2295 break;
2296 case 'd': case 'D':
2297 base = 10;
2298 break;
2299 default:
2300 base = 8;
2301 break;
2302 }
2303 }
2304 else if (base < -1) {
2305 base = -base;
2306 }
2307 else {
2308 base = 10;
2309 }
2310 }
2311 switch (base) {
2312 case 2:
2313 if (p[0] == '0' && (p[1] == 'b'||p[1] == 'B')) {
2314 p += 2;
2315 }
2316 break;
2317 case 3:
2318 break;
2319 case 8:
2320 if (p[0] == '0' && (p[1] == 'o'||p[1] == 'O')) {
2321 p += 2;
2322 }
2323 case 4: case 5: case 6: case 7:
2324 break;
2325 case 10:
2326 if (p[0] == '0' && (p[1] == 'd'||p[1] == 'D')) {
2327 p += 2;
2328 }
2329 case 9: case 11: case 12: case 13: case 14: case 15:
2330 break;
2331 case 16:
2332 if (p[0] == '0' && (p[1] == 'x'||p[1] == 'X')) {
2333 p += 2;
2334 }
2335 break;
2336 default:
2337 if (base < 2 || 36 < base) {
2338 mrb_raisef(mrb, E_ARGUMENT_ERROR, "illegal radix %i", base);
2339 }
2340 break;
2341 } /* end of switch (base) { */
2342 if (p>=pend) {
2343 if (badcheck) goto bad;
2344 return mrb_fixnum_value(0);
2345 }
2346 if (*p == '0') { /* squeeze preceding 0s */
2347 p++;
2348 while (p<pend) {
2349 c = *p++;
2350 if (c == '_') {
2351 if (p<pend && *p == '_') {
2352 if (badcheck) goto bad;
2353 break;
2354 }
2355 continue;
2356 }
2357 if (c != '0') {
2358 p--;
2359 break;
2360 }
2361 }
2362 if (*(p - 1) == '0')
2363 p--;
2364 }
2365 if (p == pend || *p == '_') {
2366 if (badcheck) goto bad;
2367 return mrb_fixnum_value(0);
2368 }
2369 #ifdef MRB_USE_BIGINT
2370 p2 = p;
2371 #endif
2372 for (;p<pend; p++) {
2373 if (*p == '_') {
2374 p++;
2375 if (p==pend) {
2376 if (badcheck) goto bad;
2377 continue;
2378 }
2379 if (*p == '_') {
2380 if (badcheck) goto bad;
2381 break;
2382 }
2383 }
2384 if (badcheck && *p == '\0') {
2385 mrb_raise(mrb, E_ARGUMENT_ERROR, "string contains null byte");
2386 }
2387 c = conv_digit(*p);
2388 if (c < 0 || c >= base) {
2389 break;
2390 }
2391 if (mrb_int_mul_overflow(n, base, &n)) goto overflow;
2392 if (MRB_INT_MAX - c < n) {
2393 if (sign == 0 && MRB_INT_MAX - n == c - 1) {
2394 n = MRB_INT_MIN;
2395 sign = 1;
2396 break;
2397 }
2398 overflow:
2399 #ifdef MRB_USE_BIGINT
2400 ;
2401 const char *p3 = p2;
2402 while (p3 < pend) {
2403 char c = TOLOWER(*p3);
2404 const char *p4 = strchr(mrb_digitmap, c);
2405 if (p4 == NULL && c != '_') break;
2406 if (p4 - mrb_digitmap >= base) break;
2407 p3++;
2408 }
2409 if (badcheck && trailingbad(str, p, pend)) goto bad;
2410 return mrb_bint_new_str(mrb, p2, (mrb_int)(p3-p2), sign ? base : -base);
2411 #else
2412 mrb_raisef(mrb, E_RANGE_ERROR, "string (%l) too big for integer", str, pend-str);
2413 #endif
2414 }
2415 n += c;
2416 }
2417 val = (mrb_int)n;
2418 if (badcheck && trailingbad(str, p, pend)) goto bad;
2419 return mrb_int_value(mrb, sign ? val : -val);
2420 bad:
2421 mrb_raisef(mrb, E_ARGUMENT_ERROR, "invalid string for number(%!l)", str, pend-str);
2422 /* not reached */
2423 return mrb_fixnum_value(0);
2424 }
2425
2426 /* obslete: use RSTRING_CSTR() or mrb_string_cstr() */
2427 MRB_API const char*
2428 mrb_string_value_cstr(mrb_state *mrb, mrb_value *ptr)
2429 {
2430 struct RString *ps;
2431 const char *p;
2432 mrb_int len;
2433
2434 mrb_ensure_string_type(mrb, *ptr);
2435 ps = mrb_str_ptr(*ptr);
2436 check_null_byte(mrb, ps);
2437 p = RSTR_PTR(ps);
2438 len = RSTR_LEN(ps);
2439 if (p == NULL) return "";
2440 if (p[len] == '\0') {
2441 return p;
2442 }
2443
2444 /*
2445 * Even after str_modify_keep_ascii(), NULL termination is not ensured if
2446 * RSTR_SET_LEN() is used explicitly (e.g. String#delete_suffix!).
2447 */
2448 str_modify_keep_ascii(mrb, ps);
2449 RSTR_PTR(ps)[len] = '\0';
2450 return RSTR_PTR(ps);
2451 }
2452
2453 MRB_API const char*
2454 mrb_string_cstr(mrb_state *mrb, mrb_value str)
2455 {
2456 return mrb_string_value_cstr(mrb, &str);
2457 }
2458
2459 MRB_API mrb_value
2460 mrb_str_to_integer(mrb_state *mrb, mrb_value str, mrb_int base, mrb_bool badcheck)
2461 {
2462 const char *s;
2463 mrb_int len;
2464
2465 mrb_ensure_string_type(mrb, str);
2466 s = RSTRING_PTR(str);
2467 len = RSTRING_LEN(str);
2468 return mrb_str_len_to_integer(mrb, s, len, base, badcheck);
2469 }
2470
2471 /* 15.2.10.5.38 */
2472 /*
2473 * call-seq:
2474 * str.to_i(base=10) => integer
2475 *
2476 * Returns the result of interpreting leading characters in <i>str</i> as an
2477 * integer base <i>base</i> (between 2 and 36). Extraneous characters past the
2478 * end of a valid number are ignored. If there is not a valid number at the
2479 * start of <i>str</i>, <code>0</code> is returned. This method never raises an
2480 * exception.
2481 *
2482 * "12345".to_i #=> 12345
2483 * "99 red balloons".to_i #=> 99
2484 * "0a".to_i #=> 0
2485 * "0a".to_i(16) #=> 10
2486 * "hello".to_i #=> 0
2487 * "1100101".to_i(2) #=> 101
2488 * "1100101".to_i(8) #=> 294977
2489 * "1100101".to_i(10) #=> 1100101
2490 * "1100101".to_i(16) #=> 17826049
2491 */
2492 static mrb_value
2493 mrb_str_to_i(mrb_state *mrb, mrb_value self)
2494 {
2495 mrb_int base = 10;
2496
2497 mrb_get_args(mrb, "|i", &base);
2498 if (base < 0 || 36 < base) {
2499 mrb_raisef(mrb, E_ARGUMENT_ERROR, "illegal radix %i", base);
2500 }
2501 return mrb_str_to_integer(mrb, self, base, FALSE);
2502 }
2503
2504 #ifndef MRB_NO_FLOAT
2505 static double
2506 mrb_str_len_to_dbl(mrb_state *mrb, const char *s, size_t len, mrb_bool badcheck)
2507 {
2508 char buf[DBL_DIG * 4 + 20];
2509 const char *p = s, *p2;
2510 const char *pend = p + len;
2511 char *end;
2512 char *n;
2513 char prev = 0;
2514 double d;
2515 mrb_bool dot = FALSE;
2516
2517 if (!p) return 0.0;
2518 while (p<pend && ISSPACE(*p)) p++;
2519 p2 = p;
2520
2521 if (pend - p > 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
2522 mrb_value x;
2523
2524 if (!badcheck) return 0.0;
2525 x = mrb_str_len_to_integer(mrb, p, pend-p, 0, badcheck);
2526 if (mrb_integer_p(x))
2527 d = (double)mrb_integer(x);
2528 else /* if (mrb_float_p(x)) */
2529 d = mrb_float(x);
2530 return d;
2531 }
2532 while (p < pend) {
2533 if (!*p) {
2534 if (badcheck) {
2535 mrb_raise(mrb, E_ARGUMENT_ERROR, "string for Float contains null byte");
2536 /* not reached */
2537 }
2538 pend = p;
2539 p = p2;
2540 goto nocopy;
2541 }
2542 if (!badcheck && *p == ' ') {
2543 pend = p;
2544 p = p2;
2545 goto nocopy;
2546 }
2547 if (*p == '_') break;
2548 p++;
2549 }
2550 p = p2;
2551 n = buf;
2552 while (p < pend) {
2553 char c = *p++;
2554 if (c == '.') dot = TRUE;
2555 if (c == '_') {
2556 /* remove an underscore between digits */
2557 if (n == buf || !ISDIGIT(prev) || p == pend) {
2558 if (badcheck) goto bad;
2559 break;
2560 }
2561 }
2562 else if (badcheck && prev == '_' && !ISDIGIT(c)) goto bad;
2563 else {
2564 const char *bend = buf+sizeof(buf)-1;
2565 if (n==bend) { /* buffer overflow */
2566 if (dot) break; /* cut off remaining fractions */
2567 return INFINITY;
2568 }
2569 *n++ = c;
2570 }
2571 prev = c;
2572 }
2573 *n = '\0';
2574 p = buf;
2575 pend = n;
2576 nocopy:
2577 if (mrb_read_float(p, &end, &d) == FALSE) {
2578 if (badcheck) {
2579 bad:
2580 mrb_raisef(mrb, E_ARGUMENT_ERROR, "invalid string for float(%!s)", s);
2581 /* not reached */
2582 }
2583 return d;
2584 }
2585 if (badcheck) {
2586 if (!end || p == end) goto bad;
2587 while (end<pend && ISSPACE(*end)) end++;
2588 if (end<pend) goto bad;
2589 }
2590 return d;
2591 }
2592
2593 MRB_API double
2594 mrb_str_to_dbl(mrb_state *mrb, mrb_value str, mrb_bool badcheck)
2595 {
2596 return mrb_str_len_to_dbl(mrb, RSTRING_PTR(str), RSTRING_LEN(str), badcheck);
2597 }
2598
2599 /* 15.2.10.5.39 */
2600 /*
2601 * call-seq:
2602 * str.to_f => float
2603 *
2604 * Returns the result of interpreting leading characters in <i>str</i> as a
2605 * floating-point number. Extraneous characters past the end of a valid number
2606 * are ignored. If there is not a valid number at the start of <i>str</i>,
2607 * <code>0.0</code> is returned. This method never raises an exception.
2608 *
2609 * "123.45e1".to_f #=> 1234.5
2610 * "45.67 degrees".to_f #=> 45.67
2611 * "thx1138".to_f #=> 0.0
2612 */
2613 static mrb_value
2614 mrb_str_to_f(mrb_state *mrb, mrb_value self)
2615 {
2616 return mrb_float_value(mrb, mrb_str_to_dbl(mrb, self, FALSE));
2617 }
2618 #endif
2619
2620 /* 15.2.10.5.40 */
2621 /*
2622 * call-seq:
2623 * str.to_s => str
2624 *
2625 * Returns the receiver.
2626 */
2627 static mrb_value
2628 mrb_str_to_s(mrb_state *mrb, mrb_value self)
2629 {
2630 if (mrb_obj_class(mrb, self) != mrb->string_class) {
2631 return mrb_str_dup(mrb, self);
2632 }
2633 return self;
2634 }
2635
2636 /* 15.2.10.5.43 */
2637 /*
2638 * call-seq:
2639 * str.upcase! => str or nil
2640 *
2641 * Upcases the contents of <i>str</i>, returning <code>nil</code> if no changes
2642 * were made.
2643 */
2644 static mrb_value
2645 mrb_str_upcase_bang(mrb_state *mrb, mrb_value str)
2646 {
2647 struct RString *s = mrb_str_ptr(str);
2648 char *p, *pend;
2649 mrb_bool modify = FALSE;
2650
2651 mrb_str_modify_keep_ascii(mrb, s);
2652 p = RSTRING_PTR(str);
2653 pend = RSTRING_END(str);
2654 while (p < pend) {
2655 if (ISLOWER(*p)) {
2656 *p = TOUPPER(*p);
2657 modify = TRUE;
2658 }
2659 p++;
2660 }
2661
2662 if (modify) return str;
2663 return mrb_nil_value();
2664 }
2665
2666 /* 15.2.10.5.42 */
2667 /*
2668 * call-seq:
2669 * str.upcase => new_str
2670 *
2671 * Returns a copy of <i>str</i> with all lowercase letters replaced with their
2672 * uppercase counterparts. The operation is locale insensitive---only
2673 * characters 'a' to 'z' are affected.
2674 *
2675 * "hEllO".upcase #=> "HELLO"
2676 */
2677 static mrb_value
2678 mrb_str_upcase(mrb_state *mrb, mrb_value self)
2679 {
2680 mrb_value str;
2681
2682 str = mrb_str_dup(mrb, self);
2683 mrb_str_upcase_bang(mrb, str);
2684 return str;
2685 }
2686
2687 /*
2688 * call-seq:
2689 * str.dump -> new_str
2690 *
2691 * Produces a version of <i>str</i> with all nonprinting characters replaced by
2692 * <code>\nnn</code> notation and all special characters escaped.
2693 */
2694 mrb_value
2695 mrb_str_dump(mrb_state *mrb, mrb_value str)
2696 {
2697 return str_escape(mrb, str, FALSE);
2698 }
2699
2700 MRB_API mrb_value
2701 mrb_str_cat(mrb_state *mrb, mrb_value str, const char *ptr, size_t len)
2702 {
2703 struct RString *s = mrb_str_ptr(str);
2704 mrb_int capa;
2705 mrb_int total;
2706 ptrdiff_t off = -1;
2707
2708 if (len == 0) return str;
2709 mrb_str_modify(mrb, s);
2710 if (ptr >= RSTR_PTR(s) && ptr <= RSTR_PTR(s) + (size_t)RSTR_LEN(s)) {
2711 off = ptr - RSTR_PTR(s);
2712 }
2713
2714 capa = RSTR_CAPA(s);
2715 if (mrb_int_add_overflow(RSTR_LEN(s), len, &total)) {
2716 size_error:
2717 mrb_raise(mrb, E_ARGUMENT_ERROR, "string size too big");
2718 }
2719 if (capa <= total) {
2720 if (capa == 0) capa = 1;
2721 while (capa <= total) {
2722 if (mrb_int_mul_overflow(capa, 2, &capa)) goto size_error;
2723 }
2724 resize_capa(mrb, s, capa);
2725 }
2726 if (off != -1) {
2727 ptr = RSTR_PTR(s) + off;
2728 }
2729 memcpy(RSTR_PTR(s) + RSTR_LEN(s), ptr, len);
2730 RSTR_SET_LEN(s, total);
2731 RSTR_PTR(s)[total] = '\0'; /* sentinel */
2732 return str;
2733 }
2734
2735 MRB_API mrb_value
2736 mrb_str_cat_cstr(mrb_state *mrb, mrb_value str, const char *ptr)
2737 {
2738 return mrb_str_cat(mrb, str, ptr, ptr ? strlen(ptr) : 0);
2739 }
2740
2741 MRB_API mrb_value
2742 mrb_str_cat_str(mrb_state *mrb, mrb_value str, mrb_value str2)
2743 {
2744 if (mrb_str_ptr(str) == mrb_str_ptr(str2)) {
2745 mrb_str_modify(mrb, mrb_str_ptr(str));
2746 }
2747 return mrb_str_cat(mrb, str, RSTRING_PTR(str2), RSTRING_LEN(str2));
2748 }
2749
2750 MRB_API mrb_value
2751 mrb_str_append(mrb_state *mrb, mrb_value str1, mrb_value str2)
2752 {
2753 mrb_ensure_string_type(mrb, str2);
2754 return mrb_str_cat_str(mrb, str1, str2);
2755 }
2756
2757 /*
2758 * call-seq:
2759 * str.inspect -> string
2760 *
2761 * Returns a printable version of _str_, surrounded by quote marks,
2762 * with special characters escaped.
2763 *
2764 * str = "hello"
2765 * str[3] = "\b"
2766 * str.inspect #=> "\"hel\\bo\""
2767 */
2768 mrb_value
2769 mrb_str_inspect(mrb_state *mrb, mrb_value str)
2770 {
2771 return str_escape(mrb, str, TRUE);
2772 }
2773
2774 /*
2775 * call-seq:
2776 * str.bytes -> array of int
2777 *
2778 * Returns an array of bytes in _str_.
2779 *
2780 * str = "hello"
2781 * str.bytes #=> [104, 101, 108, 108, 111]
2782 */
2783 static mrb_value
2784 mrb_str_bytes(mrb_state *mrb, mrb_value str)
2785 {
2786 struct RString *s = mrb_str_ptr(str);
2787 mrb_value a = mrb_ary_new_capa(mrb, RSTR_LEN(s));
2788 unsigned char *p = (unsigned char*)(RSTR_PTR(s)), *pend = p + RSTR_LEN(s);
2789
2790 while (p < pend) {
2791 mrb_ary_push(mrb, a, mrb_fixnum_value(p[0]));
2792 p++;
2793 }
2794 return a;
2795 }
2796
2797 /*
2798 * call-seq:
2799 * str.getbyte(index) -> 0 .. 255
2800 *
2801 * returns the <i>index</i>th byte as an integer.
2802 */
2803 static mrb_value
2804 mrb_str_getbyte(mrb_state *mrb, mrb_value str)
2805 {
2806 mrb_int pos;
2807 mrb_get_args(mrb, "i", &pos);
2808
2809 if (pos < 0)
2810 pos += RSTRING_LEN(str);
2811 if (pos < 0 || RSTRING_LEN(str) <= pos)
2812 return mrb_nil_value();
2813
2814 return mrb_fixnum_value((unsigned char)RSTRING_PTR(str)[pos]);
2815 }
2816
2817 /*
2818 * call-seq:
2819 * str.setbyte(index, integer) -> integer
2820 *
2821 * modifies the <i>index</i>th byte as <i>integer</i>.
2822 */
2823 static mrb_value
2824 mrb_str_setbyte(mrb_state *mrb, mrb_value str)
2825 {
2826 mrb_int pos, byte;
2827 mrb_int len;
2828
2829 mrb_get_args(mrb, "ii", &pos, &byte);
2830
2831 len = RSTRING_LEN(str);
2832 if (pos < -len || len <= pos)
2833 mrb_raisef(mrb, E_INDEX_ERROR, "index %i out of string", pos);
2834 if (pos < 0)
2835 pos += len;
2836
2837 mrb_str_modify(mrb, mrb_str_ptr(str));
2838 byte &= 0xff;
2839 RSTRING_PTR(str)[pos] = (unsigned char)byte;
2840 return mrb_fixnum_value((unsigned char)byte);
2841 }
2842
2843 /*
2844 * call-seq:
2845 * str.byteslice(integer) -> new_str or nil
2846 * str.byteslice(integer, integer) -> new_str or nil
2847 * str.byteslice(range) -> new_str or nil
2848 *
2849 * Byte Reference---If passed a single Integer, returns a
2850 * substring of one byte at that position. If passed two Integer
2851 * objects, returns a substring starting at the offset given by the first, and
2852 * a length given by the second. If given a Range, a substring containing
2853 * bytes at offsets given by the range is returned. In all three cases, if
2854 * an offset is negative, it is counted from the end of <i>str</i>. Returns
2855 * <code>nil</code> if the initial offset falls outside the string, the length
2856 * is negative, or the beginning of the range is greater than the end.
2857 * The encoding of the resulted string keeps original encoding.
2858 *
2859 * "hello".byteslice(1) #=> "e"
2860 * "hello".byteslice(-1) #=> "o"
2861 * "hello".byteslice(1, 2) #=> "el"
2862 * "\x80\u3042".byteslice(1, 3) #=> "\u3042"
2863 * "\x03\u3042\xff".byteslice(1..3) #=> "\u3042"
2864 */
2865 static mrb_value
2866 mrb_str_byteslice(mrb_state *mrb, mrb_value str)
2867 {
2868 mrb_value a1;
2869 mrb_int str_len, beg, len;
2870 mrb_bool empty = TRUE;
2871
2872 len = mrb_get_argc(mrb);
2873 switch (len) {
2874 case 2:
2875 mrb_get_args(mrb, "ii", &beg, &len);
2876 str_len = RSTRING_LEN(str);
2877 break;
2878 case 1:
2879 a1 = mrb_get_arg1(mrb);
2880 str_len = RSTRING_LEN(str);
2881 if (mrb_range_p(a1)) {
2882 if (mrb_range_beg_len(mrb, a1, &beg, &len, str_len, TRUE) != MRB_RANGE_OK) {
2883 return mrb_nil_value();
2884 }
2885 }
2886 else {
2887 beg = mrb_as_int(mrb, a1);
2888 len = 1;
2889 empty = FALSE;
2890 }
2891 break;
2892 default:
2893 mrb_argnum_error(mrb, len, 1, 2);
2894 break;
2895 }
2896 if (mrb_str_beg_len(str_len, &beg, &len) && (empty || len != 0)) {
2897 return mrb_str_byte_subseq(mrb, str, beg, len);
2898 }
2899 else {
2900 return mrb_nil_value();
2901 }
2902 }
2903
2904 static mrb_value
2905 sub_replace(mrb_state *mrb, mrb_value self)
2906 {
2907 char *p, *match;
2908 mrb_int plen, mlen;
2909 mrb_int found, offset;
2910 mrb_value result;
2911
2912 mrb_get_args(mrb, "ssi", &p, &plen, &match, &mlen, &found);
2913 result = mrb_str_new(mrb, 0, 0);
2914 for (mrb_int i=0; i<plen; i++) {
2915 if (p[i] != '\\' || i+1==plen) {
2916 mrb_str_cat(mrb, result, p+i, 1);
2917 continue;
2918 }
2919 i++;
2920 switch (p[i]) {
2921 case '\\':
2922 mrb_str_cat(mrb, result, "\\", 1);
2923 break;
2924 case '`':
2925 mrb_str_cat(mrb, result, RSTRING_PTR(self), found);
2926 break;
2927 case '&': case '0':
2928 mrb_str_cat(mrb, result, match, mlen);
2929 break;
2930 case '\'':
2931 offset = found + mlen;
2932 if (RSTRING_LEN(self) > offset) {
2933 mrb_str_cat(mrb, result, RSTRING_PTR(self)+offset, RSTRING_LEN(self)-offset);
2934 }
2935 break;
2936 case '1': case '2': case '3':
2937 case '4': case '5': case '6':
2938 case '7': case '8': case '9':
2939 /* ignore sub-group match (no Regexp supported) */
2940 break;
2941 default:
2942 mrb_str_cat(mrb, result, &p[i-1], 2);
2943 break;
2944 }
2945 }
2946 return result;
2947 }
2948
2949
2950 static mrb_value
2951 str_bytesplice(mrb_state *mrb, mrb_value str, mrb_int idx1, mrb_int len1, mrb_value replace, mrb_int idx2, mrb_int len2)
2952 {
2953 struct RString *s = RSTRING(str);
2954 if (idx1 < 0) {
2955 idx1 += RSTR_LEN(s);
2956 }
2957 if (idx2 < 0) {
2958 idx2 += RSTRING_LEN(replace);
2959 }
2960 if (RSTR_LEN(s) < idx1 || idx1 < 0 || RSTRING_LEN(replace) < idx2 || idx2 < 0) {
2961 mrb_raise(mrb, E_INDEX_ERROR, "index out of string");
2962 }
2963 if (len1 < 0 || len2 < 0) {
2964 mrb_raise(mrb, E_INDEX_ERROR, "negative length");
2965 }
2966 mrb_int n;
2967 if (mrb_int_add_overflow(idx1, len1, &n) || RSTR_LEN(s) < n) {
2968 len1 = RSTR_LEN(s) - idx1;
2969 }
2970 if (mrb_int_add_overflow(idx2, len2, &n) || RSTRING_LEN(replace) < n) {
2971 len2 = RSTRING_LEN(replace) - idx2;
2972 }
2973 mrb_str_modify(mrb, s);
2974 if (len1 >= len2) {
2975 memmove(RSTR_PTR(s)+idx1, RSTRING_PTR(replace)+idx2, len2);
2976 if (len1 > len2) {
2977 memmove(RSTR_PTR(s)+idx1+len2, RSTR_PTR(s)+idx1+len1, RSTR_LEN(s)-(idx1+len1));
2978 RSTR_SET_LEN(s, RSTR_LEN(s)-(len1-len2));
2979 }
2980 }
2981 else { /* len1 < len2 */
2982 mrb_int slen = RSTR_LEN(s);
2983 mrb_str_resize(mrb, str, slen+len2-len1);
2984 memmove(RSTR_PTR(s)+idx1+len2, RSTR_PTR(s)+idx1+len1, slen-(idx1+len1));
2985 memmove(RSTR_PTR(s)+idx1, RSTRING_PTR(replace)+idx2, len2);
2986 }
2987 return str;
2988 }
2989
2990 /*
2991 * call-seq:
2992 * bytesplice(index, length, str) -> string
2993 * bytesplice(index, length, str, str_index, str_length) -> string
2994 * bytesplice(range, str) -> string
2995 * bytesplice(range, str, str_range) -> string
2996 *
2997 * Replaces some or all of the content of +self+ with +str+, and returns +self+.
2998 * The portion of the string affected is determined using
2999 * the same criteria as String#byteslice, except that +length+ cannot be omitted.
3000 * If the replacement string is not the same length as the text it is replacing,
3001 * the string will be adjusted accordingly.
3002 *
3003 * If +str_index+ and +str_length+, or +str_range+ are given, the content of +self+ is replaced by str.byteslice(str_index, str_length) or str.byteslice(str_range); however the substring of +str+ is not allocated as a new string.
3004 *
3005 * The form that take an Integer will raise an IndexError if the value is out
3006 * of range; the Range form will raise a RangeError.
3007 * If the beginning or ending offset does not land on character (codepoint)
3008 * boundary, an IndexError will be raised.
3009 */
3010 static mrb_value
3011 mrb_str_bytesplice(mrb_state *mrb, mrb_value str)
3012 {
3013 mrb_int idx1, len1, idx2, len2;
3014 mrb_value range1, range2, replace;
3015 switch (mrb_get_argc(mrb)) {
3016 case 3:
3017 mrb_get_args(mrb, "ooo", &range1, &replace, &range2);
3018 if (mrb_integer_p(range1)) {
3019 mrb_get_args(mrb, "iiS", &idx1, &len1, &replace);
3020 return str_bytesplice(mrb, str, idx1, len1, replace, 0, RSTRING_LEN(replace));
3021 }
3022 mrb_ensure_string_type(mrb, replace);
3023 if (mrb_range_beg_len(mrb, range1, &idx1, &len1, RSTRING_LEN(str), FALSE) != MRB_RANGE_OK) break;
3024 if (mrb_range_beg_len(mrb, range2, &idx2, &len2, RSTRING_LEN(replace), FALSE) != MRB_RANGE_OK) break;
3025 return str_bytesplice(mrb, str, idx1, len1, replace, idx2, len2);
3026 case 5:
3027 mrb_get_args(mrb, "iiSii", &idx1, &len1, &replace, &idx2, &len2);
3028 return str_bytesplice(mrb, str, idx1, len1, replace, idx2, len2);
3029 case 2:
3030 mrb_get_args(mrb, "oS", &range1, &replace);
3031 if (mrb_range_beg_len(mrb, range1, &idx1, &len1, RSTRING_LEN(str), FALSE) == MRB_RANGE_OK) {
3032 return str_bytesplice(mrb, str, idx1, len1, replace, 0, RSTRING_LEN(replace));
3033 }
3034 default:
3035 break;
3036 }
3037 mrb_raise(mrb, E_ARGUMENT_ERROR, "wrong number of arumgnts");
3038 }
3039
3040 /* ---------------------------*/
3041 void
3042 mrb_init_string(mrb_state *mrb)
3043 {
3044 struct RClass *s;
3045
3046 mrb_static_assert(RSTRING_EMBED_LEN_MAX < (1 << MRB_STR_EMBED_LEN_BIT),
3047 "pointer size too big for embedded string");
3048
3049 mrb->string_class = s = mrb_define_class(mrb, "String", mrb->object_class); /* 15.2.10 */
3050 MRB_SET_INSTANCE_TT(s, MRB_TT_STRING);
3051
3052 mrb_define_method(mrb, s, "bytesize", mrb_str_bytesize, MRB_ARGS_NONE());
3053
3054 mrb_define_method(mrb, s, "<=>", mrb_str_cmp_m, MRB_ARGS_REQ(1)); /* 15.2.10.5.1 */
3055 mrb_define_method(mrb, s, "==", mrb_str_equal_m, MRB_ARGS_REQ(1)); /* 15.2.10.5.2 */
3056 mrb_define_method(mrb, s, "+", mrb_str_plus_m, MRB_ARGS_REQ(1)); /* 15.2.10.5.4 */
3057 mrb_define_method(mrb, s, "*", mrb_str_times, MRB_ARGS_REQ(1)); /* 15.2.10.5.5 */
3058 mrb_define_method(mrb, s, "[]", mrb_str_aref_m, MRB_ARGS_ANY()); /* 15.2.10.5.6 */
3059 mrb_define_method(mrb, s, "[]=", mrb_str_aset_m, MRB_ARGS_ANY());
3060 mrb_define_method(mrb, s, "capitalize", mrb_str_capitalize, MRB_ARGS_NONE()); /* 15.2.10.5.7 */
3061 mrb_define_method(mrb, s, "capitalize!", mrb_str_capitalize_bang, MRB_ARGS_NONE()); /* 15.2.10.5.8 */
3062 mrb_define_method(mrb, s, "chomp", mrb_str_chomp, MRB_ARGS_ANY()); /* 15.2.10.5.9 */
3063 mrb_define_method(mrb, s, "chomp!", mrb_str_chomp_bang, MRB_ARGS_ANY()); /* 15.2.10.5.10 */
3064 mrb_define_method(mrb, s, "chop", mrb_str_chop, MRB_ARGS_NONE()); /* 15.2.10.5.11 */
3065 mrb_define_method(mrb, s, "chop!", mrb_str_chop_bang, MRB_ARGS_NONE()); /* 15.2.10.5.12 */
3066 mrb_define_method(mrb, s, "downcase", mrb_str_downcase, MRB_ARGS_NONE()); /* 15.2.10.5.13 */
3067 mrb_define_method(mrb, s, "downcase!", mrb_str_downcase_bang, MRB_ARGS_NONE()); /* 15.2.10.5.14 */
3068 mrb_define_method(mrb, s, "empty?", mrb_str_empty_p, MRB_ARGS_NONE()); /* 15.2.10.5.16 */
3069 mrb_define_method(mrb, s, "eql?", mrb_str_eql, MRB_ARGS_REQ(1)); /* 15.2.10.5.17 */
3070
3071 mrb_define_method(mrb, s, "hash", mrb_str_hash_m, MRB_ARGS_NONE()); /* 15.2.10.5.20 */
3072 mrb_define_method(mrb, s, "include?", mrb_str_include, MRB_ARGS_REQ(1)); /* 15.2.10.5.21 */
3073 mrb_define_method(mrb, s, "index", mrb_str_index_m, MRB_ARGS_ARG(1,1)); /* 15.2.10.5.22 */
3074 mrb_define_method(mrb, s, "initialize", mrb_str_init, MRB_ARGS_REQ(1)); /* 15.2.10.5.23 */
3075 mrb_define_method(mrb, s, "initialize_copy", mrb_str_replace, MRB_ARGS_REQ(1)); /* 15.2.10.5.24 */
3076 mrb_define_method(mrb, s, "intern", mrb_str_intern, MRB_ARGS_NONE()); /* 15.2.10.5.25 */
3077 mrb_define_method(mrb, s, "length", mrb_str_size, MRB_ARGS_NONE()); /* 15.2.10.5.26 */
3078 mrb_define_method(mrb, s, "replace", mrb_str_replace, MRB_ARGS_REQ(1)); /* 15.2.10.5.28 */
3079 mrb_define_method(mrb, s, "reverse", mrb_str_reverse, MRB_ARGS_NONE()); /* 15.2.10.5.29 */
3080 mrb_define_method(mrb, s, "reverse!", mrb_str_reverse_bang, MRB_ARGS_NONE()); /* 15.2.10.5.30 */
3081 mrb_define_method(mrb, s, "rindex", mrb_str_rindex_m, MRB_ARGS_ANY()); /* 15.2.10.5.31 */
3082 mrb_define_method(mrb, s, "size", mrb_str_size, MRB_ARGS_NONE()); /* 15.2.10.5.33 */
3083 mrb_define_method(mrb, s, "slice", mrb_str_aref_m, MRB_ARGS_ANY()); /* 15.2.10.5.34 */
3084 mrb_define_method(mrb, s, "split", mrb_str_split_m, MRB_ARGS_ANY()); /* 15.2.10.5.35 */
3085
3086 #ifndef MRB_NO_FLOAT
3087 mrb_define_method(mrb, s, "to_f", mrb_str_to_f, MRB_ARGS_NONE()); /* 15.2.10.5.38 */
3088 #endif
3089 mrb_define_method(mrb, s, "to_i", mrb_str_to_i, MRB_ARGS_ANY()); /* 15.2.10.5.39 */
3090 mrb_define_method(mrb, s, "to_s", mrb_str_to_s, MRB_ARGS_NONE()); /* 15.2.10.5.40 */
3091 mrb_define_method(mrb, s, "to_str", mrb_str_to_s, MRB_ARGS_NONE());
3092 mrb_define_method(mrb, s, "to_sym", mrb_str_intern, MRB_ARGS_NONE()); /* 15.2.10.5.41 */
3093 mrb_define_method(mrb, s, "upcase", mrb_str_upcase, MRB_ARGS_NONE()); /* 15.2.10.5.42 */
3094 mrb_define_method(mrb, s, "upcase!", mrb_str_upcase_bang, MRB_ARGS_NONE()); /* 15.2.10.5.43 */
3095 mrb_define_method(mrb, s, "inspect", mrb_str_inspect, MRB_ARGS_NONE()); /* 15.2.10.5.46(x) */
3096 mrb_define_method(mrb, s, "bytes", mrb_str_bytes, MRB_ARGS_NONE());
3097
3098 mrb_define_method(mrb, s, "getbyte", mrb_str_getbyte, MRB_ARGS_REQ(1));
3099 mrb_define_method(mrb, s, "setbyte", mrb_str_setbyte, MRB_ARGS_REQ(2));
3100 mrb_define_method(mrb, s, "byteindex", mrb_str_byteindex_m, MRB_ARGS_ARG(1,1));
3101 mrb_define_method(mrb, s, "byterindex", mrb_str_byterindex_m, MRB_ARGS_ARG(1,1));
3102 mrb_define_method(mrb, s, "byteslice", mrb_str_byteslice, MRB_ARGS_ARG(1,1));
3103 mrb_define_method(mrb, s, "bytesplice", mrb_str_bytesplice, MRB_ARGS_ANY());
3104
3105 mrb_define_method(mrb, s, "__sub_replace", sub_replace, MRB_ARGS_REQ(3)); /* internal */
3106 }