string.c 67.2 KB
Newer Older
mimaki's avatar
mimaki committed
1 2
/*
** string.c - String class
roco's avatar
roco committed
3
**
mimaki's avatar
mimaki committed
4 5 6
** See Copyright Notice in mruby.h
*/

Yasuhiro Matsumoto's avatar
Yasuhiro Matsumoto committed
7 8 9 10
#ifdef _MSC_VER
# define _CRT_NONSTDC_NO_DEPRECATE
#endif

11
#include <float.h>
12
#include <limits.h>
13
#include <stddef.h>
14
#include <stdlib.h>
mimaki's avatar
mimaki committed
15
#include <string.h>
16 17 18 19 20 21
#include <mruby.h>
#include <mruby/array.h>
#include <mruby/class.h>
#include <mruby/range.h>
#include <mruby/string.h>
#include <mruby/re.h>
mimaki's avatar
mimaki committed
22

23
typedef struct mrb_shared_string {
ksss's avatar
ksss committed
24
  mrb_bool nofree : 1;
25 26 27 28 29
  int refcnt;
  char *ptr;
  mrb_int len;
} mrb_shared_string;

30
const char mrb_digitmap[] = "0123456789abcdefghijklmnopqrstuvwxyz";
mimaki's avatar
mimaki committed
31

Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
32
#define mrb_obj_alloc_string(mrb) ((struct RString*)mrb_obj_alloc((mrb), MRB_TT_STRING, (mrb)->string_class))
33

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
static struct RString*
str_new_static(mrb_state *mrb, const char *p, size_t len)
{
  struct RString *s;

  if (len >= MRB_INT_MAX) {
    mrb_raise(mrb, E_ARGUMENT_ERROR, "string size too big");
  }
  s = mrb_obj_alloc_string(mrb);
  s->as.heap.len = len;
  s->as.heap.aux.capa = 0;             /* nofree */
  s->as.heap.ptr = (char *)p;
  s->flags = MRB_STR_NOFREE;

  return s;
}

51
static struct RString*
52
str_new(mrb_state *mrb, const char *p, size_t len)
mimaki's avatar
mimaki committed
53
{
54
  struct RString *s;
mimaki's avatar
mimaki committed
55

56
  if (p && mrb_ro_data_p(p)) {
57 58
    return str_new_static(mrb, p, len);
  }
59
  s = mrb_obj_alloc_string(mrb);
60
  if (len < RSTRING_EMBED_LEN_MAX) {
61
    RSTR_SET_EMBED_FLAG(s);
62
    RSTR_SET_EMBED_LEN(s, len);
63 64 65 66
    if (p) {
      memcpy(s->as.ary, p, len);
    }
  } else {
67 68 69
    if (len >= MRB_INT_MAX) {
      mrb_raise(mrb, E_ARGUMENT_ERROR, "string size too big");
    }
70 71
    s->as.heap.len = len;
    s->as.heap.aux.capa = len;
72
    s->as.heap.ptr = (char *)mrb_malloc(mrb, len+1);
73 74 75
    if (p) {
      memcpy(s->as.heap.ptr, p, len);
    }
mimaki's avatar
mimaki committed
76
  }
77
  RSTR_PTR(s)[len] = '\0';
78
  return s;
mimaki's avatar
mimaki committed
79 80
}

81
static inline void
82
str_with_class(mrb_state *mrb, struct RString *s, mrb_value obj)
mimaki's avatar
mimaki committed
83
{
84
  s->c = mrb_str_ptr(obj)->c;
mimaki's avatar
mimaki committed
85 86 87
}

static mrb_value
88
mrb_str_new_empty(mrb_state *mrb, mrb_value str)
mimaki's avatar
mimaki committed
89
{
90 91 92 93
  struct RString *s = str_new(mrb, 0, 0);

  str_with_class(mrb, s, str);
  return mrb_obj_value(s);
mimaki's avatar
mimaki committed
94 95
}

96 97 98 99
#ifndef MRB_STR_BUF_MIN_SIZE
# define MRB_STR_BUF_MIN_SIZE 128
#endif

100
MRB_API mrb_value
101
mrb_str_buf_new(mrb_state *mrb, size_t capa)
mimaki's avatar
mimaki committed
102 103 104
{
  struct RString *s;

105
  s = mrb_obj_alloc_string(mrb);
mimaki's avatar
mimaki committed
106

107 108 109
  if (capa >= MRB_INT_MAX) {
    mrb_raise(mrb, E_ARGUMENT_ERROR, "string capacity size too big");
  }
110 111
  if (capa < MRB_STR_BUF_MIN_SIZE) {
    capa = MRB_STR_BUF_MIN_SIZE;
mimaki's avatar
mimaki committed
112
  }
ksss's avatar
ksss committed
113 114 115
  s->as.heap.len = 0;
  s->as.heap.aux.capa = capa;
  s->as.heap.ptr = (char *)mrb_malloc(mrb, capa+1);
116
  RSTR_PTR(s)[0] = '\0';
mimaki's avatar
mimaki committed
117 118 119 120

  return mrb_obj_value(s);
}

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
static inline void
resize_capa(mrb_state *mrb, struct RString *s, mrb_int capacity)
{
  if (RSTR_EMBED_P(s)) {
    if (RSTRING_EMBED_LEN_MAX < capacity) {
      char *const tmp = (char *)mrb_malloc(mrb, capacity+1);
      const mrb_int len = RSTR_EMBED_LEN(s);
      memcpy(tmp, s->as.ary, len);
      RSTR_UNSET_EMBED_FLAG(s);
      s->as.heap.ptr = tmp;
      s->as.heap.len = len;
      s->as.heap.aux.capa = capacity;
    }
  }
  else {
    s->as.heap.ptr = (char *)mrb_realloc(mrb, RSTR_PTR(s), capacity+1);
    s->as.heap.aux.capa = capacity;
  }
}

141
static void
142
str_buf_cat(mrb_state *mrb, struct RString *s, const char *ptr, size_t len)
mimaki's avatar
mimaki committed
143
{
144 145
  size_t capa;
  size_t total;
146
  ptrdiff_t off = -1;
mimaki's avatar
mimaki committed
147

148
  if (len == 0) return;
h2so5's avatar
h2so5 committed
149
  mrb_str_modify(mrb, s);
150 151
  if (ptr >= RSTR_PTR(s) && ptr <= RSTR_PTR(s) + (size_t)RSTR_LEN(s)) {
      off = ptr - RSTR_PTR(s);
mimaki's avatar
mimaki committed
152
  }
153

154
  if (RSTR_EMBED_P(s))
155 156 157 158
    capa = RSTRING_EMBED_LEN_MAX;
  else
    capa = s->as.heap.aux.capa;

159
  if (RSTR_LEN(s) >= MRB_INT_MAX - (mrb_int)len) {
160
    mrb_raise(mrb, E_ARGUMENT_ERROR, "string size too big");
mimaki's avatar
mimaki committed
161
  }
162
  total = RSTR_LEN(s)+len;
mimaki's avatar
mimaki committed
163 164
  if (capa <= total) {
    while (total > capa) {
Jun Hiroe's avatar
Jun Hiroe committed
165 166 167 168 169
      if (capa + 1 >= MRB_INT_MAX / 2) {
        capa = (total + 4095) / 4096;
        break;
      }
      capa = (capa + 1) * 2;
mimaki's avatar
mimaki committed
170
    }
cremno's avatar
cremno committed
171
    resize_capa(mrb, s, capa);
mimaki's avatar
mimaki committed
172 173
  }
  if (off != -1) {
174
      ptr = RSTR_PTR(s) + off;
mimaki's avatar
mimaki committed
175
  }
176
  memcpy(RSTR_PTR(s) + RSTR_LEN(s), ptr, len);
177
  mrb_assert_int_fit(size_t, total, mrb_int, MRB_INT_MAX);
178 179
  RSTR_SET_LEN(s, total);
  RSTR_PTR(s)[total] = '\0';   /* sentinel */
mimaki's avatar
mimaki committed
180 181
}

182
MRB_API mrb_value
183
mrb_str_new(mrb_state *mrb, const char *p, size_t len)
mimaki's avatar
mimaki committed
184
{
185
  return mrb_obj_value(str_new(mrb, p, len));
mimaki's avatar
mimaki committed
186 187 188 189 190 191 192 193 194
}

/*
 *  call-seq: (Caution! NULL string)
 *     String.new(str="")   => new_str
 *
 *  Returns a new string object containing a copy of <i>str</i>.
 */

195
MRB_API mrb_value
mimaki's avatar
mimaki committed
196 197 198
mrb_str_new_cstr(mrb_state *mrb, const char *p)
{
  struct RString *s;
199 200 201 202 203 204 205 206
  size_t len;

  if (p) {
    len = strlen(p);
  }
  else {
    len = 0;
  }
mimaki's avatar
mimaki committed
207

208
  s = str_new(mrb, p, len);
mimaki's avatar
mimaki committed
209 210 211 212

  return mrb_obj_value(s);
}

213
MRB_API mrb_value
214
mrb_str_new_static(mrb_state *mrb, const char *p, size_t len)
215
{
216
  struct RString *s = str_new_static(mrb, p, len);
217 218 219
  return mrb_obj_value(s);
}

220 221 222 223 224 225 226 227 228 229 230 231
static void
str_decref(mrb_state *mrb, mrb_shared_string *shared)
{
  shared->refcnt--;
  if (shared->refcnt == 0) {
    if (!shared->nofree) {
      mrb_free(mrb, shared->ptr);
    }
    mrb_free(mrb, shared);
  }
}

232 233 234
void
mrb_gc_free_str(mrb_state *mrb, struct RString *str)
{
235
  if (RSTR_EMBED_P(str))
ksss's avatar
ksss committed
236
    /* no code */;
237
  else if (RSTR_SHARED_P(str))
ksss's avatar
ksss committed
238
    str_decref(mrb, str->as.heap.aux.shared);
239
  else if (!RSTR_NOFREE_P(str))
ksss's avatar
ksss committed
240
    mrb_free(mrb, str->as.heap.ptr);
241 242
}

243 244
#ifdef MRB_UTF8_STRING
static const char utf8len_codepage[256] =
Akira Yumiyama's avatar
Akira Yumiyama committed
245
{
246 247 248 249 250 251 252 253 254
  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
  2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
  3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,1,1,1,1,1,1,1,1,1,1,1,
};
Akira Yumiyama's avatar
Akira Yumiyama committed
255

256
static mrb_int
257
utf8len(const char* p, const char* e)
258 259 260 261
{
  mrb_int len;
  mrb_int i;

262 263
  len = utf8len_codepage[(unsigned char)*p];
  if (p + len > e) return 1;
264 265 266 267 268 269 270 271 272 273
  for (i = 1; i < len; ++i)
    if ((p[i] & 0xc0) != 0x80)
      return 1;
  return len;
}

static mrb_int
utf8_strlen(mrb_value str, mrb_int len)
{
  mrb_int total = 0;
274 275
  char* p = RSTRING_PTR(str);
  char* e = p;
276 277 278
  if (RSTRING(str)->flags & MRB_STR_NO_UTF) {
    return RSTRING_LEN(str);
  }
279 280
  e += len < 0 ? RSTRING_LEN(str) : len;
  while (p<e) {
281
    p += utf8len(p, e);
282
    total++;
283
  }
284 285 286
  if (RSTRING_LEN(str) == total) {
    RSTRING(str)->flags |= MRB_STR_NO_UTF;
  }
287 288
  return total;
}
289

290 291 292 293
#define RSTRING_CHAR_LEN(s) utf8_strlen(s, -1)

/* map character index to byte offset index */
static mrb_int
294
chars2bytes(mrb_value s, mrb_int off, mrb_int idx)
295 296
{
  mrb_int i, b, n;
297 298
  const char *p = RSTRING_PTR(s) + off;
  const char *e = RSTRING_END(s);
299

300 301
  for (b=i=0; p<e && i<idx; i++) {
    n = utf8len(p, e);
302 303
    b += n;
    p += n;
Akira Yumiyama's avatar
Akira Yumiyama committed
304
  }
305
  return b;
Akira Yumiyama's avatar
Akira Yumiyama committed
306 307
}

308 309 310
/* map byte offset to character index */
static mrb_int
bytes2chars(char *p, mrb_int bi)
311
{
312
  mrb_int i, b, n;
313

314
  for (b=i=0; b<bi; i++) {
315
    n = utf8len_codepage[(unsigned char)*p];
316 317 318
    b += n;
    p += n;
  }
319
  if (b != bi) return -1;
320 321 322
  return i;
}

323
#define BYTES_ALIGN_CHECK(pos) if (pos < 0) return mrb_nil_value();
324 325
#else
#define RSTRING_CHAR_LEN(s) RSTRING_LEN(s)
326
#define chars2bytes(p, off, ci) (ci)
327
#define bytes2chars(p, bi) (bi)
328
#define BYTES_ALIGN_CHECK(pos)
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
#endif

static inline mrb_int
mrb_memsearch_qs(const unsigned char *xs, mrb_int m, const unsigned char *ys, mrb_int n)
{
  const unsigned char *x = xs, *xe = xs + m;
  const unsigned char *y = ys;
  int i, qstable[256];

  /* Preprocessing */
  for (i = 0; i < 256; ++i)
    qstable[i] = m + 1;
  for (; x < xe; ++x)
    qstable[*x] = xe - x;
  /* Searching */
  for (; y + m <= ys + n; y += *(qstable + y[m])) {
    if (*xs == *y && memcmp(xs, y, m) == 0)
      return y - ys;
  }
  return -1;
}

static mrb_int
mrb_memsearch(const void *x0, mrb_int m, const void *y0, mrb_int n)
{
  const unsigned char *x = (const unsigned char *)x0, *y = (const unsigned char *)y0;

  if (m > n) return -1;
  else if (m == n) {
    return memcmp(x0, y0, m) == 0 ? 0 : -1;
  }
  else if (m < 1) {
    return 0;
  }
  else if (m == 1) {
364
    const unsigned char *ys = (const unsigned char *)memchr(y, *x, n);
ksss's avatar
ksss committed
365 366 367 368 369

    if (ys)
      return ys - y;
    else
      return -1;
370 371 372 373 374 375 376 377 378 379 380 381 382
  }
  return mrb_memsearch_qs((const unsigned char *)x0, m, (const unsigned char *)y0, n);
}

static void
str_make_shared(mrb_state *mrb, struct RString *s)
{
  if (!RSTR_SHARED_P(s)) {
    mrb_shared_string *shared = (mrb_shared_string *)mrb_malloc(mrb, sizeof(mrb_shared_string));

    shared->refcnt = 1;
    if (RSTR_EMBED_P(s)) {
      const mrb_int len = RSTR_EMBED_LEN(s);
383 384 385
      char *const tmp = (char *)mrb_malloc(mrb, len+1);
      memcpy(tmp, s->as.ary, len);
      tmp[len] = '\0';
386
      RSTR_UNSET_EMBED_FLAG(s);
387 388 389
      s->as.heap.ptr = tmp;
      s->as.heap.len = len;
      shared->nofree = FALSE;
ksss's avatar
ksss committed
390
      shared->ptr = s->as.heap.ptr;
391
    }
Jun Hiroe's avatar
Jun Hiroe committed
392
    else if (RSTR_NOFREE_P(s)) {
393
      shared->nofree = TRUE;
ksss's avatar
ksss committed
394
      shared->ptr = s->as.heap.ptr;
Jun Hiroe's avatar
Jun Hiroe committed
395
      RSTR_UNSET_NOFREE_FLAG(s);
396 397
    }
    else {
398
      shared->nofree = FALSE;
ksss's avatar
ksss committed
399
      if (s->as.heap.aux.capa > s->as.heap.len) {
ksss's avatar
ksss committed
400
        s->as.heap.ptr = shared->ptr = (char *)mrb_realloc(mrb, s->as.heap.ptr, s->as.heap.len+1);
401 402
      }
      else {
ksss's avatar
ksss committed
403
        shared->ptr = s->as.heap.ptr;
404
      }
405
    }
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
    shared->len = s->as.heap.len;
    s->as.heap.aux.shared = shared;
    RSTR_SET_SHARED_FLAG(s);
  }
}

static mrb_value
byte_subseq(mrb_state *mrb, mrb_value str, mrb_int beg, mrb_int len)
{
  struct RString *orig, *s;
  mrb_shared_string *shared;

  orig = mrb_str_ptr(str);
  if (RSTR_EMBED_P(orig)) {
    s = str_new(mrb, orig->as.ary+beg, len);
  }
  else {
    str_make_shared(mrb, orig);
    shared = orig->as.heap.aux.shared;
    s = mrb_obj_alloc_string(mrb);
    s->as.heap.ptr = orig->as.heap.ptr + beg;
    s->as.heap.len = len;
    s->as.heap.aux.shared = shared;
    RSTR_SET_SHARED_FLAG(s);
    shared->refcnt++;
  }

  return mrb_obj_value(s);
}
#ifdef MRB_UTF8_STRING
static inline mrb_value
str_subseq(mrb_state *mrb, mrb_value str, mrb_int beg, mrb_int len)
{
439 440
  beg = chars2bytes(str, 0, beg);
  len = chars2bytes(str, beg, len);
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578

  return byte_subseq(mrb, str, beg, len);
}
#else
#define str_subseq(mrb, str, beg, len) byte_subseq(mrb, str, beg, len)
#endif

static mrb_value
str_substr(mrb_state *mrb, mrb_value str, mrb_int beg, mrb_int len)
{
  mrb_int clen = RSTRING_CHAR_LEN(str);

  if (len < 0) return mrb_nil_value();
  if (clen == 0) {
    len = 0;
  }
  else if (beg < 0) {
    beg = clen + beg;
  }
  if (beg > clen) return mrb_nil_value();
  if (beg < 0) {
    beg += clen;
    if (beg < 0) return mrb_nil_value();
  }
  if (beg + len > clen)
    len = clen - beg;
  if (len <= 0) {
    len = 0;
  }
  return str_subseq(mrb, str, beg, len);
}

static mrb_int
str_index(mrb_state *mrb, mrb_value str, mrb_value sub, mrb_int offset)
{
  mrb_int pos;
  char *s, *sptr;
  mrb_int len, slen;

  len = RSTRING_LEN(str);
  slen = RSTRING_LEN(sub);
  if (offset < 0) {
    offset += len;
    if (offset < 0) return -1;
  }
  if (len - offset < slen) return -1;
  s = RSTRING_PTR(str);
  if (offset) {
    s += offset;
  }
  if (slen == 0) return offset;
  /* need proceed one character at a time */
  sptr = RSTRING_PTR(sub);
  slen = RSTRING_LEN(sub);
  len = RSTRING_LEN(str) - offset;
  pos = mrb_memsearch(sptr, slen, s, len);
  if (pos < 0) return pos;
  return pos + offset;
}

static void
check_frozen(mrb_state *mrb, struct RString *s)
{
  if (RSTR_FROZEN_P(s)) {
    mrb_raise(mrb, E_RUNTIME_ERROR, "can't modify frozen string");
  }
}

static mrb_value
str_replace(mrb_state *mrb, struct RString *s1, struct RString *s2)
{
  long len;

  check_frozen(mrb, s1);
  len = RSTR_LEN(s2);
  if (RSTR_SHARED_P(s1)) {
    str_decref(mrb, s1->as.heap.aux.shared);
  }
  else if (!RSTR_EMBED_P(s1) && !RSTR_NOFREE_P(s1)) {
    mrb_free(mrb, s1->as.heap.ptr);
  }

  RSTR_UNSET_NOFREE_FLAG(s1);

  if (RSTR_SHARED_P(s2)) {
L_SHARE:
    RSTR_UNSET_EMBED_FLAG(s1);
    s1->as.heap.ptr = s2->as.heap.ptr;
    s1->as.heap.len = len;
    s1->as.heap.aux.shared = s2->as.heap.aux.shared;
    RSTR_SET_SHARED_FLAG(s1);
    s1->as.heap.aux.shared->refcnt++;
  }
  else {
    if (len <= RSTRING_EMBED_LEN_MAX) {
      RSTR_UNSET_SHARED_FLAG(s1);
      RSTR_SET_EMBED_FLAG(s1);
      memcpy(s1->as.ary, RSTR_PTR(s2), len);
      RSTR_SET_EMBED_LEN(s1, len);
    }
    else {
      str_make_shared(mrb, s2);
      goto L_SHARE;
    }
  }

  return mrb_obj_value(s1);
}

static mrb_int
str_rindex(mrb_state *mrb, mrb_value str, mrb_value sub, mrb_int pos)
{
  char *s, *sbeg, *t;
  struct RString *ps = mrb_str_ptr(str);
  mrb_int len = RSTRING_LEN(sub);

  /* substring longer than string */
  if (RSTR_LEN(ps) < len) return -1;
  if (RSTR_LEN(ps) - pos < len) {
    pos = RSTR_LEN(ps) - len;
  }
  sbeg = RSTR_PTR(ps);
  s = RSTR_PTR(ps) + pos;
  t = RSTRING_PTR(sub);
  if (len) {
    while (sbeg <= s) {
      if (memcmp(s, t, len) == 0) {
        return s - RSTR_PTR(ps);
      }
      s--;
    }
    return -1;
  }
  else {
    return pos;
  }
}

579
MRB_API mrb_int
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
mrb_str_strlen(mrb_state *mrb, struct RString *s)
{
  mrb_int i, max = RSTR_LEN(s);
  char *p = RSTR_PTR(s);

  if (!p) return 0;
  for (i=0; i<max; i++) {
    if (p[i] == '\0') {
      mrb_raise(mrb, E_ARGUMENT_ERROR, "string contains null byte");
    }
  }
  return max;
}

#ifdef _WIN32
#include <windows.h>

char*
mrb_utf8_from_locale(const char *str, size_t len)
{
  wchar_t* wcsp;
  char* mbsp;
  size_t mbssize, wcssize;

  if (len == 0)
    return strdup("");
  if (len == -1)
    len = strlen(str);
  wcssize = MultiByteToWideChar(GetACP(), 0, str, len,  NULL, 0);
  wcsp = (wchar_t*) malloc((wcssize + 1) * sizeof(wchar_t));
  if (!wcsp)
    return NULL;
  wcssize = MultiByteToWideChar(GetACP(), 0, str, len, wcsp, wcssize + 1);
  wcsp[wcssize] = 0;

  mbssize = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR) wcsp, -1, NULL, 0, NULL, NULL);
  mbsp = (char*) malloc((mbssize + 1));
  if (!mbsp) {
    free(wcsp);
    return NULL;
  }
  mbssize = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR) wcsp, -1, mbsp, mbssize, NULL, NULL);
  mbsp[mbssize] = 0;
  free(wcsp);
  return mbsp;
}

char*
mrb_locale_from_utf8(const char *utf8, size_t len)
{
  wchar_t* wcsp;
  char* mbsp;
  size_t mbssize, wcssize;

  if (len == 0)
    return strdup("");
  if (len == -1)
    len = strlen(utf8);
  wcssize = MultiByteToWideChar(CP_UTF8, 0, utf8, len,  NULL, 0);
  wcsp = (wchar_t*) malloc((wcssize + 1) * sizeof(wchar_t));
  if (!wcsp)
    return NULL;
  wcssize = MultiByteToWideChar(CP_UTF8, 0, utf8, len, wcsp, wcssize + 1);
  wcsp[wcssize] = 0;
  mbssize = WideCharToMultiByte(GetACP(), 0, (LPCWSTR) wcsp, -1, NULL, 0, NULL, NULL);
  mbsp = (char*) malloc((mbssize + 1));
  if (!mbsp) {
    free(wcsp);
    return NULL;
  }
  mbssize = WideCharToMultiByte(GetACP(), 0, (LPCWSTR) wcsp, -1, mbsp, mbssize, NULL, NULL);
  mbsp[mbssize] = 0;
  free(wcsp);
  return mbsp;
}
#endif

MRB_API void
mrb_str_modify(mrb_state *mrb, struct RString *s)
{
  check_frozen(mrb, s);
661
  s->flags &= ~MRB_STR_NO_UTF;
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
  if (RSTR_SHARED_P(s)) {
    mrb_shared_string *shared = s->as.heap.aux.shared;

    if (shared->refcnt == 1 && s->as.heap.ptr == shared->ptr) {
      s->as.heap.ptr = shared->ptr;
      s->as.heap.aux.capa = shared->len;
      RSTR_PTR(s)[s->as.heap.len] = '\0';
      mrb_free(mrb, shared);
    }
    else {
      char *ptr, *p;
      mrb_int len;

      p = RSTR_PTR(s);
      len = s->as.heap.len;
      ptr = (char *)mrb_malloc(mrb, (size_t)len + 1);
      if (p) {
        memcpy(ptr, p, len);
      }
      ptr[len] = '\0';
      s->as.heap.ptr = ptr;
      s->as.heap.aux.capa = len;
      str_decref(mrb, shared);
    }
    RSTR_UNSET_SHARED_FLAG(s);
    return;
  }
  if (RSTR_NOFREE_P(s)) {
    char *p = s->as.heap.ptr;

    s->as.heap.ptr = (char *)mrb_malloc(mrb, (size_t)s->as.heap.len+1);
    if (p) {
      memcpy(RSTR_PTR(s), p, s->as.heap.len);
    }
    RSTR_PTR(s)[s->as.heap.len] = '\0';
    s->as.heap.aux.capa = s->as.heap.len;
    RSTR_UNSET_NOFREE_FLAG(s);
    return;
  }
}

static mrb_value
mrb_str_freeze(mrb_state *mrb, mrb_value str)
{
  struct RString *s = mrb_str_ptr(str);

  RSTR_SET_FROZEN_FLAG(s);
  return str;
}

MRB_API mrb_value
mrb_str_resize(mrb_state *mrb, mrb_value str, mrb_int len)
{
  mrb_int slen;
  struct RString *s = mrb_str_ptr(str);

  mrb_str_modify(mrb, s);
  slen = RSTR_LEN(s);
  if (len != slen) {
    if (slen < len || slen - len > 256) {
      resize_capa(mrb, s, len);
    }
    RSTR_SET_LEN(s, len);
    RSTR_PTR(s)[len] = '\0';   /* sentinel */
  }
  return str;
}

MRB_API char*
mrb_str_to_cstr(mrb_state *mrb, mrb_value str0)
{
  struct RString *s;

  if (!mrb_string_p(str0)) {
    mrb_raise(mrb, E_TYPE_ERROR, "expected String");
  }

  s = str_new(mrb, RSTRING_PTR(str0), RSTRING_LEN(str0));
  if ((strlen(RSTR_PTR(s)) ^ RSTR_LEN(s)) != 0) {
    mrb_raise(mrb, E_ARGUMENT_ERROR, "string contains null byte");
742
  }
743
  return RSTR_PTR(s);
744 745
}

mimaki's avatar
mimaki committed
746 747 748 749 750 751
/*
 *  call-seq: (Caution! String("abcd") change)
 *     String("abcdefg") = String("abcd") + String("efg")
 *
 *  Returns a new string object containing a copy of <i>str</i>.
 */
752
MRB_API void
mimaki's avatar
mimaki committed
753 754 755
mrb_str_concat(mrb_state *mrb, mrb_value self, mrb_value other)
{
  struct RString *s1 = mrb_str_ptr(self), *s2;
756
  mrb_int len;
mimaki's avatar
mimaki committed
757

h2so5's avatar
h2so5 committed
758
  mrb_str_modify(mrb, s1);
759
  if (!mrb_string_p(other)) {
mimaki's avatar
mimaki committed
760 761 762
    other = mrb_str_to_str(mrb, other);
  }
  s2 = mrb_str_ptr(other);
763
  len = RSTR_LEN(s1) + RSTR_LEN(s2);
mimaki's avatar
mimaki committed
764

765
  if (RSTRING_CAPA(self) < len) {
cremno's avatar
cremno committed
766
    resize_capa(mrb, s1, len);
mimaki's avatar
mimaki committed
767
  }
768 769 770
  memcpy(RSTR_PTR(s1)+RSTR_LEN(s1), RSTR_PTR(s2), RSTR_LEN(s2));
  RSTR_SET_LEN(s1, len);
  RSTR_PTR(s1)[len] = '\0';
mimaki's avatar
mimaki committed
771 772 773 774 775 776 777 778
}

/*
 *  call-seq: (Caution! String("abcd") remain)
 *     String("abcdefg") = String("abcd") + String("efg")
 *
 *  Returns a new string object containing a copy of <i>str</i>.
 */
779
MRB_API mrb_value
mimaki's avatar
mimaki committed
780 781 782 783 784 785
mrb_str_plus(mrb_state *mrb, mrb_value a, mrb_value b)
{
  struct RString *s = mrb_str_ptr(a);
  struct RString *s2 = mrb_str_ptr(b);
  struct RString *t;

786 787 788
  t = str_new(mrb, 0, RSTR_LEN(s) + RSTR_LEN(s2));
  memcpy(RSTR_PTR(t), RSTR_PTR(s), RSTR_LEN(s));
  memcpy(RSTR_PTR(t) + RSTR_LEN(s), RSTR_PTR(s2), RSTR_LEN(s2));
mimaki's avatar
mimaki committed
789

790
  return mrb_obj_value(t);
mimaki's avatar
mimaki committed
791 792 793 794 795 796 797 798 799 800 801 802 803
}

/* 15.2.10.5.2  */

/*
 *  call-seq: (Caution! String("abcd") remain) for stack_argument
 *     String("abcdefg") = String("abcd") + String("efg")
 *
 *  Returns a new string object containing a copy of <i>str</i>.
 */
static mrb_value
mrb_str_plus_m(mrb_state *mrb, mrb_value self)
{
804 805 806 807
  mrb_value str;

  mrb_get_args(mrb, "S", &str);
  return mrb_str_plus(mrb, self, str);
mimaki's avatar
mimaki committed
808 809 810 811 812 813
}

/* 15.2.10.5.26 */
/* 15.2.10.5.33 */
/*
 *  call-seq:
814
 *     "abcd".size   => int
mimaki's avatar
mimaki committed
815
 *
816
 *  Returns the length of string.
mimaki's avatar
mimaki committed
817
 */
818
static mrb_value
mimaki's avatar
mimaki committed
819 820
mrb_str_size(mrb_state *mrb, mrb_value self)
{
821 822 823 824 825 826 827 828 829
  mrb_int len = RSTRING_CHAR_LEN(self);
  return mrb_fixnum_value(len);
}

static mrb_value
mrb_str_bytesize(mrb_state *mrb, mrb_value self)
{
  mrb_int len = RSTRING_LEN(self);
  return mrb_fixnum_value(len);
mimaki's avatar
mimaki committed
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
}

/* 15.2.10.5.1  */
/*
 *  call-seq:
 *     str * integer   => new_str
 *
 *  Copy---Returns a new <code>String</code> containing <i>integer</i> copies of
 *  the receiver.
 *
 *     "Ho! " * 3   #=> "Ho! Ho! Ho! "
 */
static mrb_value
mrb_str_times(mrb_state *mrb, mrb_value self)
{
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
845
  mrb_int n,len,times;
846 847
  struct RString *str2;
  char *p;
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
848 849 850 851 852

  mrb_get_args(mrb, "i", &times);
  if (times < 0) {
    mrb_raise(mrb, E_ARGUMENT_ERROR, "negative argument");
  }
853
  if (times && MRB_INT_MAX / times < RSTRING_LEN(self)) {
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
854 855 856 857
    mrb_raise(mrb, E_ARGUMENT_ERROR, "argument too big");
  }

  len = RSTRING_LEN(self)*times;
858 859
  str2 = str_new(mrb, 0, len);
  str_with_class(mrb, str2, self);
860
  p = RSTR_PTR(str2);
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
861 862
  if (len > 0) {
    n = RSTRING_LEN(self);
863
    memcpy(p, RSTRING_PTR(self), n);
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
864
    while (n <= len/2) {
865
      memcpy(p + n, p, n);
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
866 867
      n *= 2;
    }
868
    memcpy(p + n, p, len-n);
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
869
  }
870
  p[RSTR_LEN(str2)] = '\0';
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
871

872
  return mrb_obj_value(str2);
mimaki's avatar
mimaki committed
873 874 875 876 877 878 879 880 881 882 883 884 885
}
/* -------------------------------------------------------------- */

#define lesser(a,b) (((a)>(b))?(b):(a))

/* ---------------------------*/
/*
 *  call-seq:
 *     mrb_value str1 <=> mrb_value str2   => int
 *                     >  1
 *                     =  0
 *                     <  -1
 */
886
MRB_API int
mimaki's avatar
mimaki committed
887 888 889 890 891 892 893
mrb_str_cmp(mrb_state *mrb, mrb_value str1, mrb_value str2)
{
  mrb_int len;
  mrb_int retval;
  struct RString *s1 = mrb_str_ptr(str1);
  struct RString *s2 = mrb_str_ptr(str2);

894 895
  len = lesser(RSTR_LEN(s1), RSTR_LEN(s2));
  retval = memcmp(RSTR_PTR(s1), RSTR_PTR(s2), len);
mimaki's avatar
mimaki committed
896
  if (retval == 0) {
897 898
    if (RSTR_LEN(s1) == RSTR_LEN(s2)) return 0;
    if (RSTR_LEN(s1) > RSTR_LEN(s2))  return 1;
mimaki's avatar
mimaki committed
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
    return -1;
  }
  if (retval > 0) return 1;
  return -1;
}

/* 15.2.10.5.3  */

/*
 *  call-seq:
 *     str <=> other_str   => -1, 0, +1
 *
 *  Comparison---Returns -1 if <i>other_str</i> is less than, 0 if
 *  <i>other_str</i> is equal to, and +1 if <i>other_str</i> is greater than
 *  <i>str</i>. If the strings are of different lengths, and the strings are
 *  equal when compared up to the shortest length, then the longer string is
 *  considered greater than the shorter one. If the variable <code>$=</code> is
 *  <code>false</code>, the comparison is based on comparing the binary values
 *  of each character in the string. In older versions of Ruby, setting
 *  <code>$=</code> allowed case-insensitive comparisons; this is now deprecated
 *  in favor of using <code>String#casecmp</code>.
 *
 *  <code><=></code> is the basis for the methods <code><</code>,
 *  <code><=</code>, <code>></code>, <code>>=</code>, and <code>between?</code>,
 *  included from module <code>Comparable</code>.  The method
 *  <code>String#==</code> does not use <code>Comparable#==</code>.
 *
 *     "abcdef" <=> "abcde"     #=> 1
 *     "abcdef" <=> "abcdef"    #=> 0
 *     "abcdef" <=> "abcdefg"   #=> -1
 *     "abcdef" <=> "ABCDEF"    #=> 1
 */
static mrb_value
mrb_str_cmp_m(mrb_state *mrb, mrb_value str1)
{
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
934 935 936 937
  mrb_value str2;
  mrb_int result;

  mrb_get_args(mrb, "o", &str2);
938
  if (!mrb_string_p(str2)) {
939
    if (!mrb_respond_to(mrb, str2, mrb_intern_lit(mrb, "to_s"))) {
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
940 941
      return mrb_nil_value();
    }
942
    else if (!mrb_respond_to(mrb, str2, mrb_intern_lit(mrb, "<=>"))) {
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
      return mrb_nil_value();
    }
    else {
      mrb_value tmp = mrb_funcall(mrb, str2, "<=>", 1, str1);

      if (mrb_nil_p(tmp)) return mrb_nil_value();
      if (!mrb_fixnum(tmp)) {
        return mrb_funcall(mrb, mrb_fixnum_value(0), "-", 1, tmp);
      }
      result = -mrb_fixnum(tmp);
    }
  }
  else {
    result = mrb_str_cmp(mrb, str1, str2);
  }
  return mrb_fixnum_value(result);
mimaki's avatar
mimaki committed
959 960
}

961
static mrb_bool
mimaki's avatar
mimaki committed
962 963
str_eql(mrb_state *mrb, const mrb_value str1, const mrb_value str2)
{
964
  const mrb_int len = RSTRING_LEN(str1);
965

mimaki's avatar
mimaki committed
966
  if (len != RSTRING_LEN(str2)) return FALSE;
967
  if (memcmp(RSTRING_PTR(str1), RSTRING_PTR(str2), (size_t)len) == 0)
mimaki's avatar
mimaki committed
968 969 970 971
    return TRUE;
  return FALSE;
}

972
MRB_API mrb_bool
mimaki's avatar
mimaki committed
973 974
mrb_str_equal(mrb_state *mrb, mrb_value str1, mrb_value str2)
{
975
  if (mrb_immediate_p(str2)) return FALSE;
976
  if (!mrb_string_p(str2)) {
mimaki's avatar
mimaki committed
977
    if (mrb_nil_p(str2)) return FALSE;
978
    if (!mrb_respond_to(mrb, str2, mrb_intern_lit(mrb, "to_str"))) {
mimaki's avatar
mimaki committed
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
      return FALSE;
    }
    str2 = mrb_funcall(mrb, str2, "to_str", 0);
    return mrb_equal(mrb, str2, str1);
  }
  return str_eql(mrb, str1, str2);
}

/* 15.2.10.5.4  */
/*
 *  call-seq:
 *     str == obj   => true or false
 *
 *  Equality---
 *  If <i>obj</i> is not a <code>String</code>, returns <code>false</code>.
 *  Otherwise, returns <code>false</code> or <code>true</code>
 *
 *   caution:if <i>str</i> <code><=></code> <i>obj</i> returns zero.
 */
static mrb_value
mrb_str_equal_m(mrb_state *mrb, mrb_value str1)
{
  mrb_value str2;

  mrb_get_args(mrb, "o", &str2);
1004

1005
  return mrb_bool_value(mrb_str_equal(mrb, str1, str2));
mimaki's avatar
mimaki committed
1006 1007
}
/* ---------------------------------- */
1008
MRB_API mrb_value
mimaki's avatar
mimaki committed
1009 1010 1011 1012
mrb_str_to_str(mrb_state *mrb, mrb_value str)
{
  mrb_value s;

1013
  if (!mrb_string_p(str)) {
mimaki's avatar
mimaki committed
1014 1015 1016 1017 1018 1019 1020 1021 1022
    s = mrb_check_convert_type(mrb, str, MRB_TT_STRING, "String", "to_str");
    if (mrb_nil_p(s)) {
      s = mrb_convert_type(mrb, str, MRB_TT_STRING, "String", "to_s");
    }
    return s;
  }
  return str;
}

1023
MRB_API const char*
mimaki's avatar
mimaki committed
1024 1025
mrb_string_value_ptr(mrb_state *mrb, mrb_value ptr)
{
Jun Hiroe's avatar
Jun Hiroe committed
1026 1027
  mrb_value str = mrb_str_to_str(mrb, ptr);
  return RSTRING_PTR(str);
mimaki's avatar
mimaki committed
1028 1029
}

1030 1031 1032 1033 1034 1035 1036
MRB_API mrb_int
mrb_string_value_len(mrb_state *mrb, mrb_value ptr)
{
  mrb_value str = mrb_str_to_str(mrb, ptr);
  return RSTRING_LEN(str);
}

1037
void
1038
mrb_noregexp(mrb_state *mrb, mrb_value self)
mimaki's avatar
mimaki committed
1039
{
1040
  mrb_raise(mrb, E_NOTIMP_ERROR, "Regexp class not implemented");
mimaki's avatar
mimaki committed
1041 1042
}

1043
void
1044
mrb_regexp_check(mrb_state *mrb, mrb_value obj)
1045
{
1046
  if (mrb_regexp_p(mrb, obj)) {
1047
    mrb_noregexp(mrb, obj);
1048 1049 1050
  }
}

1051
MRB_API mrb_value
mimaki's avatar
mimaki committed
1052 1053 1054
mrb_str_dup(mrb_state *mrb, mrb_value str)
{
  struct RString *s = mrb_str_ptr(str);
1055
  struct RString *dup = str_new(mrb, 0, 0);
mimaki's avatar
mimaki committed
1056

1057 1058
  str_with_class(mrb, dup, str);
  return str_replace(mrb, dup, s);
mimaki's avatar
mimaki committed
1059 1060 1061 1062 1063
}

static mrb_value
mrb_str_aref(mrb_state *mrb, mrb_value str, mrb_value indx)
{
1064
  mrb_int idx;
mimaki's avatar
mimaki committed
1065

1066
  mrb_regexp_check(mrb, indx);
mimaki's avatar
mimaki committed
1067 1068 1069 1070 1071
  switch (mrb_type(indx)) {
    case MRB_TT_FIXNUM:
      idx = mrb_fixnum(indx);

num_index:
1072
      str = str_substr(mrb, str, idx, 1);
mimaki's avatar
mimaki committed
1073 1074 1075 1076
      if (!mrb_nil_p(str) && RSTRING_LEN(str) == 0) return mrb_nil_value();
      return str;

    case MRB_TT_STRING:
1077
      if (str_index(mrb, str, indx, 0) != -1)
mimaki's avatar
mimaki committed
1078 1079 1080
        return mrb_str_dup(mrb, indx);
      return mrb_nil_value();

1081
    case MRB_TT_RANGE:
mimaki's avatar
mimaki committed
1082 1083 1084 1085
      /* check if indx is Range */
      {
        mrb_int beg, len;

1086
        len = RSTRING_CHAR_LEN(str);
1087
        if (mrb_range_beg_len(mrb, indx, &beg, &len, len)) {
1088
          return str_subseq(mrb, str, beg, len);
1089 1090 1091
        }
        else {
          return mrb_nil_value();
mimaki's avatar
mimaki committed
1092 1093
        }
      }
1094
    case MRB_TT_FLOAT:
1095
    default:
1096 1097 1098 1099
      indx = mrb_Integer(mrb, indx);
      if (mrb_nil_p(indx)) {
        mrb_raise(mrb, E_TYPE_ERROR, "can't convert to Fixnum");
      }
mimaki's avatar
mimaki committed
1100 1101
      idx = mrb_fixnum(indx);
      goto num_index;
Jun Hiroe's avatar
Jun Hiroe committed
1102 1103
  }
  return mrb_nil_value();    /* not reached */
mimaki's avatar
mimaki committed
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
}

/* 15.2.10.5.6  */
/* 15.2.10.5.34 */
/*
 *  call-seq:
 *     str[fixnum]                 => fixnum or nil
 *     str[fixnum, fixnum]         => new_str or nil
 *     str[range]                  => new_str or nil
 *     str[regexp]                 => new_str or nil
 *     str[regexp, fixnum]         => new_str or nil
 *     str[other_str]              => new_str or nil
 *     str.slice(fixnum)           => fixnum or nil
 *     str.slice(fixnum, fixnum)   => new_str or nil
1118
 *     str.slice(range)            => new_str or nil
mimaki's avatar
mimaki committed
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
 *     str.slice(other_str)        => new_str or nil
 *
 *  Element Reference---If passed a single <code>Fixnum</code>, returns the code
 *  of the character at that position. If passed two <code>Fixnum</code>
 *  objects, returns a substring starting at the offset given by the first, and
 *  a length given by the second. If given a range, a substring containing
 *  characters at offsets given by the range is returned. In all three cases, if
 *  an offset is negative, it is counted from the end of <i>str</i>. Returns
 *  <code>nil</code> if the initial offset falls outside the string, the length
 *  is negative, or the beginning of the range is greater than the end.
 *
1130
 *  If a <code>String</code> is given, that string is returned if it occurs in
mimaki's avatar
mimaki committed
1131 1132 1133 1134 1135
 *  <i>str</i>. In both cases, <code>nil</code> is returned if there is no
 *  match.
 *
 *     a = "hello there"
 *     a[1]                   #=> 101(1.8.7) "e"(1.9.2)
1136
 *     a[1.1]                 #=>            "e"(1.9.2)
mimaki's avatar
mimaki committed
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
 *     a[1,3]                 #=> "ell"
 *     a[1..3]                #=> "ell"
 *     a[-3,2]                #=> "er"
 *     a[-4..-2]              #=> "her"
 *     a[12..-1]              #=> nil
 *     a[-2..-4]              #=> ""
 *     a["lo"]                #=> "lo"
 *     a["bye"]               #=> nil
 */
static mrb_value
mrb_str_aref_m(mrb_state *mrb, mrb_value str)
{
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
1149
  mrb_value a1, a2;
mimaki's avatar
mimaki committed
1150 1151
  int argc;

Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
1152
  argc = mrb_get_args(mrb, "o|o", &a1, &a2);
mimaki's avatar
mimaki committed
1153
  if (argc == 2) {
1154
    mrb_regexp_check(mrb, a1);
1155
    return str_substr(mrb, str, mrb_fixnum(a1), mrb_fixnum(a2));
mimaki's avatar
mimaki committed
1156 1157
  }
  if (argc != 1) {
1158
    mrb_raisef(mrb, E_ARGUMENT_ERROR, "wrong number of arguments (%S for 1)", mrb_fixnum_value(argc));
mimaki's avatar
mimaki committed
1159
  }
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
1160
  return mrb_str_aref(mrb, str, a1);
mimaki's avatar
mimaki committed
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
}

/* 15.2.10.5.8  */
/*
 *  call-seq:
 *     str.capitalize!   => str or nil
 *
 *  Modifies <i>str</i> by converting the first character to uppercase and the
 *  remainder to lowercase. Returns <code>nil</code> if no changes are made.
 *
 *     a = "hello"
 *     a.capitalize!   #=> "Hello"
 *     a               #=> "Hello"
 *     a.capitalize!   #=> nil
 */
static mrb_value
mrb_str_capitalize_bang(mrb_state *mrb, mrb_value str)
{
1179
  char *p, *pend;
1180
  mrb_bool modify = FALSE;
1181
  struct RString *s = mrb_str_ptr(str);
1182

h2so5's avatar
h2so5 committed
1183
  mrb_str_modify(mrb, s);
1184 1185
  if (RSTR_LEN(s) == 0 || !RSTR_PTR(s)) return mrb_nil_value();
  p = RSTR_PTR(s); pend = RSTR_PTR(s) + RSTR_LEN(s);
1186
  if (ISLOWER(*p)) {
1187
    *p = TOUPPER(*p);
1188
    modify = TRUE;
1189
  }
1190 1191
  while (++p < pend) {
    if (ISUPPER(*p)) {
1192
      *p = TOLOWER(*p);
1193
      modify = TRUE;
1194 1195 1196
    }
  }
  if (modify) return str;
mimaki's avatar
mimaki committed
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
  return mrb_nil_value();
}

/* 15.2.10.5.7  */
/*
 *  call-seq:
 *     str.capitalize   => new_str
 *
 *  Returns a copy of <i>str</i> with the first character converted to uppercase
 *  and the remainder to lowercase.
 *
 *     "hello".capitalize    #=> "Hello"
 *     "HELLO".capitalize    #=> "Hello"
 *     "123ABC".capitalize   #=> "123abc"
 */
static mrb_value
mrb_str_capitalize(mrb_state *mrb, mrb_value self)
{
  mrb_value str;

  str = mrb_str_dup(mrb, self);
  mrb_str_capitalize_bang(mrb, str);
  return str;
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
1220 1221 1222 1223 1224
}

/* 15.2.10.5.10  */
/*
 *  call-seq:
1225
 *     str.chomp!(separator="\n")   => str or nil
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
1226 1227 1228 1229 1230 1231 1232
 *
 *  Modifies <i>str</i> in place as described for <code>String#chomp</code>,
 *  returning <i>str</i>, or <code>nil</code> if no modifications were made.
 */
static mrb_value
mrb_str_chomp_bang(mrb_state *mrb, mrb_value str)
{
1233 1234 1235
  mrb_value rs;
  mrb_int newline;
  char *p, *pp;
1236 1237
  mrb_int rslen;
  mrb_int len;
1238
  struct RString *s = mrb_str_ptr(str);
1239

h2so5's avatar
h2so5 committed
1240
  mrb_str_modify(mrb, s);
1241
  len = RSTR_LEN(s);
1242 1243 1244
  if (mrb_get_args(mrb, "|S", &rs) == 0) {
    if (len == 0) return mrb_nil_value();
  smart_chomp:
1245 1246 1247 1248 1249
    if (RSTR_PTR(s)[len-1] == '\n') {
      RSTR_SET_LEN(s, RSTR_LEN(s) - 1);
      if (RSTR_LEN(s) > 0 &&
          RSTR_PTR(s)[RSTR_LEN(s)-1] == '\r') {
        RSTR_SET_LEN(s, RSTR_LEN(s) - 1);
1250 1251
      }
    }
1252 1253
    else if (RSTR_PTR(s)[len-1] == '\r') {
      RSTR_SET_LEN(s, RSTR_LEN(s) - 1);
1254 1255 1256 1257
    }
    else {
      return mrb_nil_value();
    }
1258
    RSTR_PTR(s)[RSTR_LEN(s)] = '\0';
1259 1260 1261 1262
    return str;
  }

  if (len == 0 || mrb_nil_p(rs)) return mrb_nil_value();
1263
  p = RSTR_PTR(s);
1264 1265 1266 1267 1268 1269 1270
  rslen = RSTRING_LEN(rs);
  if (rslen == 0) {
    while (len>0 && p[len-1] == '\n') {
      len--;
      if (len>0 && p[len-1] == '\r')
        len--;
    }
1271 1272
    if (len < RSTR_LEN(s)) {
      RSTR_SET_LEN(s, len);
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
      p[len] = '\0';
      return str;
    }
    return mrb_nil_value();
  }
  if (rslen > len) return mrb_nil_value();
  newline = RSTRING_PTR(rs)[rslen-1];
  if (rslen == 1 && newline == '\n')
    newline = RSTRING_PTR(rs)[rslen-1];
  if (rslen == 1 && newline == '\n')
    goto smart_chomp;

  pp = p + len - rslen;
  if (p[len-1] == newline &&
     (rslen <= 1 ||
     memcmp(RSTRING_PTR(rs), pp, rslen) == 0)) {
1289 1290
    RSTR_SET_LEN(s, len - rslen);
    p[RSTR_LEN(s)] = '\0';
1291 1292
    return str;
  }
mimaki's avatar
mimaki committed
1293 1294 1295 1296 1297 1298
  return mrb_nil_value();
}

/* 15.2.10.5.9  */
/*
 *  call-seq:
1299
 *     str.chomp(separator="\n")   => new_str
mimaki's avatar
mimaki committed
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
 *
 *  Returns a new <code>String</code> with the given record separator removed
 *  from the end of <i>str</i> (if present). If <code>$/</code> has not been
 *  changed from the default Ruby record separator, then <code>chomp</code> also
 *  removes carriage return characters (that is it will remove <code>\n</code>,
 *  <code>\r</code>, and <code>\r\n</code>).
 *
 *     "hello".chomp            #=> "hello"
 *     "hello\n".chomp          #=> "hello"
 *     "hello\r\n".chomp        #=> "hello"
 *     "hello\n\r".chomp        #=> "hello\n"
 *     "hello\r".chomp          #=> "hello"
 *     "hello \n there".chomp   #=> "hello \n there"
 *     "hello".chomp("llo")     #=> "he"
 */
static mrb_value
mrb_str_chomp(mrb_state *mrb, mrb_value self)
{
  mrb_value str;

  str = mrb_str_dup(mrb, self);
  mrb_str_chomp_bang(mrb, str);
  return str;
}

/* 15.2.10.5.12 */
/*
 *  call-seq:
 *     str.chop!   => str or nil
 *
 *  Processes <i>str</i> as for <code>String#chop</code>, returning <i>str</i>,
 *  or <code>nil</code> if <i>str</i> is the empty string.  See also
 *  <code>String#chomp!</code>.
 */
static mrb_value
mrb_str_chop_bang(mrb_state *mrb, mrb_value str)
{
1337 1338
  struct RString *s = mrb_str_ptr(str);

h2so5's avatar
h2so5 committed
1339
  mrb_str_modify(mrb, s);
1340
  if (RSTR_LEN(s) > 0) {
cubicdaiya's avatar
cubicdaiya committed
1341
    mrb_int len;
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
#ifdef MRB_UTF8_STRING
    const char* t = RSTR_PTR(s), *p = t;
    const char* e = p + RSTR_LEN(s);
    while (p<e) {
      mrb_int clen = utf8len(p, e);
      if (p + clen>=e) break;
      p += clen;
    }
    len = p - t;
#else
1352
    len = RSTR_LEN(s) - 1;
1353
#endif
1354
    if (RSTR_PTR(s)[len] == '\n') {
mimaki's avatar
mimaki committed
1355
      if (len > 0 &&
1356
          RSTR_PTR(s)[len-1] == '\r') {
mimaki's avatar
mimaki committed
1357 1358 1359
        len--;
      }
    }
1360 1361
    RSTR_SET_LEN(s, len);
    RSTR_PTR(s)[len] = '\0';
mimaki's avatar
mimaki committed
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
    return str;
  }
  return mrb_nil_value();
}

/* 15.2.10.5.11 */
/*
 *  call-seq:
 *     str.chop   => new_str
 *
 *  Returns a new <code>String</code> with the last character removed.  If the
 *  string ends with <code>\r\n</code>, both characters are removed. Applying
 *  <code>chop</code> to an empty string returns an empty
 *  string. <code>String#chomp</code> is often a safer alternative, as it leaves
 *  the string unchanged if it doesn't end in a record separator.
 *
 *     "string\r\n".chop   #=> "string"
 *     "string\n\r".chop   #=> "string\n"
 *     "string\n".chop     #=> "string"
 *     "string".chop       #=> "strin"
 *     "x".chop            #=> ""
 */
static mrb_value
mrb_str_chop(mrb_state *mrb, mrb_value self)
{
  mrb_value str;
  str = mrb_str_dup(mrb, self);
  mrb_str_chop_bang(mrb, str);
  return str;
}

/* 15.2.10.5.14 */
/*
 *  call-seq:
 *     str.downcase!   => str or nil
 *
 *  Downcases the contents of <i>str</i>, returning <code>nil</code> if no
 *  changes were made.
 */
static mrb_value
mrb_str_downcase_bang(mrb_state *mrb, mrb_value str)
{
1404
  char *p, *pend;
Jun Hiroe's avatar
Jun Hiroe committed
1405
  mrb_bool modify = FALSE;
1406
  struct RString *s = mrb_str_ptr(str);
1407

h2so5's avatar
h2so5 committed
1408
  mrb_str_modify(mrb, s);
1409 1410
  p = RSTR_PTR(s);
  pend = RSTR_PTR(s) + RSTR_LEN(s);
1411 1412
  while (p < pend) {
    if (ISUPPER(*p)) {
1413
      *p = TOLOWER(*p);
Jun Hiroe's avatar
Jun Hiroe committed
1414
      modify = TRUE;
1415
    }
1416
    p++;
1417 1418 1419
  }

  if (modify) return str;
mimaki's avatar
mimaki committed
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
  return mrb_nil_value();
}

/* 15.2.10.5.13 */
/*
 *  call-seq:
 *     str.downcase   => new_str
 *
 *  Returns a copy of <i>str</i> with all uppercase letters replaced with their
 *  lowercase counterparts. The operation is locale insensitive---only
1430
 *  characters 'A' to 'Z' are affected.
mimaki's avatar
mimaki committed
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
 *
 *     "hEllO".downcase   #=> "hello"
 */
static mrb_value
mrb_str_downcase(mrb_state *mrb, mrb_value self)
{
  mrb_value str;

  str = mrb_str_dup(mrb, self);
  mrb_str_downcase_bang(mrb, str);
  return str;
}

/* 15.2.10.5.16 */
/*
 *  call-seq:
 *     str.empty?   => true or false
 *
 *  Returns <code>true</code> if <i>str</i> has a length of zero.
 *
 *     "hello".empty?   #=> false
 *     "".empty?        #=> true
 */
static mrb_value
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
1455
mrb_str_empty_p(mrb_state *mrb, mrb_value self)
mimaki's avatar
mimaki committed
1456 1457 1458
{
  struct RString *s = mrb_str_ptr(self);

1459
  return mrb_bool_value(RSTR_LEN(s) == 0);
mimaki's avatar
mimaki committed
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
}

/* 15.2.10.5.17 */
/*
 * call-seq:
 *   str.eql?(other)   => true or false
 *
 * Two strings are equal if the have the same length and content.
 */
static mrb_value
mrb_str_eql(mrb_state *mrb, mrb_value self)
{
  mrb_value str2;
1473
  mrb_bool eql_p;
mimaki's avatar
mimaki committed
1474 1475

  mrb_get_args(mrb, "o", &str2);
1476 1477
  eql_p = (mrb_type(str2) == MRB_TT_STRING) && str_eql(mrb, self, str2);

1478
  return mrb_bool_value(eql_p);
mimaki's avatar
mimaki committed
1479 1480
}

1481
MRB_API mrb_value
1482
mrb_str_substr(mrb_state *mrb, mrb_value str, mrb_int beg, mrb_int len)
mimaki's avatar
mimaki committed
1483
{
1484
  return str_substr(mrb, str, beg, len);
mimaki's avatar
mimaki committed
1485 1486 1487 1488 1489 1490 1491
}

mrb_int
mrb_str_hash(mrb_state *mrb, mrb_value str)
{
  /* 1-8-7 */
  struct RString *s = mrb_str_ptr(str);
1492 1493
  mrb_int len = RSTR_LEN(s);
  char *p = RSTR_PTR(s);
mimaki's avatar
mimaki committed
1494 1495 1496 1497 1498 1499
  mrb_int key = 0;

  while (len--) {
    key = key*65599 + *p;
    p++;
  }
Jun Hiroe's avatar
Jun Hiroe committed
1500
  return key + (key>>5);
mimaki's avatar
mimaki committed
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
}

/* 15.2.10.5.20 */
/*
 * call-seq:
 *    str.hash   => fixnum
 *
 * Return a hash based on the string's length and content.
 */
static mrb_value
mrb_str_hash_m(mrb_state *mrb, mrb_value self)
{
  mrb_int key = mrb_str_hash(mrb, self);
  return mrb_fixnum_value(key);
}

/* 15.2.10.5.21 */
/*
 *  call-seq:
 *     str.include? other_str   => true or false
 *     str.include? fixnum      => true or false
 *
 *  Returns <code>true</code> if <i>str</i> contains the given string or
 *  character.
 *
 *     "hello".include? "lo"   #=> true
 *     "hello".include? "ol"   #=> false
 *     "hello".include? ?h     #=> true
 */
static mrb_value
mrb_str_include(mrb_state *mrb, mrb_value self)
{
  mrb_value str2;

1535 1536 1537 1538
  mrb_get_args(mrb, "S", &str2);
  if (str_index(mrb, self, str2, 0) < 0)
    return mrb_bool_value(FALSE);
  return mrb_bool_value(TRUE);
mimaki's avatar
mimaki committed
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
}

/* 15.2.10.5.22 */
/*
 *  call-seq:
 *     str.index(substring [, offset])   => fixnum or nil
 *     str.index(fixnum [, offset])      => fixnum or nil
 *     str.index(regexp [, offset])      => fixnum or nil
 *
 *  Returns the index of the first occurrence of the given
 *  <i>substring</i>,
 *  character (<i>fixnum</i>), or pattern (<i>regexp</i>) in <i>str</i>.
 *  Returns
 *  <code>nil</code> if not found.
 *  If the second parameter is present, it
 *  specifies the position in the string to begin the search.
 *
 *     "hello".index('e')             #=> 1
 *     "hello".index('lo')            #=> 3
 *     "hello".index('a')             #=> nil
 *     "hello".index(101)             #=> 1(101=0x65='e')
 *     "hello".index(/[aeiou]/, -3)   #=> 4
 */
static mrb_value
1563
mrb_str_index(mrb_state *mrb, mrb_value str)
mimaki's avatar
mimaki committed
1564 1565
{
  mrb_value *argv;
1566
  mrb_int argc;
mimaki's avatar
mimaki committed
1567
  mrb_value sub;
1568
  mrb_int pos, clen;
mimaki's avatar
mimaki committed
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581

  mrb_get_args(mrb, "*", &argv, &argc);
  if (argc == 2) {
    pos = mrb_fixnum(argv[1]);
    sub = argv[0];
  }
  else {
    pos = 0;
    if (argc > 0)
      sub = argv[0];
    else
      sub = mrb_nil_value();
  }
1582
  mrb_regexp_check(mrb, sub);
1583
  clen = RSTRING_CHAR_LEN(str);
mimaki's avatar
mimaki committed
1584
  if (pos < 0) {
1585
    pos += clen;
mimaki's avatar
mimaki committed
1586 1587 1588 1589
    if (pos < 0) {
      return mrb_nil_value();
    }
  }
1590
  if (pos >= clen) return mrb_nil_value();
1591
  pos = chars2bytes(str, 0, pos);
mimaki's avatar
mimaki committed
1592 1593 1594 1595 1596 1597 1598

  switch (mrb_type(sub)) {
    default: {
      mrb_value tmp;

      tmp = mrb_check_string_type(mrb, sub);
      if (mrb_nil_p(tmp)) {
1599
        mrb_raisef(mrb, E_TYPE_ERROR, "type mismatch: %S given", sub);
mimaki's avatar
mimaki committed
1600 1601 1602 1603 1604
      }
      sub = tmp;
    }
    /* fall through */
    case MRB_TT_STRING:
1605
      pos = str_index(mrb, str, sub, pos);
mimaki's avatar
mimaki committed
1606
      break;
kano4's avatar
kano4 committed
1607
  }
mimaki's avatar
mimaki committed
1608

kano4's avatar
kano4 committed
1609
  if (pos == -1) return mrb_nil_value();
1610
  pos = bytes2chars(RSTRING_PTR(str), pos);
1611
  BYTES_ALIGN_CHECK(pos);
kano4's avatar
kano4 committed
1612
  return mrb_fixnum_value(pos);
mimaki's avatar
mimaki committed
1613 1614
}

1615 1616
#define STR_REPLACE_SHARED_MIN 10

mimaki's avatar
mimaki committed
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
/* 15.2.10.5.24 */
/* 15.2.10.5.28 */
/*
 *  call-seq:
 *     str.replace(other_str)   => str
 *
 *     s = "hello"         #=> "hello"
 *     s.replace "world"   #=> "world"
 */
static mrb_value
mrb_str_replace(mrb_state *mrb, mrb_value str)
{
  mrb_value str2;

1631 1632
  mrb_get_args(mrb, "S", &str2);
  return str_replace(mrb, mrb_str_ptr(str), mrb_str_ptr(str2));
mimaki's avatar
mimaki committed
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
}

/* 15.2.10.5.23 */
/*
 *  call-seq:
 *     String.new(str="")   => new_str
 *
 *  Returns a new string object containing a copy of <i>str</i>.
 */
static mrb_value
mrb_str_init(mrb_state *mrb, mrb_value self)
{
1645
  mrb_value str2;
mimaki's avatar
mimaki committed
1646

1647 1648 1649
  if (mrb_get_args(mrb, "|S", &str2) == 1) {
    str_replace(mrb, mrb_str_ptr(self), mrb_str_ptr(str2));
  }
mimaki's avatar
mimaki committed
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
  return self;
}

/* 15.2.10.5.25 */
/* 15.2.10.5.41 */
/*
 *  call-seq:
 *     str.intern   => symbol
 *     str.to_sym   => symbol
 *
 *  Returns the <code>Symbol</code> corresponding to <i>str</i>, creating the
 *  symbol if it did not previously exist. See <code>Symbol#id2name</code>.
 *
 *     "Koala".intern         #=> :Koala
 *     s = 'cat'.to_sym       #=> :cat
 *     s == :cat              #=> true
 *     s = '@cat'.to_sym      #=> :@cat
 *     s == :@cat             #=> true
 *
 *  This can also be used to create symbols that cannot be represented using the
 *  <code>:xxx</code> notation.
 *
 *     'cat and dog'.to_sym   #=> :"cat and dog"
 */
1674
MRB_API mrb_value
mimaki's avatar
mimaki committed
1675 1676
mrb_str_intern(mrb_state *mrb, mrb_value self)
{
1677
  return mrb_symbol_value(mrb_intern_str(mrb, self));
mimaki's avatar
mimaki committed
1678 1679
}
/* ---------------------------------- */
1680
MRB_API mrb_value
mimaki's avatar
mimaki committed
1681 1682 1683 1684
mrb_obj_as_string(mrb_state *mrb, mrb_value obj)
{
  mrb_value str;

1685
  if (mrb_string_p(obj)) {
mimaki's avatar
mimaki committed
1686 1687 1688
    return obj;
  }
  str = mrb_funcall(mrb, obj, "to_s", 0);
1689
  if (!mrb_string_p(str))
mimaki's avatar
mimaki committed
1690 1691 1692 1693
    return mrb_any_to_s(mrb, obj);
  return str;
}

1694
MRB_API mrb_value
1695
mrb_ptr_to_str(mrb_state *mrb, void *p)
1696 1697 1698 1699
{
  struct RString *p_str;
  char *p1;
  char *p2;
1700
  uintptr_t n = (uintptr_t)p;
1701 1702

  p_str = str_new(mrb, NULL, 2 + sizeof(uintptr_t) * CHAR_BIT / 4);
1703
  p1 = RSTR_PTR(p_str);
1704 1705 1706 1707 1708 1709 1710 1711 1712
  *p1++ = '0';
  *p1++ = 'x';
  p2 = p1;

  do {
    *p2++ = mrb_digitmap[n % 16];
    n /= 16;
  } while (n > 0);
  *p2 = '\0';
1713
  RSTR_SET_LEN(p_str, (mrb_int)(p2 - RSTR_PTR(p_str)));
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723

  while (p1 < p2) {
    const char  c = *p1;
    *p1++ = *--p2;
    *p2 = c;
  }

  return mrb_obj_value(p_str);
}

1724
MRB_API mrb_value
Tomoyuki Sahara's avatar
Tomoyuki Sahara committed
1725 1726 1727 1728 1729
mrb_string_type(mrb_state *mrb, mrb_value str)
{
  return mrb_convert_type(mrb, str, MRB_TT_STRING, "String", "to_str");
}

1730
MRB_API mrb_value
mimaki's avatar
mimaki committed
1731 1732 1733 1734 1735
mrb_check_string_type(mrb_state *mrb, mrb_value str)
{
  return mrb_check_convert_type(mrb, str, MRB_TT_STRING, "String", "to_str");
}

1736
/* 15.2.10.5.30 */
mimaki's avatar
mimaki committed
1737 1738
/*
 *  call-seq:
1739
 *     str.reverse!   => str
mimaki's avatar
mimaki committed
1740
 *
1741
 *  Reverses <i>str</i> in place.
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
1742 1743
 */
static mrb_value
1744
mrb_str_reverse_bang(mrb_state *mrb, mrb_value str)
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
1745
{
1746 1747 1748 1749 1750 1751 1752 1753
#ifdef MRB_UTF8_STRING
  mrb_int utf8_len = RSTRING_CHAR_LEN(str);
  mrb_int len = RSTRING_LEN(str);

  if (utf8_len == len) goto bytes;
  if (utf8_len > 1) {
    char *buf;
    char *p, *e, *r;
mimaki's avatar
mimaki committed
1754

1755 1756 1757 1758 1759
    mrb_str_modify(mrb, mrb_str_ptr(str));
    len = RSTRING_LEN(str);
    buf = mrb_malloc(mrb, (size_t)len);
    p = buf;
    e = buf + len;
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
1760

1761 1762
    memcpy(buf, RSTRING_PTR(str), len);
    r = RSTRING_PTR(str) + len;
mimaki's avatar
mimaki committed
1763

1764
    while (p<e) {
1765
      mrb_int clen = utf8len(p, e);
1766 1767 1768 1769 1770
      r -= clen;
      memcpy(r, p, clen);
      p += clen;
    }
    mrb_free(mrb, buf);
1771
  }
1772
  return str;
mimaki's avatar
mimaki committed
1773

1774 1775 1776 1777 1778 1779
 bytes:
#endif
  {
    struct RString *s = mrb_str_ptr(str);
    char *p, *e;
    char c;
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
1780

1781 1782 1783 1784 1785
    mrb_str_modify(mrb, s);
    if (RSTR_LEN(s) > 1) {
      p = RSTR_PTR(s);
      e = p + RSTR_LEN(s) - 1;
      while (p < e) {
1786 1787
      c = *p;
      *p++ = *e;
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
1788
      *e-- = c;
1789
      }
mimaki's avatar
mimaki committed
1790
    }
1791
    return str;
mimaki's avatar
mimaki committed
1792 1793 1794
  }
}

1795 1796
/* ---------------------------------- */
/* 15.2.10.5.29 */
mimaki's avatar
mimaki committed
1797 1798
/*
 *  call-seq:
1799
 *     str.reverse   => new_str
mimaki's avatar
mimaki committed
1800
 *
1801
 *  Returns a new string with the characters from <i>str</i> in reverse order.
mimaki's avatar
mimaki committed
1802
 *
1803
 *     "stressed".reverse   #=> "desserts"
mimaki's avatar
mimaki committed
1804
 */
1805 1806
static mrb_value
mrb_str_reverse(mrb_state *mrb, mrb_value str)
mimaki's avatar
mimaki committed
1807
{
1808 1809 1810
  mrb_value str2 = mrb_str_dup(mrb, str);
  mrb_str_reverse_bang(mrb, str2);
  return str2;
mimaki's avatar
mimaki committed
1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832
}

/* 15.2.10.5.31 */
/*
 *  call-seq:
 *     str.rindex(substring [, fixnum])   => fixnum or nil
 *     str.rindex(fixnum [, fixnum])   => fixnum or nil
 *     str.rindex(regexp [, fixnum])   => fixnum or nil
 *
 *  Returns the index of the last occurrence of the given <i>substring</i>,
 *  character (<i>fixnum</i>), or pattern (<i>regexp</i>) in <i>str</i>. Returns
 *  <code>nil</code> if not found. If the second parameter is present, it
 *  specifies the position in the string to end the search---characters beyond
 *  this point will not be considered.
 *
 *     "hello".rindex('e')             #=> 1
 *     "hello".rindex('l')             #=> 3
 *     "hello".rindex('a')             #=> nil
 *     "hello".rindex(101)             #=> 1
 *     "hello".rindex(/[aeiou]/, -2)   #=> 1
 */
static mrb_value
1833
mrb_str_rindex(mrb_state *mrb, mrb_value str)
mimaki's avatar
mimaki committed
1834 1835
{
  mrb_value *argv;
1836
  mrb_int argc;
mimaki's avatar
mimaki committed
1837 1838
  mrb_value sub;
  mrb_value vpos;
1839
  mrb_int pos, len = RSTRING_CHAR_LEN(str);
mimaki's avatar
mimaki committed
1840 1841 1842 1843 1844 1845 1846 1847 1848

  mrb_get_args(mrb, "*", &argv, &argc);
  if (argc == 2) {
    sub = argv[0];
    vpos = argv[1];
    pos = mrb_fixnum(vpos);
    if (pos < 0) {
      pos += len;
      if (pos < 0) {
1849
        mrb_regexp_check(mrb, sub);
mimaki's avatar
mimaki committed
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861
        return mrb_nil_value();
      }
    }
    if (pos > len) pos = len;
  }
  else {
    pos = len;
    if (argc > 0)
      sub = argv[0];
    else
      sub = mrb_nil_value();
  }
1862
  pos = chars2bytes(str, 0, pos);
1863
  mrb_regexp_check(mrb, sub);
mimaki's avatar
mimaki committed
1864 1865 1866 1867 1868 1869 1870

  switch (mrb_type(sub)) {
    default: {
      mrb_value tmp;

      tmp = mrb_check_string_type(mrb, sub);
      if (mrb_nil_p(tmp)) {
1871
        mrb_raisef(mrb, E_TYPE_ERROR, "type mismatch: %S given", sub);
mimaki's avatar
mimaki committed
1872 1873 1874 1875 1876
      }
      sub = tmp;
    }
     /* fall through */
    case MRB_TT_STRING:
1877 1878 1879
      pos = str_rindex(mrb, str, sub, pos);
      if (pos >= 0) {
        pos = bytes2chars(RSTRING_PTR(str), pos);
1880
        BYTES_ALIGN_CHECK(pos);
1881 1882
        return mrb_fixnum_value(pos);
      }
mimaki's avatar
mimaki committed
1883 1884 1885 1886 1887 1888 1889 1890 1891 1892
      break;

  } /* end of switch (TYPE(sub)) */
  return mrb_nil_value();
}

/* 15.2.10.5.35 */

/*
 *  call-seq:
1893
 *     str.split(pattern="\n", [limit])   => anArray
mimaki's avatar
mimaki committed
1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908
 *
 *  Divides <i>str</i> into substrings based on a delimiter, returning an array
 *  of these substrings.
 *
 *  If <i>pattern</i> is a <code>String</code>, then its contents are used as
 *  the delimiter when splitting <i>str</i>. If <i>pattern</i> is a single
 *  space, <i>str</i> is split on whitespace, with leading whitespace and runs
 *  of contiguous whitespace characters ignored.
 *
 *  If <i>pattern</i> is a <code>Regexp</code>, <i>str</i> is divided where the
 *  pattern matches. Whenever the pattern matches a zero-length string,
 *  <i>str</i> is split into individual characters.
 *
 *  If <i>pattern</i> is omitted, the value of <code>$;</code> is used.  If
 *  <code>$;</code> is <code>nil</code> (which is the default), <i>str</i> is
1909
 *  split on whitespace as if ' ' were specified.
mimaki's avatar
mimaki committed
1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
 *
 *  If the <i>limit</i> parameter is omitted, trailing null fields are
 *  suppressed. If <i>limit</i> is a positive number, at most that number of
 *  fields will be returned (if <i>limit</i> is <code>1</code>, the entire
 *  string is returned as the only entry in an array). If negative, there is no
 *  limit to the number of fields returned, and trailing null fields are not
 *  suppressed.
 *
 *     " now's  the time".split        #=> ["now's", "the", "time"]
 *     " now's  the time".split(' ')   #=> ["now's", "the", "time"]
 *     " now's  the time".split(/ /)   #=> ["", "now's", "", "the", "time"]
 *     "hello".split(//)               #=> ["h", "e", "l", "l", "o"]
 *     "hello".split(//, 3)            #=> ["h", "e", "llo"]
 *
 *     "mellow yellow".split("ello")   #=> ["m", "w y", "w"]
 *     "1,2,,3,4,,".split(',')         #=> ["1", "2", "", "3", "4"]
 *     "1,2,,3,4,,".split(',', 4)      #=> ["1", "2", "", "3,4,,"]
 *     "1,2,,3,4,,".split(',', -4)     #=> ["1", "2", "", "3", "4", "", ""]
 */

static mrb_value
mrb_str_split_m(mrb_state *mrb, mrb_value str)
{
  int argc;
1934
  mrb_value spat = mrb_nil_value();
1935
  enum {awk, string, regexp} split_type = string;
1936 1937 1938
  long i = 0, lim_p;
  mrb_int beg;
  mrb_int end;
1939
  mrb_int lim = 0;
mimaki's avatar
mimaki committed
1940 1941
  mrb_value result, tmp;

1942
  argc = mrb_get_args(mrb, "|oi", &spat, &lim);
1943
  lim_p = (lim > 0 && argc == 2);
mimaki's avatar
mimaki committed
1944
  if (argc == 2) {
1945
    if (lim == 1) {
mimaki's avatar
mimaki committed
1946 1947
      if (RSTRING_LEN(str) == 0)
        return mrb_ary_new_capa(mrb, 0);
1948
      return mrb_ary_new_from_values(mrb, 1, &str);
mimaki's avatar
mimaki committed
1949 1950 1951 1952
    }
    i = 1;
  }

1953
  if (argc == 0 || mrb_nil_p(spat)) {
mimaki's avatar
mimaki committed
1954 1955 1956
    split_type = awk;
  }
  else {
1957
    if (mrb_string_p(spat)) {
mimaki's avatar
mimaki committed
1958
      split_type = string;
yui-knk's avatar
yui-knk committed
1959
      if (RSTRING_LEN(spat) == 1 && RSTRING_PTR(spat)[0] == ' ') {
mattn's avatar
mattn committed
1960
          split_type = awk;
mimaki's avatar
mimaki committed
1961 1962 1963
      }
    }
    else {
1964
      mrb_noregexp(mrb, str);
mimaki's avatar
mimaki committed
1965 1966 1967 1968 1969 1970
    }
  }

  result = mrb_ary_new(mrb);
  beg = 0;
  if (split_type == awk) {
Jun Hiroe's avatar
Jun Hiroe committed
1971
    mrb_bool skip = TRUE;
1972 1973
    mrb_int idx = 0;
    mrb_int str_len = RSTRING_LEN(str);
mimaki's avatar
mimaki committed
1974
    unsigned int c;
1975
    int ai = mrb_gc_arena_save(mrb);
mimaki's avatar
mimaki committed
1976

1977 1978 1979
    idx = end = beg;
    while (idx < str_len) {
      c = (unsigned char)RSTRING_PTR(str)[idx++];
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
1980
      if (skip) {
1981
        if (ISSPACE(c)) {
1982
          beg = idx;
1983 1984
        }
        else {
1985
          end = idx;
Jun Hiroe's avatar
Jun Hiroe committed
1986
          skip = FALSE;
1987 1988
          if (lim_p && lim <= i) break;
        }
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
1989
      }
1990
      else if (ISSPACE(c)) {
1991
        mrb_ary_push(mrb, result, byte_subseq(mrb, str, beg, end-beg));
1992
        mrb_gc_arena_restore(mrb, ai);
Jun Hiroe's avatar
Jun Hiroe committed
1993
        skip = TRUE;
1994
        beg = idx;
1995
        if (lim_p) ++i;
mimaki's avatar
mimaki committed
1996
      }
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
1997
      else {
1998
        end = idx;
mimaki's avatar
mimaki committed
1999 2000 2001
      }
    }
  }
2002
  else if (split_type == string) {
2003 2004 2005 2006 2007
    mrb_int str_len = RSTRING_LEN(str);
    mrb_int pat_len = RSTRING_LEN(spat);
    mrb_int idx = 0;
    int ai = mrb_gc_arena_save(mrb);

2008
    while (idx < str_len) {
2009 2010 2011 2012
      if (pat_len > 0) {
        end = mrb_memsearch(RSTRING_PTR(spat), pat_len, RSTRING_PTR(str)+idx, str_len - idx);
        if (end < 0) break;
      } else {
2013
        end = chars2bytes(str, idx, 1);
2014
      }
2015
      mrb_ary_push(mrb, result, byte_subseq(mrb, str, idx, end));
2016 2017 2018
      mrb_gc_arena_restore(mrb, ai);
      idx += end + pat_len;
      if (lim_p && lim <= ++i) break;
2019
    }
2020
    beg = idx;
2021
  }
mimaki's avatar
mimaki committed
2022
  else {
2023
    mrb_noregexp(mrb, str);
mimaki's avatar
mimaki committed
2024
  }
2025 2026 2027 2028 2029
  if (RSTRING_LEN(str) > 0 && (lim_p || RSTRING_LEN(str) > beg || lim < 0)) {
    if (RSTRING_LEN(str) == beg) {
      tmp = mrb_str_new_empty(mrb, str);
    }
    else {
2030
      tmp = byte_subseq(mrb, str, beg, RSTRING_LEN(str)-beg);
2031
    }
mimaki's avatar
mimaki committed
2032 2033
    mrb_ary_push(mrb, result, tmp);
  }
2034
  if (!lim_p && lim == 0) {
2035
    mrb_int len;
mimaki's avatar
mimaki committed
2036 2037 2038 2039 2040 2041 2042 2043
    while ((len = RARRAY_LEN(result)) > 0 &&
           (tmp = RARRAY_PTR(result)[len-1], RSTRING_LEN(tmp) == 0))
      mrb_ary_pop(mrb, result);
  }

  return result;
}

2044
MRB_API mrb_value
2045
mrb_str_len_to_inum(mrb_state *mrb, const char *str, size_t len, int base, int badcheck)
mimaki's avatar
mimaki committed
2046
{
2047 2048
  const char *p = str;
  const char *pend = str + len;
mimaki's avatar
mimaki committed
2049
  char sign = 1;
2050
  int c;
2051
  uint64_t n = 0;
2052
  mrb_int val;
mimaki's avatar
mimaki committed
2053 2054

#define conv_digit(c) \
2055 2056 2057
    (ISDIGIT(c) ? ((c) - '0') : \
     ISLOWER(c) ? ((c) - 'a' + 10) : \
     ISUPPER(c) ? ((c) - 'A' + 10) : \
mimaki's avatar
mimaki committed
2058 2059
     -1)

2060
  if (!p) {
mimaki's avatar
mimaki committed
2061 2062 2063
    if (badcheck) goto bad;
    return mrb_fixnum_value(0);
  }
2064 2065
  while (p<pend && ISSPACE(*p))
    p++;
mimaki's avatar
mimaki committed
2066

2067 2068
  if (p[0] == '+') {
    p++;
mimaki's avatar
mimaki committed
2069
  }
2070 2071
  else if (p[0] == '-') {
    p++;
mimaki's avatar
mimaki committed
2072 2073 2074
    sign = 0;
  }
  if (base <= 0) {
2075 2076
    if (p[0] == '0') {
      switch (p[1]) {
mimaki's avatar
mimaki committed
2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090
        case 'x': case 'X':
          base = 16;
          break;
        case 'b': case 'B':
          base = 2;
          break;
        case 'o': case 'O':
          base = 8;
          break;
        case 'd': case 'D':
          base = 10;
          break;
        default:
          base = 8;
2091
          break;
mimaki's avatar
mimaki committed
2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102
      }
    }
    else if (base < -1) {
      base = -base;
    }
    else {
      base = 10;
    }
  }
  switch (base) {
    case 2:
2103 2104
      if (p[0] == '0' && (p[1] == 'b'||p[1] == 'B')) {
        p += 2;
mimaki's avatar
mimaki committed
2105 2106 2107 2108 2109
      }
      break;
    case 3:
      break;
    case 8:
2110 2111
      if (p[0] == '0' && (p[1] == 'o'||p[1] == 'O')) {
        p += 2;
mimaki's avatar
mimaki committed
2112 2113 2114 2115
      }
    case 4: case 5: case 6: case 7:
      break;
    case 10:
2116 2117
      if (p[0] == '0' && (p[1] == 'd'||p[1] == 'D')) {
        p += 2;
mimaki's avatar
mimaki committed
2118 2119 2120 2121
      }
    case 9: case 11: case 12: case 13: case 14: case 15:
      break;
    case 16:
2122 2123
      if (p[0] == '0' && (p[1] == 'x'||p[1] == 'X')) {
        p += 2;
mimaki's avatar
mimaki committed
2124 2125 2126 2127
      }
      break;
    default:
      if (base < 2 || 36 < base) {
2128
        mrb_raisef(mrb, E_ARGUMENT_ERROR, "illegal radix %S", mrb_fixnum_value(base));
mimaki's avatar
mimaki committed
2129 2130 2131
      }
      break;
  } /* end of switch (base) { */
2132 2133 2134 2135
  if (p>=pend) {
    if (badcheck) goto bad;
    return mrb_fixnum_value(0);
  }
2136
  if (*p == '0') {    /* squeeze preceding 0s */
2137 2138 2139
    p++;
    while (p<pend) {
      c = *p++;
mimaki's avatar
mimaki committed
2140
      if (c == '_') {
2141
        if (p<pend && *p == '_') {
2142
          if (badcheck) goto bad;
mimaki's avatar
mimaki committed
2143
          break;
2144
        }
2145 2146 2147 2148 2149
        continue;
      }
      if (c != '0') {
        p--;
        break;
mimaki's avatar
mimaki committed
2150 2151
      }
    }
Syohei YOSHIDA's avatar
Syohei YOSHIDA committed
2152 2153
    if (*(p - 1) == '0')
      p--;
mimaki's avatar
mimaki committed
2154
  }
2155
  if (p == pend) {
mimaki's avatar
mimaki committed
2156 2157 2158
    if (badcheck) goto bad;
    return mrb_fixnum_value(0);
  }
2159
  for ( ;p<pend;p++) {
2160
    if (*p == '_') {
2161 2162
      p++;
      if (p==pend) {
2163
        if (badcheck) goto bad;
2164 2165
        continue;
      }
2166 2167 2168 2169
      if (*p == '_') {
        if (badcheck) goto bad;
        break;
      }
2170 2171 2172
    }
    if (badcheck && *p == '\0') {
      goto nullbyte;
2173 2174 2175 2176 2177 2178 2179
    }
    c = conv_digit(*p);
    if (c < 0 || c >= base) {
      break;
    }
    n *= base;
    n += c;
Yasuhiro Matsumoto's avatar
Yasuhiro Matsumoto committed
2180
    if (n > (uint64_t)MRB_INT_MAX + (sign ? 0 : 1)) {
2181 2182
      mrb_raisef(mrb, E_ARGUMENT_ERROR, "string (%S) too big for integer",
                 mrb_str_new(mrb, str, pend-str));
2183
    }
2184
  }
Yasuhiro Matsumoto's avatar
Yasuhiro Matsumoto committed
2185
  val = (mrb_int)n;
2186
  if (badcheck) {
2187
    if (p == str) goto bad; /* no number */
2188 2189
    while (p<pend && ISSPACE(*p)) p++;
    if (p<pend) goto bad;       /* trailing garbage */
2190
  }
mimaki's avatar
mimaki committed
2191

2192
  return mrb_fixnum_value(sign ? val : -val);
2193 2194 2195 2196
 nullbyte:
  mrb_raise(mrb, E_ARGUMENT_ERROR, "string contains null byte");
  /* not reached */
 bad:
2197
  mrb_raisef(mrb, E_ARGUMENT_ERROR, "invalid string for number(%S)",
2198
             mrb_inspect(mrb, mrb_str_new(mrb, str, pend-str)));
2199
  /* not reached */
mimaki's avatar
mimaki committed
2200 2201
  return mrb_fixnum_value(0);
}
2202

2203 2204 2205 2206 2207 2208
MRB_API mrb_value
mrb_cstr_to_inum(mrb_state *mrb, const char *str, int base, int badcheck)
{
  return mrb_str_len_to_inum(mrb, str, strlen(str), base, badcheck);
}

2209
MRB_API const char*
mimaki's avatar
mimaki committed
2210 2211
mrb_string_value_cstr(mrb_state *mrb, mrb_value *ptr)
{
2212 2213
  mrb_value str = mrb_str_to_str(mrb, *ptr);
  struct RString *ps = mrb_str_ptr(str);
2214
  mrb_int len = mrb_str_strlen(mrb, ps);
2215
  char *p = RSTR_PTR(ps);
mimaki's avatar
mimaki committed
2216

2217
  if (!p || p[len] != '\0') {
2218 2219 2220 2221
    if (RSTR_FROZEN_P(ps)) {
      *ptr = str = mrb_str_dup(mrb, str);
      ps = mrb_str_ptr(str);
    }
2222
    mrb_str_modify(mrb, ps);
2223
    return RSTR_PTR(ps);
mimaki's avatar
mimaki committed
2224
  }
2225
  return p;
mimaki's avatar
mimaki committed
2226 2227
}

2228
MRB_API mrb_value
2229
mrb_str_to_inum(mrb_state *mrb, mrb_value str, mrb_int base, mrb_bool badcheck)
mimaki's avatar
mimaki committed
2230
{
2231
  const char *s;
cubicdaiya's avatar
cubicdaiya committed
2232
  mrb_int len;
mimaki's avatar
mimaki committed
2233

2234
  s = mrb_string_value_ptr(mrb, str);
2235 2236
  len = RSTRING_LEN(str);
  return mrb_str_len_to_inum(mrb, s, len, base, badcheck);
mimaki's avatar
mimaki committed
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262
}

/* 15.2.10.5.38 */
/*
 *  call-seq:
 *     str.to_i(base=10)   => integer
 *
 *  Returns the result of interpreting leading characters in <i>str</i> as an
 *  integer base <i>base</i> (between 2 and 36). Extraneous characters past the
 *  end of a valid number are ignored. If there is not a valid number at the
 *  start of <i>str</i>, <code>0</code> is returned. This method never raises an
 *  exception.
 *
 *     "12345".to_i             #=> 12345
 *     "99 red balloons".to_i   #=> 99
 *     "0a".to_i                #=> 0
 *     "0a".to_i(16)            #=> 10
 *     "hello".to_i             #=> 0
 *     "1100101".to_i(2)        #=> 101
 *     "1100101".to_i(8)        #=> 294977
 *     "1100101".to_i(10)       #=> 1100101
 *     "1100101".to_i(16)       #=> 17826049
 */
static mrb_value
mrb_str_to_i(mrb_state *mrb, mrb_value self)
{
2263
  mrb_int base = 10;
mimaki's avatar
mimaki committed
2264

2265
  mrb_get_args(mrb, "|i", &base);
mimaki's avatar
mimaki committed
2266
  if (base < 0) {
2267
    mrb_raisef(mrb, E_ARGUMENT_ERROR, "illegal radix %S", mrb_fixnum_value(base));
mimaki's avatar
mimaki committed
2268
  }
2269
  return mrb_str_to_inum(mrb, self, base, FALSE);
mimaki's avatar
mimaki committed
2270 2271
}

2272
MRB_API double
cremno's avatar
cremno committed
2273
mrb_cstr_to_dbl(mrb_state *mrb, const char * p, mrb_bool badcheck)
mimaki's avatar
mimaki committed
2274 2275
{
  char *end;
cremno's avatar
cremno committed
2276
  char buf[DBL_DIG * 4 + 10];
mimaki's avatar
mimaki committed
2277
  double d;
2278

mimaki's avatar
mimaki committed
2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
  enum {max_width = 20};

  if (!p) return 0.0;
  while (ISSPACE(*p)) p++;

  if (!badcheck && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
    return 0.0;
  }
  d = strtod(p, &end);
  if (p == end) {
    if (badcheck) {
bad:
2291
      mrb_raisef(mrb, E_ARGUMENT_ERROR, "invalid string for float(%S)", mrb_str_new_cstr(mrb, p));
2292
      /* not reached */
mimaki's avatar
mimaki committed
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334
    }
    return d;
  }
  if (*end) {
    char *n = buf;
    char *e = buf + sizeof(buf) - 1;
    char prev = 0;

    while (p < end && n < e) prev = *n++ = *p++;
    while (*p) {
      if (*p == '_') {
        /* remove underscores between digits */
        if (badcheck) {
          if (n == buf || !ISDIGIT(prev)) goto bad;
          ++p;
          if (!ISDIGIT(*p)) goto bad;
        }
        else {
          while (*++p == '_');
          continue;
        }
      }
      prev = *p++;
      if (n < e) *n++ = prev;
    }
    *n = '\0';
    p = buf;

    if (!badcheck && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
      return 0.0;
    }

    d = strtod(p, &end);
    if (badcheck) {
      if (!end || p == end) goto bad;
      while (*end && ISSPACE(*end)) end++;
      if (*end) goto bad;
    }
  }
  return d;
}

2335
MRB_API double
cremno's avatar
cremno committed
2336
mrb_str_to_dbl(mrb_state *mrb, mrb_value str, mrb_bool badcheck)
mimaki's avatar
mimaki committed
2337 2338
{
  char *s;
cubicdaiya's avatar
cubicdaiya committed
2339
  mrb_int len;
mimaki's avatar
mimaki committed
2340

2341
  str = mrb_str_to_str(mrb, str);
mimaki's avatar
mimaki committed
2342 2343 2344 2345 2346 2347 2348
  s = RSTRING_PTR(str);
  len = RSTRING_LEN(str);
  if (s) {
    if (badcheck && memchr(s, '\0', len)) {
      mrb_raise(mrb, E_ARGUMENT_ERROR, "string for Float contains null byte");
    }
    if (s[len]) {    /* no sentinel somehow */
2349
      struct RString *temp_str = str_new(mrb, s, len);
2350
      s = RSTR_PTR(temp_str);
mimaki's avatar
mimaki committed
2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
    }
  }
  return mrb_cstr_to_dbl(mrb, s, badcheck);
}

/* 15.2.10.5.39 */
/*
 *  call-seq:
 *     str.to_f   => float
 *
 *  Returns the result of interpreting leading characters in <i>str</i> as a
 *  floating point number. Extraneous characters past the end of a valid number
 *  are ignored. If there is not a valid number at the start of <i>str</i>,
 *  <code>0.0</code> is returned. This method never raises an exception.
 *
 *     "123.45e1".to_f        #=> 1234.5
 *     "45.67 degrees".to_f   #=> 45.67
 *     "thx1138".to_f         #=> 0.0
 */
static mrb_value
mrb_str_to_f(mrb_state *mrb, mrb_value self)
{
2373
  return mrb_float_value(mrb, mrb_str_to_dbl(mrb, self, FALSE));
mimaki's avatar
mimaki committed
2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403
}

/* 15.2.10.5.40 */
/*
 *  call-seq:
 *     str.to_s     => str
 *     str.to_str   => str
 *
 *  Returns the receiver.
 */
static mrb_value
mrb_str_to_s(mrb_state *mrb, mrb_value self)
{
  if (mrb_obj_class(mrb, self) != mrb->string_class) {
    return mrb_str_dup(mrb, self);
  }
  return self;
}

/* 15.2.10.5.43 */
/*
 *  call-seq:
 *     str.upcase!   => str or nil
 *
 *  Upcases the contents of <i>str</i>, returning <code>nil</code> if no changes
 *  were made.
 */
static mrb_value
mrb_str_upcase_bang(mrb_state *mrb, mrb_value str)
{
2404 2405
  struct RString *s = mrb_str_ptr(str);
  char *p, *pend;
Jun Hiroe's avatar
Jun Hiroe committed
2406
  mrb_bool modify = FALSE;
mimaki's avatar
mimaki committed
2407

h2so5's avatar
h2so5 committed
2408
  mrb_str_modify(mrb, s);
2409 2410 2411 2412
  p = RSTRING_PTR(str);
  pend = RSTRING_END(str);
  while (p < pend) {
    if (ISLOWER(*p)) {
2413
      *p = TOUPPER(*p);
Jun Hiroe's avatar
Jun Hiroe committed
2414
      modify = TRUE;
mimaki's avatar
mimaki committed
2415
    }
2416
    p++;
mimaki's avatar
mimaki committed
2417
  }
Yukihiro Matsumoto's avatar
Yukihiro Matsumoto committed
2418

mimaki's avatar
mimaki committed
2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429
  if (modify) return str;
  return mrb_nil_value();
}

/* 15.2.10.5.42 */
/*
 *  call-seq:
 *     str.upcase   => new_str
 *
 *  Returns a copy of <i>str</i> with all lowercase letters replaced with their
 *  uppercase counterparts. The operation is locale insensitive---only
2430
 *  characters 'a' to 'z' are affected.
mimaki's avatar
mimaki committed
2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443
 *
 *     "hEllO".upcase   #=> "HELLO"
 */
static mrb_value
mrb_str_upcase(mrb_state *mrb, mrb_value self)
{
  mrb_value str;

  str = mrb_str_dup(mrb, self);
  mrb_str_upcase_bang(mrb, str);
  return str;
}

2444 2445
#define IS_EVSTR(p,e) ((p) < (e) && (*(p) == '$' || *(p) == '@' || *(p) == '{'))

mimaki's avatar
mimaki committed
2446 2447 2448 2449 2450 2451 2452 2453 2454 2455
/*
 *  call-seq:
 *     str.dump   -> new_str
 *
 *  Produces a version of <i>str</i> with all nonprinting characters replaced by
 *  <code>\nnn</code> notation and all special characters escaped.
 */
mrb_value
mrb_str_dump(mrb_state *mrb, mrb_value str)
{
h2so5's avatar
h2so5 committed
2456 2457 2458 2459
  mrb_int len;
  const char *p, *pend;
  char *q;
  struct RString *result;
mimaki's avatar
mimaki committed
2460

h2so5's avatar
h2so5 committed
2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484
  len = 2;                  /* "" */
  p = RSTRING_PTR(str); pend = p + RSTRING_LEN(str);
  while (p < pend) {
    unsigned char c = *p++;
    switch (c) {
      case '"':  case '\\':
      case '\n': case '\r':
      case '\t': case '\f':
      case '\013': case '\010': case '\007': case '\033':
        len += 2;
        break;

      case '#':
        len += IS_EVSTR(p, pend) ? 2 : 1;
        break;

      default:
        if (ISPRINT(c)) {
          len++;
        }
        else {
          len += 4;                /* \NNN */
        }
        break;
mimaki's avatar
mimaki committed
2485
    }
h2so5's avatar
h2so5 committed
2486
  }
mimaki's avatar
mimaki committed
2487

h2so5's avatar
h2so5 committed
2488 2489 2490
  result = str_new(mrb, 0, len);
  str_with_class(mrb, result, str);
  p = RSTRING_PTR(str); pend = p + RSTRING_LEN(str);
2491
  q = RSTR_PTR(result);
h2so5's avatar
h2so5 committed
2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506
  *q++ = '"';
  while (p < pend) {
    unsigned char c = *p++;

    switch (c) {
      case '"':
      case '\\':
        *q++ = '\\';
        *q++ = c;
        break;

      case '\n':
        *q++ = '\\';
        *q++ = 'n';
        break;
2507

h2so5's avatar
h2so5 committed
2508 2509 2510 2511
      case '\r':
        *q++ = '\\';
        *q++ = 'r';
        break;
2512

h2so5's avatar
h2so5 committed
2513 2514 2515 2516
      case '\t':
        *q++ = '\\';
        *q++ = 't';
        break;
2517

h2so5's avatar
h2so5 committed
2518 2519 2520 2521
      case '\f':
        *q++ = '\\';
        *q++ = 'f';
        break;
2522

h2so5's avatar
h2so5 committed
2523 2524 2525 2526
      case '\013':
        *q++ = '\\';
        *q++ = 'v';
        break;
2527

h2so5's avatar
h2so5 committed
2528 2529 2530 2531
      case '\010':
        *q++ = '\\';
        *q++ = 'b';
        break;
2532

h2so5's avatar
h2so5 committed
2533 2534 2535 2536
      case '\007':
        *q++ = '\\';
        *q++ = 'a';
        break;
2537

h2so5's avatar
h2so5 committed
2538 2539 2540 2541
      case '\033':
        *q++ = '\\';
        *q++ = 'e';
        break;
2542

h2so5's avatar
h2so5 committed
2543 2544 2545 2546
      case '#':
        if (IS_EVSTR(p, pend)) *q++ = '\\';
        *q++ = '#';
        break;
2547

h2so5's avatar
h2so5 committed
2548 2549
      default:
        if (ISPRINT(c)) {
mimaki's avatar
mimaki committed
2550
          *q++ = c;
h2so5's avatar
h2so5 committed
2551 2552
        }
        else {
2553
          *q++ = '\\';
2554 2555 2556
          q[2] = '0' + c % 8; c /= 8;
          q[1] = '0' + c % 8; c /= 8;
          q[0] = '0' + c % 8;
2557
          q += 3;
h2so5's avatar
h2so5 committed
2558
        }
mimaki's avatar
mimaki committed
2559
    }
h2so5's avatar
h2so5 committed
2560
  }
cubicdaiya's avatar
cubicdaiya committed
2561
  *q = '"';
h2so5's avatar
h2so5 committed
2562
  return mrb_obj_value(result);
mimaki's avatar
mimaki committed
2563 2564
}

2565
MRB_API mrb_value
2566
mrb_str_cat(mrb_state *mrb, mrb_value str, const char *ptr, size_t len)
mimaki's avatar
mimaki committed
2567
{
2568
  str_buf_cat(mrb, mrb_str_ptr(str), ptr, len);
2569
  return str;
mimaki's avatar
mimaki committed
2570 2571
}

2572
MRB_API mrb_value
2573
mrb_str_cat_cstr(mrb_state *mrb, mrb_value str, const char *ptr)
mimaki's avatar
mimaki committed
2574
{
2575
  return mrb_str_cat(mrb, str, ptr, strlen(ptr));
mimaki's avatar
mimaki committed
2576 2577
}

2578
MRB_API mrb_value
2579 2580 2581 2582 2583
mrb_str_cat_str(mrb_state *mrb, mrb_value str, mrb_value str2)
{
  return mrb_str_cat(mrb, str, RSTRING_PTR(str2), RSTRING_LEN(str2));
}

2584
MRB_API mrb_value
2585
mrb_str_append(mrb_state *mrb, mrb_value str1, mrb_value str2)
mimaki's avatar
mimaki committed
2586
{
2587
  str2 = mrb_str_to_str(mrb, str2);
2588
  return mrb_str_cat_str(mrb, str1, str2);
mimaki's avatar
mimaki committed
2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606
}

#define CHAR_ESC_LEN 13 /* sizeof(\x{ hex of 32bit unsigned int } \0) */

/*
 * call-seq:
 *   str.inspect   -> string
 *
 * Returns a printable version of _str_, surrounded by quote marks,
 * with special characters escaped.
 *
 *    str = "hello"
 *    str[3] = "\b"
 *    str.inspect       #=> "\"hel\\bo\""
 */
mrb_value
mrb_str_inspect(mrb_state *mrb, mrb_value str)
{
2607 2608 2609
  const char *p, *pend;
  char buf[CHAR_ESC_LEN + 1];
  mrb_value result = mrb_str_new_lit(mrb, "\"");
mimaki's avatar
mimaki committed
2610

2611 2612 2613
  p = RSTRING_PTR(str); pend = RSTRING_END(str);
  for (;p < pend; p++) {
    unsigned char c, cc;
2614 2615 2616 2617 2618 2619
#ifdef MRB_UTF8_STRING
    mrb_int clen;

    clen = utf8len(p, pend);
    if (clen > 1) {
      mrb_int i;
mimaki's avatar
mimaki committed
2620

2621 2622 2623 2624
      for (i=0; i<clen; i++) {
        buf[i] = p[i];
      }
      mrb_str_cat(mrb, result, buf, clen);
2625
      p += clen-1;
2626 2627 2628
      continue;
    }
#endif
2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655
    c = *p;
    if (c == '"'|| c == '\\' || (c == '#' && IS_EVSTR(p, pend))) {
      buf[0] = '\\'; buf[1] = c;
      mrb_str_cat(mrb, result, buf, 2);
      continue;
    }
    if (ISPRINT(c)) {
      buf[0] = c;
      mrb_str_cat(mrb, result, buf, 1);
      continue;
    }
    switch (c) {
      case '\n': cc = 'n'; break;
      case '\r': cc = 'r'; break;
      case '\t': cc = 't'; break;
      case '\f': cc = 'f'; break;
      case '\013': cc = 'v'; break;
      case '\010': cc = 'b'; break;
      case '\007': cc = 'a'; break;
      case 033: cc = 'e'; break;
      default: cc = 0; break;
    }
    if (cc) {
      buf[0] = '\\';
      buf[1] = (char)cc;
      mrb_str_cat(mrb, result, buf, 2);
      continue;
mimaki's avatar
mimaki committed
2656
    }
2657 2658 2659 2660 2661 2662 2663 2664 2665 2666
    else {
      buf[0] = '\\';
      buf[3] = '0' + c % 8; c /= 8;
      buf[2] = '0' + c % 8; c /= 8;
      buf[1] = '0' + c % 8;
      mrb_str_cat(mrb, result, buf, 4);
      continue;
    }
  }
  mrb_str_cat_lit(mrb, result, "\"");
mimaki's avatar
mimaki committed
2667

2668
  return result;
mimaki's avatar
mimaki committed
2669 2670
}

2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683
/*
 * call-seq:
 *   str.bytes   -> array of fixnums
 *
 * Returns an array of bytes in _str_.
 *
 *    str = "hello"
 *    str.bytes       #=> [104, 101, 108, 108, 111]
 */
static mrb_value
mrb_str_bytes(mrb_state *mrb, mrb_value str)
{
  struct RString *s = mrb_str_ptr(str);
2684 2685
  mrb_value a = mrb_ary_new_capa(mrb, RSTR_LEN(s));
  unsigned char *p = (unsigned char *)(RSTR_PTR(s)), *pend = p + RSTR_LEN(s);
2686 2687 2688 2689 2690 2691 2692 2693

  while (p < pend) {
    mrb_ary_push(mrb, a, mrb_fixnum_value(p[0]));
    p++;
  }
  return a;
}

mimaki's avatar
mimaki committed
2694 2695 2696 2697 2698 2699
/* ---------------------------*/
void
mrb_init_string(mrb_state *mrb)
{
  struct RClass *s;

2700 2701
  mrb_static_assert(RSTRING_EMBED_LEN_MAX < (1 << 5), "pointer size too big for embedded string");

Seba Gamboa's avatar
Seba Gamboa committed
2702
  mrb->string_class = s = mrb_define_class(mrb, "String", mrb->object_class);             /* 15.2.10 */
mimaki's avatar
mimaki committed
2703
  MRB_SET_INSTANCE_TT(s, MRB_TT_STRING);
2704

2705
  mrb_define_method(mrb, s, "bytesize",        mrb_str_bytesize,        MRB_ARGS_NONE());
2706 2707 2708 2709 2710

  mrb_define_method(mrb, s, "<=>",             mrb_str_cmp_m,           MRB_ARGS_REQ(1)); /* 15.2.10.5.1  */
  mrb_define_method(mrb, s, "==",              mrb_str_equal_m,         MRB_ARGS_REQ(1)); /* 15.2.10.5.2  */
  mrb_define_method(mrb, s, "+",               mrb_str_plus_m,          MRB_ARGS_REQ(1)); /* 15.2.10.5.4  */
  mrb_define_method(mrb, s, "*",               mrb_str_times,           MRB_ARGS_REQ(1)); /* 15.2.10.5.5  */
2711 2712
  mrb_define_method(mrb, s, "[]",              mrb_str_aref_m,          MRB_ARGS_ANY());  /* 15.2.10.5.6  */
  mrb_define_method(mrb, s, "capitalize",      mrb_str_capitalize,      MRB_ARGS_NONE()); /* 15.2.10.5.7  */
2713
  mrb_define_method(mrb, s, "capitalize!",     mrb_str_capitalize_bang, MRB_ARGS_NONE()); /* 15.2.10.5.8  */
2714 2715
  mrb_define_method(mrb, s, "chomp",           mrb_str_chomp,           MRB_ARGS_ANY());  /* 15.2.10.5.9  */
  mrb_define_method(mrb, s, "chomp!",          mrb_str_chomp_bang,      MRB_ARGS_ANY());  /* 15.2.10.5.10 */
2716 2717
  mrb_define_method(mrb, s, "chop",            mrb_str_chop,            MRB_ARGS_NONE()); /* 15.2.10.5.11 */
  mrb_define_method(mrb, s, "chop!",           mrb_str_chop_bang,       MRB_ARGS_NONE()); /* 15.2.10.5.12 */
2718 2719 2720 2721
  mrb_define_method(mrb, s, "downcase",        mrb_str_downcase,        MRB_ARGS_NONE()); /* 15.2.10.5.13 */
  mrb_define_method(mrb, s, "downcase!",       mrb_str_downcase_bang,   MRB_ARGS_NONE()); /* 15.2.10.5.14 */
  mrb_define_method(mrb, s, "empty?",          mrb_str_empty_p,         MRB_ARGS_NONE()); /* 15.2.10.5.16 */
  mrb_define_method(mrb, s, "eql?",            mrb_str_eql,             MRB_ARGS_REQ(1)); /* 15.2.10.5.17 */
mattn's avatar
mattn committed
2722

2723
  mrb_define_method(mrb, s, "hash",            mrb_str_hash_m,          MRB_ARGS_NONE()); /* 15.2.10.5.20 */
2724
  mrb_define_method(mrb, s, "include?",        mrb_str_include,         MRB_ARGS_REQ(1)); /* 15.2.10.5.21 */
2725
  mrb_define_method(mrb, s, "index",           mrb_str_index,           MRB_ARGS_ANY());  /* 15.2.10.5.22 */
2726 2727 2728
  mrb_define_method(mrb, s, "initialize",      mrb_str_init,            MRB_ARGS_REQ(1)); /* 15.2.10.5.23 */
  mrb_define_method(mrb, s, "initialize_copy", mrb_str_replace,         MRB_ARGS_REQ(1)); /* 15.2.10.5.24 */
  mrb_define_method(mrb, s, "intern",          mrb_str_intern,          MRB_ARGS_NONE()); /* 15.2.10.5.25 */
2729
  mrb_define_method(mrb, s, "length",          mrb_str_size,            MRB_ARGS_NONE()); /* 15.2.10.5.26 */
2730 2731 2732
  mrb_define_method(mrb, s, "replace",         mrb_str_replace,         MRB_ARGS_REQ(1)); /* 15.2.10.5.28 */
  mrb_define_method(mrb, s, "reverse",         mrb_str_reverse,         MRB_ARGS_NONE()); /* 15.2.10.5.29 */
  mrb_define_method(mrb, s, "reverse!",        mrb_str_reverse_bang,    MRB_ARGS_NONE()); /* 15.2.10.5.30 */
2733
  mrb_define_method(mrb, s, "rindex",          mrb_str_rindex,          MRB_ARGS_ANY());  /* 15.2.10.5.31 */
2734
  mrb_define_method(mrb, s, "size",            mrb_str_size,            MRB_ARGS_NONE()); /* 15.2.10.5.33 */
2735 2736 2737
  mrb_define_method(mrb, s, "slice",           mrb_str_aref_m,          MRB_ARGS_ANY());  /* 15.2.10.5.34 */
  mrb_define_method(mrb, s, "split",           mrb_str_split_m,         MRB_ARGS_ANY());  /* 15.2.10.5.35 */

2738 2739
  mrb_define_method(mrb, s, "to_f",            mrb_str_to_f,            MRB_ARGS_NONE()); /* 15.2.10.5.38 */
  mrb_define_method(mrb, s, "to_i",            mrb_str_to_i,            MRB_ARGS_ANY());  /* 15.2.10.5.39 */
2740
  mrb_define_method(mrb, s, "to_s",            mrb_str_to_s,            MRB_ARGS_NONE()); /* 15.2.10.5.40 */
2741
  mrb_define_method(mrb, s, "to_str",          mrb_str_to_s,            MRB_ARGS_NONE());
2742
  mrb_define_method(mrb, s, "to_sym",          mrb_str_intern,          MRB_ARGS_NONE()); /* 15.2.10.5.41 */
2743 2744
  mrb_define_method(mrb, s, "upcase",          mrb_str_upcase,          MRB_ARGS_NONE()); /* 15.2.10.5.42 */
  mrb_define_method(mrb, s, "upcase!",         mrb_str_upcase_bang,     MRB_ARGS_NONE()); /* 15.2.10.5.43 */
2745 2746
  mrb_define_method(mrb, s, "inspect",         mrb_str_inspect,         MRB_ARGS_NONE()); /* 15.2.10.5.46(x) */
  mrb_define_method(mrb, s, "bytes",           mrb_str_bytes,           MRB_ARGS_NONE());
2747 2748

  mrb_define_method(mrb, s, "freeze",          mrb_str_freeze,          MRB_ARGS_NONE());
mimaki's avatar
mimaki committed
2749
}