str.c 35.8 KB
Newer Older
eg's avatar
eg committed
1 2
/*
 *
3
 * s t r . c                            -- Strings management
eg's avatar
eg committed
4
 *
5
 * Copyright © 1993-2018 Erick Gallesio - I3S-CNRS/ESSI <eg@unice.fr>
Erick's avatar
.  
Erick committed
6
 *
eg's avatar
eg committed
7 8 9 10 11
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
Erick's avatar
.  
Erick committed
12
 *
eg's avatar
eg committed
13 14 15 16
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
Erick's avatar
.  
Erick committed
17
 *
eg's avatar
eg committed
18 19
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
Erick's avatar
.  
Erick committed
20
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
eg's avatar
eg committed
21 22 23 24
 * USA.
 *
 *           Author: Erick Gallesio [eg@unice.fr]
 *    Creation date: ??????
25
 * Last file update: 26-Jun-2018 15:23 (eg)
eg's avatar
eg committed
26 27 28
 */

#include <ctype.h>
29
#include <wctype.h>
eg's avatar
eg committed
30 31
#include "stklos.h"

32

33
/* min size added to a string when reallocated in a string-set! */
34
#define UTF8_STRING_INCR        8
35 36


eg's avatar
eg committed
37
/*
Erick's avatar
.  
Erick committed
38
 * Utilities
eg's avatar
eg committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
 *
 */

static void error_bad_string(SCM s)
{
  STk_error("bad string ~s", s);
}

static void error_bad_character(SCM s)
{
  STk_error("bad character ~S", s);
}

static void error_change_const_string(SCM s)
{
  STk_error("changing the constant string ~s is not allowed", s);
}

57 58 59 60
static void error_index_out_of_bound(SCM str, SCM index)
{
  STk_error("index ~S out of bound in string ~S", index, str);
}
eg's avatar
eg committed
61

Erick's avatar
Erick committed
62
static void error_bad_sequence(char *str)
63
{
Erick's avatar
Erick committed
64
  STk_error("bad UTF-8 sequence in '%s'", str);
65 66 67
}


eg's avatar
eg committed
68 69 70 71
static int stringcomp(SCM s1, SCM s2)
{
  register char *str1, *str2;

Erick's avatar
.  
Erick committed
72
  if (!STRINGP(s1)) error_bad_string(s1);
eg's avatar
eg committed
73 74
  if (!STRINGP(s2)) error_bad_string(s2);

75 76 77 78 79 80 81 82 83
  if (STk_use_utf8 && (!STRING_MONOBYTE(s1) || !STRING_MONOBYTE(s2))) {
    /* At least one string is multi-bytes */
    uint32_t ch1, ch2;
    char *end1, *end2;

    str1 = STRING_CHARS(s1); end1 = str1 + STRING_SIZE(s1);
    str2 = STRING_CHARS(s2); end2 = str2 + STRING_SIZE(s2);

    while ((str1 < end1) && (str2 < end2)) {
84
      if ((str1 = STk_utf8_grab_char(str1, &ch1)) == NULL)
85
        error_bad_sequence(STRING_CHARS(s1));
86
      if ((str2 = STk_utf8_grab_char(str2, &ch2)) == NULL)
87
        error_bad_sequence(STRING_CHARS(s2));
88 89 90 91 92 93 94 95 96 97 98

      if (ch1 != ch2) return ch1 - ch2;
    }

    /* str1 < end1 || str2 < end2 */
    return (str1 < end1) ? +1 : ((str2 < end2) ? -1 : 0);
  } else {
    /* fast-path for mono-byte strings */
    register int l1, l2;

    for (l1=STRING_SIZE(s1), str1=STRING_CHARS(s1),
99 100 101
         l2=STRING_SIZE(s2),str2=STRING_CHARS(s2);
         l1 && l2;
         l1--, str1++, l2--, str2++)
102
      if (*str1 != *str2) return ((unsigned char) *str1 - (unsigned char) *str2);
Erick's avatar
.  
Erick committed
103

104 105 106
    /* l1 == 0 || l2 == 0 */
    return l1 ? +1 : (l2 ? -1 : 0);
  }
eg's avatar
eg committed
107 108 109 110 111 112 113
}


static int stringcompi(SCM s1, SCM s2)
{
  register char *str1, *str2;

Erick's avatar
.  
Erick committed
114
  if (!STRINGP(s1)) error_bad_string(s1);
eg's avatar
eg committed
115 116
  if (!STRINGP(s2)) error_bad_string(s2);

117 118 119 120 121 122 123 124 125
  if (STk_use_utf8 && (!STRING_MONOBYTE(s1) || !STRING_MONOBYTE(s2))) {
    /* At least one string is multi-bytes */
    uint32_t ch1, ch2;
    char *end1, *end2;

    str1 = STRING_CHARS(s1); end1 = str1 + STRING_SIZE(s1);
    str2 = STRING_CHARS(s2); end2 = str2 + STRING_SIZE(s2);

    while ((str1 < end1) && (str2 < end2)) {
126
      if ((str1 = STk_utf8_grab_char(str1, &ch1)) == NULL)
127
        error_bad_sequence(STRING_CHARS(s1));
128
      if ((str2 = STk_utf8_grab_char(str2, &ch2)) == NULL)
129
        error_bad_sequence(STRING_CHARS(s2));
130 131 132 133 134 135 136 137 138 139 140

      if (towlower(ch1) != towlower(ch2)) return towlower(ch1) - towlower(ch2);
    }

    /* str1 < end1 || str2 < end2 */
    return (str1 < end1) ? +1 : ((str2 < end2) ? -1 : 0);
  } else {
    /* fast-path for mono-byte strings */
    register int l1, l2;

    for (l1=STRING_SIZE(s1), str1=STRING_CHARS(s1),
141 142 143
         l2=STRING_SIZE(s2),str2=STRING_CHARS(s2);
         l1 && l2;
         l1--, str1++, l2--, str2++)
144
      if (tolower(*str1) != tolower(*str2))
145
        return (tolower(*str1) - tolower(*str2));
eg's avatar
eg committed
146

147 148 149
    /* l1 == 0 || l2 == 0 */
    return l1 ? +1 : (l2 ? -1 : 0);
  }
eg's avatar
eg committed
150 151
}

152

eg's avatar
eg committed
153 154 155
static SCM control_index(int argc, SCM *argv, int *pstart, int *pend)
{
  SCM s = NULL;
156
  long len, start=0, end=-1;
eg's avatar
eg committed
157 158 159 160 161

  /* Controling number of arguments */
  switch (argc) {
  case 1: s = argv[0]; break;
  case 2: s = argv[0]; start = STk_integer_value(argv[-1]); break;
Erick's avatar
.  
Erick committed
162
  case 3: s = argv[0]; start = STk_integer_value(argv[-1]);
163
          end = STk_integer_value(argv[-2]); break;
eg's avatar
eg committed
164 165 166 167 168
  default: STk_error("incorrect number of argument (%d)", argc);
  }

  /* Controlling s */
  if (!STRINGP(s)) error_bad_string(s);
169
  len = STRING_LENGTH(s);
eg's avatar
eg committed
170 171 172 173 174

  /* Controling start index */
  if (start == LONG_MIN || start < 0 || start > len)
    /* argc cannot be 1 (start would be 0) */
    STk_error("bad starting index ~S", argv[(argc==2) ? 0 : -1]);
Erick's avatar
.  
Erick committed
175

eg's avatar
eg committed
176 177 178 179 180 181 182 183
  /* controling end index */
  if (end == -1)
    end = len;
  else
    if (end == LONG_MIN  || end < 0 || end > len)
      /* We have an end index ==> argc = 3 */
      STk_error("bad ending index ~S", argv[0]);

Erick's avatar
.  
Erick committed
184
  if (start > end)
eg's avatar
eg committed
185 186 187 188 189 190 191 192
    STk_error("low index is greater than high index");

  /* everything is correct, return values */
  *pstart = start;
  *pend   = end;
  return s;
}

193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
static uint32_t *string2int(char *s, int len, int *utf8_len, wint_t(*func)(wint_t))
{
  uint32_t ch, *tmp, *buff = STk_must_malloc_atomic(len * sizeof(uint32_t));
  int space = 0;

  for (tmp = buff; len--; tmp++) {
    s      = STk_utf8_grab_char(s, &ch);
    ch     = func(ch);
    space += STk_utf8_char_bytes_needed(ch);
    *tmp   = ch;
  }

  *utf8_len = space;
  return buff;
}

static SCM make_string_from_int_array(uint32_t *buff, int len, int utf8_len)
{
  SCM z;
  char *s, *end;

  NEWCELL(z, string);
  STRING_CHARS(z)  = s = STk_must_malloc_atomic(utf8_len + 1);
  STRING_SPACE(z)  = STRING_SIZE(z) = utf8_len;
  STRING_LENGTH(z) = len;

  end = s + utf8_len;
  while (s < end) {
    s += STk_char2utf8(*buff++, s);
  }
  *s = '\0';

 return z;
}


static void copy_array(uint32_t *buff, int len, char* from)
{
  while (len--)
    from += STk_char2utf8(*buff++, from);
}
eg's avatar
eg committed
234 235 236 237 238 239


SCM STk_makestring(int len, char *init)
{
  register SCM z;

240 241 242
  NEWCELL(z, string);
  STRING_CHARS(z) = STk_must_malloc_atomic(len + 1);
  STRING_SPACE(z) = STRING_SIZE(z) = STRING_LENGTH(z) = len;
eg's avatar
eg committed
243

Erick's avatar
.  
Erick committed
244 245 246
  if (init) {
    memcpy(STRING_CHARS(z), init, (size_t) len);
    STRING_CHARS(z)[len] = '\0'; /* so that STRING_CHARS is compatible with C */
247 248 249 250

    if (STk_use_utf8)
      /* Eventually correct the length to be in charcaters instead of bytes */
      STRING_LENGTH(z) = STk_utf8_strlen(STRING_CHARS(z), len);
Erick's avatar
.  
Erick committed
251 252 253 254
  }
  else
    bzero(STRING_CHARS(z), len+1);

eg's avatar
eg committed
255 256 257 258 259 260 261 262 263
  return z;
}


SCM STk_Cstring2string(char *str) /* Embed a C string in Scheme world  */
{
  SCM  z;
  size_t len = strlen(str);

264
  NEWCELL(z, string);
Erick's avatar
.  
Erick committed
265 266 267
  STRING_CHARS(z)  = STk_must_malloc_atomic(len + 1);
  STRING_SPACE(z)  = STRING_SIZE(z) = len;
  STRING_LENGTH(z) = STk_use_utf8 ? STk_utf8_strlen(str, len): len;
eg's avatar
eg committed
268 269 270 271 272 273 274 275 276 277 278 279
  strcpy(STRING_CHARS(z), str);

  return z;
}


DEFINE_PRIMITIVE("string?", stringp, subr1, (SCM obj))
/*
<doc string?
 * (string? obj)
 *
 * Returns |#t| if |obj| is a string, otherwise returns |#f|.
Erick's avatar
.  
Erick committed
280
doc>
eg's avatar
eg committed
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
*/
{
  return MAKE_BOOLEAN(STRINGP(obj));
}

/*
<doc  make-string
 * (make-string k)
 * (make-string k char)
 *
 * |Make-string| returns a newly allocated string of length |k|. If |char| is
 * given, then all elements of the string are initialized to |char|, otherwise
 * the contents of the string are unspecified.
doc>
 */
DEFINE_PRIMITIVE("make-string", make_string, subr12, (SCM len, SCM init_char))
{
  long k = STk_integer_value(len);
Erick's avatar
.  
Erick committed
299

eg's avatar
eg committed
300
  if (k < 0) STk_error("bad string length: ~S", len);
Erick's avatar
.  
Erick committed
301

eg's avatar
eg committed
302
  if (init_char) {
303 304 305 306 307
    SCM z = STk_void;

    if (! CHARACTERP(init_char))
      STk_error("initializing char ~S is not valid", init_char);
    else {
308
      char *s, buff[5] = {0};
309 310 311
      int c = CHARACTER_VAL(init_char);

      if (STk_use_utf8 && c >= 0x80) {
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
        /* unicode character */
        int n = STk_char2utf8(c, buff);

        z = STk_makestring(k * n, NULL);
        s = STRING_CHARS(z);
        STRING_LENGTH(z) = k; /* incorrectly set to  k*n before */

        while (k--) {
          *s++ = buff[0];
          if (!buff[1]) continue;
          *s++ = buff[1];
          if (!buff[2]) continue;
          *s++ = buff[2];
          if (!buff[3]) continue;
          *s++ = buff[3];
        }
328
      } else {
329 330 331
        /* non unicode character */
        z = STk_makestring(k, NULL);
        s = STRING_CHARS(z);
332

333
        while (k--) *s++ = c;
334
      }
Erick's avatar
.  
Erick committed
335
    }
336
    return z;
eg's avatar
eg committed
337
  }
338 339 340
  else
    /* No initialization character */
    return STk_makestring(k, NULL);
eg's avatar
eg committed
341 342 343 344 345 346 347 348 349 350 351 352 353
}

/*
<doc  string
 * (string char ...)
 *
 * Returns a newly allocated string composed of the arguments.
doc>
 */
DEFINE_PRIMITIVE("string", string, vsubr, (int argc, SCM* argv))
{
  SCM z;
  char *s;
354 355 356 357 358 359 360 361 362 363
  int i, space;
  char buff[5];

  for (space = i = 0; i < argc; i++) {
    if (!CHARACTERP(argv[-i])) error_bad_character(argv[-i]);
    /* compute the size that must be allocated */
    if (STk_use_utf8)
      space += STk_char2utf8(CHARACTER_VAL(argv[-i]), buff);
    else
      if (CHARACTER_VAL(argv[-i]) > 255)
364
        STk_error("character ~S is too big", argv[-i]);
365
      else
366
        space += 1;
367
  }
Erick's avatar
.  
Erick committed
368

369
  z = STk_makestring(space, NULL);
370
  STRING_LENGTH(z) = argc;      /* correct the length */
Erick's avatar
.  
Erick committed
371

eg's avatar
eg committed
372
  /* copy element in newly allocated string */
373 374 375 376 377 378 379
  for (s=STRING_CHARS(z); argc--; argv--) {
    if (STk_use_utf8) {
      int n = STk_char2utf8(CHARACTER_VAL(*argv), buff);
      memcpy(s, buff, n);
      s += n;
    } else
      *s++ = CHARACTER_VAL(*argv);
eg's avatar
eg committed
380
  }
381 382
  *s = '\0';

eg's avatar
eg committed
383 384 385 386 387 388 389 390 391 392 393 394 395 396
  return z;
}


/*
<doc  string-length
 * (string-length string)
 *
 * Returns the number of characters in the given |string|.
doc>
 */
DEFINE_PRIMITIVE("string-length", string_length, subr1, (SCM str))
{
  if (!STRINGP(str)) error_bad_string(str);
397
  return MAKE_INT(STRING_LENGTH(str));
eg's avatar
eg committed
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
}


/*
<doc  string-ref
 * (string-ref string k)
 *
 * |String-ref| returns character k of string using zero-origin indexing
 * (|k| must be a valid index of string).
doc>
 */
DEFINE_PRIMITIVE("string-ref", string_ref, subr2, (SCM str, SCM index))
{
  long k = STk_integer_value(index);

413
  if (!STRINGP(str))                    error_bad_string(str);
414
  if (k < 0 || k >= STRING_LENGTH(str)) error_index_out_of_bound(str, index);
Erick's avatar
.  
Erick committed
415

416
  if (!STk_use_utf8 || (STRING_SIZE(str) == STRING_LENGTH(str)))
417 418 419 420
    /* string doesn't contain multibytes chars */
    return MAKE_CHARACTER(STRING_CHARS(str)[k]);
  else {
    /* We have multibytes chars */
421
    uint32_t c;
422 423 424 425 426 427 428
    char *s = STRING_CHARS(str);

    do
      s = STk_utf8_grab_char(s, &c);
    while (k--);
    return  MAKE_CHARACTER(c);
  }
eg's avatar
eg committed
429 430 431 432 433 434 435
}


/*
<doc  string-set!
 * (string-set! string k char)
 *
Erick's avatar
.  
Erick committed
436 437 438
 * |String-set!| stores |char| in element |k| of |string| and returns
 * ,(emph "void") (|k| must be a valid index of |string|).
 *
eg's avatar
eg committed
439 440 441 442 443
 * @lisp
 * (define (f) (make-string 3 #\*))
 * (define (g) "***")
 * (string-set! (f) 0 #\?)  =>  void
 * (string-set! (g) 0 #\?)  =>  error
Erick's avatar
.  
Erick committed
444
 * (string-set! (symbol->string 'immutable) 0 #\?)
eg's avatar
eg committed
445 446 447 448 449 450 451
 *                          =>  error
 * @end lisp
doc>
 */
DEFINE_PRIMITIVE("string-set!", string_set, subr3, (SCM str, SCM index, SCM value))
{
  long k = STk_integer_value(index);
452
  int cval;
eg's avatar
eg committed
453

454
  if (!STRINGP(str))                    error_bad_string(str);
455
  if (BOXED_INFO(str) & STRING_CONST)   error_change_const_string(str);
456
  if (!CHARACTERP(value))               error_bad_character(value);
457
  if (k < 0 || k >= STRING_LENGTH(str)) error_index_out_of_bound(str, index);
eg's avatar
eg committed
458 459


460 461
  cval = CHARACTER_VAL(value);
  if (!STk_use_utf8 || (STRING_MONOBYTE(str) &&
462
                        (STk_utf8_char_bytes_needed(cval) == 1)))
463 464 465 466 467 468 469 470 471 472 473 474 475
    /* string doesn't contain multibytes chars and value is mono byte */
    STRING_CHARS(str)[k] = cval;
  else {
    /* Multi bytes string. The following code could be better factorized */
    char buffer[5];
    char *start     = STRING_CHARS(str);
    char *pos       = STk_utf8_index(start, k, STRING_SIZE(str));
    int new_char_sz = STk_char2utf8(cval, buffer);
    int old_char_sz = STk_utf8_sequence_length(pos);

    if (old_char_sz < new_char_sz) {
      /* new character has a longer representation than the old one */
      if (STRING_LENGTH(str) + new_char_sz - old_char_sz >= STRING_SPACE(str)) {
476 477 478 479 480 481 482 483 484 485
        /* not enough space; allocate some more bytes */
        char *new = STk_must_malloc_atomic(STRING_SPACE(str) + UTF8_STRING_INCR + 1);

        memcpy(new, start, pos - start);
        memcpy(new + (pos - start), buffer, new_char_sz);
        memcpy(new + (pos - start) + new_char_sz,
               pos + old_char_sz,
               start + STRING_SIZE(str) - pos + old_char_sz);
        STRING_CHARS(str)  = new;
        STRING_SPACE(str) += UTF8_STRING_INCR;
486
      } else {
487 488 489 490
        memmove(pos + new_char_sz,
                pos + old_char_sz,
                start + STRING_SIZE(str) - pos + old_char_sz);
        memcpy(pos, buffer, new_char_sz);
491 492 493 494 495 496
      }
      STRING_SIZE(str) += new_char_sz - old_char_sz;
    }
    else if (old_char_sz > new_char_sz) {
      /* old character has a longer representation than the old one */
      memmove(pos + new_char_sz,
497 498
              pos + old_char_sz,
              start + STRING_SIZE(str) - pos + old_char_sz);
499 500 501 502 503 504 505 506 507 508
      memcpy(pos, buffer, new_char_sz);
      STRING_SIZE(str) += new_char_sz - old_char_sz;
    }
    else {
      /* characters have the same number of bytes Replace character */
      memcpy(pos, buffer, new_char_sz);
    }
    /* ensure that last character is a 0 for C compatibility */
    STRING_CHARS(str)[STRING_SIZE(str)] = '\0';
  }
eg's avatar
eg committed
509 510 511 512
  return STk_void;
}

/*
513 514 515
<doc R57RS string=? string-ci=?
 * (string=? string1 string2 ...)
 * (string-ci=? string1 string2 ...)
eg's avatar
eg committed
516
 *
517
 * Returns |#t| if all the strings are the same length and contain the same
eg's avatar
eg committed
518 519 520
 * characters in the same positions, otherwise returns |#f|. |String-ci=?|
 * treats upper and lower case letters as though they were the same character,
 * but |string=?| treats upper and lower case as distinct characters.
521
 *
522
 * ,@(bold "Note"): R5RS version of these functions accept only two arguments.
eg's avatar
eg committed
523 524 525 526
doc>
 */

/*
527 528 529 530 531 532 533 534
<doc  R57RS string<? string<=? string>? string>=? string-ci<? string-ci<=? string-ci>? string-ci>=?
 * (string<? string1 string2 ...)
 * (string>? string1 string2 ...)
 * (string<=? string1 string2 ...)
 * (string>=? string1 string2 ...)
 * (string-ci<? string1 string2 ...)
 * (string-ci>? string1 string2 ...)
 * (string-ci<=? string1 string2 ...)
eg's avatar
eg committed
535 536 537 538 539 540 541 542 543
 * (string-ci>=? string1 string2)
 *
 * These procedures are the lexicographic extensions to strings of the
 * corresponding orderings on characters. For example, |string<?| is the
 * lexicographic ordering on strings induced by the ordering |char<?| on
 * characters. If two strings differ in length but are the same up to the
 * length of the shorter string, the shorter string is considered to be
 * lexicographically less than the longer string.
 *
544
 * ,@(bold "Note"): R5RS version of these functions accept only two arguments.
eg's avatar
eg committed
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
doc>
 */

DEFINE_PRIMITIVE("string=?", streq, subr2, (SCM s1, SCM s2))
{ return MAKE_BOOLEAN(stringcomp(s1, s2) == 0); }

DEFINE_PRIMITIVE("string<?", strlt, subr2, (SCM s1, SCM s2))
{ return MAKE_BOOLEAN(stringcomp(s1, s2) < 0); }

DEFINE_PRIMITIVE("string>?", strgt, subr2, (SCM s1, SCM s2))
{ return MAKE_BOOLEAN(stringcomp(s1, s2) > 0); }

DEFINE_PRIMITIVE("string<=?", strle, subr2, (SCM s1, SCM s2))
{ return MAKE_BOOLEAN(stringcomp(s1, s2) <= 0); }

DEFINE_PRIMITIVE("string>=?", strge, subr2, (SCM s1, SCM s2))
{ return MAKE_BOOLEAN(stringcomp(s1, s2) >= 0); }



DEFINE_PRIMITIVE("string-ci=?", streqi, subr2, (SCM s1, SCM s2))
{ return MAKE_BOOLEAN(stringcompi(s1, s2) == 0); }

DEFINE_PRIMITIVE("string-ci<?", strlti, subr2, (SCM s1, SCM s2))
{ return MAKE_BOOLEAN(stringcompi(s1, s2) < 0); }

DEFINE_PRIMITIVE("string-ci>?", strgti, subr2, (SCM s1, SCM s2))
{ return MAKE_BOOLEAN(stringcompi(s1, s2) > 0); }

DEFINE_PRIMITIVE("string-ci<=?", strlei, subr2, (SCM s1, SCM s2))
{ return MAKE_BOOLEAN(stringcompi(s1, s2) <= 0); }

DEFINE_PRIMITIVE("string-ci>=?", strgei, subr2, (SCM s1, SCM s2))
{ return MAKE_BOOLEAN(stringcompi(s1, s2) >= 0); }



/*
<doc  substring
 * (substring string start end)
 *
Erick's avatar
.  
Erick committed
586
 * |String| must be a string, and |start| and |end| must be exact integers
eg's avatar
eg committed
587 588 589 590 591 592 593 594 595 596 597 598
 * satisfying
 * @lisp
 * 0 <= start <= end <= (string-length string).
 * @end lisp
 * |Substring| returns a newly allocated string formed from the characters
 * of |string| beginning with index |start| (inclusive) and ending with
 * index |end| (exclusive).
doc>
 */

DEFINE_PRIMITIVE("substring", substring, subr3, (SCM string, SCM start, SCM end))
{
599
  long from, to;
eg's avatar
eg committed
600 601 602

  if (!STRINGP(string)) error_bad_string(string);

Erick's avatar
.  
Erick committed
603
  from = STk_integer_value(start);
eg's avatar
eg committed
604 605 606 607 608
  to   = STk_integer_value(end);

  if (from == LONG_MIN) STk_error("bad lower index ~S", start);
  if (to   == LONG_MIN) STk_error("bad upper index ~S", end);

609 610 611 612 613 614 615 616 617 618 619 620
  if (0 <= from && from <= to && to <= STRING_SIZE(string)) {
    if (STRING_MONOBYTE(string))
      return STk_makestring(to - from, STRING_CHARS(string)+from);
    else {
      /* multi-bytes string */
      uint32_t c;
      char *pfrom, *pto;
      SCM z;

      pto = pfrom = STk_utf8_index(STRING_CHARS(string), from, STRING_SIZE(string));

      for ( ; from < to; from++)
621
        pto = STk_utf8_grab_char(pto, &c);
eg's avatar
eg committed
622

623 624 625 626 627
      z = STk_makestring(pto - pfrom, pfrom);
      STRING_LENGTH(z) = STk_utf8_strlen(STRING_CHARS(z), pto-pfrom);
      return z;
    }
  }
eg's avatar
eg committed
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
  STk_error("index ~S or ~S incorrect", start, end);
  return STk_void; /* cannot occur */
}

/*
<doc  string-append
 * (string-append string ...)
 *
 * Returns a newly allocated string whose characters form the concatenation
 * of the given strings.
doc>
 */
DEFINE_PRIMITIVE("string-append", string_append, vsubr, (int argc, SCM* argv))
{
  int i, total=0;
  SCM z;
  char *p;

  /* Compute total length of resulting string */
  for (i = 0; i < argc; i++) {
    p = argv[-i];
    if (!STRINGP(p)) error_bad_string(p);
    total += STRING_SIZE(p);
  }

  /* Allocate result */
  z = STk_makestring(total, NULL);
  p = STRING_CHARS(z);
Erick's avatar
.  
Erick committed
656

eg's avatar
eg committed
657
  /* copy strings */
658
  for (total=0, i=0; i < argc; i++) {
eg's avatar
eg committed
659
    memcpy(p, STRING_CHARS(*argv), (unsigned int) STRING_SIZE(*argv));
660 661 662
    p     += STRING_SIZE(*argv);
    total += STRING_LENGTH(*argv);
    argv  -=1;
eg's avatar
eg committed
663
  }
664 665
  STRING_LENGTH(z) = total;

eg's avatar
eg committed
666 667 668 669 670
  return z;
}


/*
671
<doc R57RS string->list list->string
eg's avatar
eg committed
672
 * (string->list string)
673 674
 * (string->list string start)
 * (string->list string start end)
eg's avatar
eg committed
675 676
 * (list->string list)
 *
677 678 679 680 681 682 683 684
 * |String->list| returns a newly allocated list of the characters of
 * |string| between |start| and |end|. |List->string| returns a newly
 * allocated string formed from the characters in the list |list|,
 * which must be a list of characters. |String->list| and
 * |list->string| are inverses so far as |equal?| is concerned.
 *
 * ,@("Note"): The R5RS version of |string->list| accepts only one
 * parameter.
eg's avatar
eg committed
685 686 687 688 689
doc>
 */
DEFINE_PRIMITIVE("string->list", string2list, subr1, (SCM str))
{
  register char *s;
690 691
  int len;
  uint32_t c;
eg's avatar
eg committed
692 693 694 695
  SCM tmp, tmp1, z;

  if (!STRINGP(str)) error_bad_string(str);

696
  len = STRING_LENGTH(str);
eg's avatar
eg committed
697 698 699 700 701
  s   = STRING_CHARS(str);

  tmp = z = STk_nil;

  while (len--) {
702 703
    s = STk_utf8_grab_char(s, &c);
    tmp1 = STk_cons(MAKE_CHARACTER(c), STk_nil);
eg's avatar
eg committed
704 705
    if (z == STk_nil)
      tmp = z = tmp1;
Erick's avatar
.  
Erick committed
706
    else
eg's avatar
eg committed
707 708 709 710
      tmp = CDR(tmp) = tmp1;
  }
  return z;
}
Erick's avatar
.  
Erick committed
711

eg's avatar
eg committed
712 713
DEFINE_PRIMITIVE("list->string", list2string, subr1, (SCM l))
{
714
  int bytes = 0, len = STk_int_length(l);
eg's avatar
eg committed
715
  register char *s;
716
  SCM z, tmp;
Erick's avatar
.  
Erick committed
717

eg's avatar
eg committed
718
  if (len < 0) STk_error("bad list ~S", l);
719 720 721 722 723 724 725 726

  /* compute the number of bytes needed */
  for (tmp=l; !NULLP(tmp); tmp=CDR(tmp)) {
    if (!CHARACTERP(CAR(tmp))) error_bad_character(CAR(tmp));
    bytes += STk_utf8_char_bytes_needed(CHARACTER_VAL(CAR(tmp)));
  }

  z = STk_makestring(bytes, NULL);
eg's avatar
eg committed
727 728
  s = STRING_CHARS(z);

729
  /* copy the characters in the newly allocated string */
eg's avatar
eg committed
730
  for ( ; !NULLP(l); l=CDR(l)) {
731
    s += STk_char2utf8(CHARACTER_VAL(CAR(l)), s);
eg's avatar
eg committed
732
  }
733
  *s = '\0';
eg's avatar
eg committed
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
  return z;
}


/*
<doc string-copy
 * (string-copy string)
 *
 * Returns a newly allocated copy of the given |string|.
doc>
*/
DEFINE_PRIMITIVE("string-copy", string_copy, subr1, (SCM str))
{
  if (!STRINGP(str)) error_bad_string(str);
  return STk_makestring(STRING_SIZE(str), STRING_CHARS(str));
}


/*
<doc EXT string-fill!
 * (string-fill! string char)
 *
 * Stores |char| in every element of the given |string| and returns ,(emph "void").
doc>
*/
DEFINE_PRIMITIVE("string-fill!", string_fill, subr2, (SCM str, SCM c))
{
761 762
  int bytes, len, c_char, c_len;
  char *s;
Erick's avatar
.  
Erick committed
763

764 765
  if (!STRINGP(str))                  error_bad_string(str);
  if (!CHARACTERP(c))                 error_bad_character(c);
eg's avatar
eg committed
766 767
  if (BOXED_INFO(str) & STRING_CONST) error_change_const_string(str);

768
  len    = STRING_LENGTH(str);
eg's avatar
eg committed
769 770
  s      = STRING_CHARS(str);
  c_char = CHARACTER_VAL(c);
771 772
  c_len  = STk_utf8_char_bytes_needed(c_char);
  bytes  = len * c_len;
eg's avatar
eg committed
773

774
  if (c_len == 1) {     /* unibyte character */
775 776 777
    while (len--) {
      *s++ = c_char;
    }
778
  } else {              /* multibyte character */
779 780 781 782 783 784 785 786 787 788 789 790 791
    char buffer[5];

    if (bytes > STRING_SPACE(str)) {
      STRING_CHARS(str) = s = STk_must_malloc_atomic(bytes + 1);
      STRING_SPACE(str) = bytes;
    }

    STk_char2utf8(c_char, buffer);
    while (len--) {
      memcpy(s, buffer, c_len);
      s += c_len;
    }
    *s = '\0';
eg's avatar
eg committed
792
  }
793 794

  STRING_SIZE(str) = bytes;
eg's avatar
eg committed
795 796 797 798 799
  return STk_void;
}


/*
Erick's avatar
.  
Erick committed
800
 *
eg's avatar
eg committed
801 802 803 804
 * STk bonus
 *
 */

805
static int Memmem(char *s1, int l1, char *s2, int l2, int use_utf8)
eg's avatar
eg committed
806
{
807
  int pos;
Erick's avatar
Erick committed
808
  char *start_s1 = s1;
eg's avatar
eg committed
809

810
  if (l2 == 0) return 0;
eg's avatar
eg committed
811

812 813 814 815 816 817 818
  for (pos=0; l1 >= l2 ; pos++, l1--) {
    if (memcmp(s1, s2, (unsigned int) l2) == 0) return pos;

    /* go to next character */
    if (use_utf8) {
      int len = STk_utf8_sequence_length(s1);

Erick's avatar
Erick committed
819
      if (len == UTF8_INCORRECT_SEQUENCE) error_bad_sequence(start_s1);
820 821 822 823 824 825
      s1 += len;
    } else {
      s1++;
    }
  }
  return -1; /* not found */
eg's avatar
eg committed
826 827 828 829 830 831 832 833 834 835 836
}

/*
<doc EXT string-find?
 * (string-find? str1 str2)
 *
 * Returns |#t| if |str1| appears somewhere in |str2|; otherwise returns |#f|.
doc>
*/
DEFINE_PRIMITIVE("string-find?", string_find, subr2, (SCM s1, SCM s2))
{
837 838
  int pos;

eg's avatar
eg committed
839 840
  if (!STRINGP(s1)) error_bad_string(s1);
  if (!STRINGP(s2)) error_bad_string(s2);
Erick's avatar
.  
Erick committed
841

842
  pos = Memmem(STRING_CHARS(s2), STRING_SIZE(s2),
843 844
               STRING_CHARS(s1), STRING_SIZE(s1),
               FALSE);
845 846

  return MAKE_BOOLEAN(pos != -1);
eg's avatar
eg committed
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
}

/*
<doc EXT string-index
 * (string-index str1 str2)
 *
 * Returns the (first) index where |str1| is a substring of |str2| if it exists;
 * otherwise returns |#f|.
 * @lisp
 * (string-index "ca" "abracadabra") =>  4
 * (string-index "ba" "abracadabra") =>  #f
 * @end lisp
doc>
*/
DEFINE_PRIMITIVE("string-index", string_index, subr2, (SCM s1, SCM s2))
{
863
  int pos;
eg's avatar
eg committed
864 865 866

  if (!STRINGP(s1)) error_bad_string(s1);
  if (!STRINGP(s2)) error_bad_string(s2);
Erick's avatar
.  
Erick committed
867

868
  pos = Memmem(STRING_CHARS(s2), STRING_SIZE(s2),
869 870
               STRING_CHARS(s1), STRING_SIZE(s1),
               STk_use_utf8 && !STRING_MONOBYTE(s2));
eg's avatar
eg committed
871

872
  return (pos != -1) ? STk_long2integer(pos) : STk_false;
eg's avatar
eg committed
873 874 875 876 877 878 879 880 881
}


/*
<doc EXT string-split
 * (string-split str)
 * (string-split str delimiters)
 *
 * parses |string| and returns a list of tokens ended by a character of the
Erick's avatar
.  
Erick committed
882 883
 * |delimiters| string. If |delimiters| is omitted, it defaults to a string
 * containing a space, a tabulation and a newline characters.
eg's avatar
eg committed
884
 * @lisp
Erick's avatar
.  
Erick committed
885
 * (string-split "/usr/local/bin" "/")
eg's avatar
eg committed
886
 *                        => ("usr" "local" "bin")
Erick's avatar
.  
Erick committed
887
 * (string-split "once   upon a time")
eg's avatar
eg committed
888 889 890 891 892 893 894 895 896
 *                        => ("once" "upon" "a" "time")
 * @end lisp
doc>
*/
DEFINE_PRIMITIVE("string-split", string_split, subr12, (SCM string, SCM delimiters))
{
  SCM result = STk_nil;
  char *c_string, *c_delimiters, *s;
  int i, l_string, l_delimiters;
Erick's avatar
.  
Erick committed
897

eg's avatar
eg committed
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
  if (!STRINGP(string)) error_bad_string(string);
  c_string = STRING_CHARS(string);
  l_string = STRING_SIZE(string);

  if (!delimiters) {
    c_delimiters = " \t\n";
    l_delimiters = 3;
  } else {
    if (!STRINGP(delimiters)) error_bad_string(delimiters);
    c_delimiters = STRING_CHARS(delimiters);
    l_delimiters = STRING_SIZE(delimiters);
  }

  for (s=c_string, i=0; i < l_string; s++, i++) {
    if (memchr(c_delimiters, *s, l_delimiters)) {
      if (s > c_string)
914 915
        result = STk_cons(STk_makestring(s-c_string, c_string),
                          result);
eg's avatar
eg committed
916 917 918
      c_string = s + 1;
    }
  }
Erick's avatar
.  
Erick committed
919
  if (s > c_string)
eg's avatar
eg committed
920
    result = STk_cons(STk_makestring(s-c_string, c_string),
921
                      result);
eg's avatar
eg committed
922 923 924 925 926 927 928

  return STk_dreverse(result);
}

/*
<doc EXT string-mutable?
 * (string-mutable? obj)
Erick's avatar
.  
Erick committed
929 930
 *
 * Returns |#t| if |obj| is a mutable string, otherwise returns |#f|.
eg's avatar
eg committed
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
 * @lisp
 * (string-mutable? "abc")                => #f
 * (string-mutable? (string-copy "abc"))  => #t
 * (string-mutable? (string #\a #\b #\c)) => #t
 * (string-mutable? 12)                   => #f
 * @end lisp
doc>
*/
DEFINE_PRIMITIVE("string-mutable?", string_mutable, subr1, (SCM obj))
{
  return MAKE_BOOLEAN(STRINGP(obj) && !(BOXED_INFO(obj) & STRING_CONST));
}


/*
<doc EXT string-downcase
 * (string-downcase str)
 * (string-downcase str start)
 * (string-downcase str start end)
 *
Erick's avatar
.  
Erick committed
951
 * Returns a string in which the upper case letters of string |str| between the
eg's avatar
eg committed
952 953
 * |start| and |end| indices have been replaced by their lower case equivalent.
 * If |start| is omited, it defaults to 0. If |end| is omited, it defaults to
Erick's avatar
.  
Erick committed
954
 * the length of |str|.
eg's avatar
eg committed
955 956 957 958 959
 * @lisp
 * (string-downcase "Foo BAR")        => "foo bar"
 * (string-downcase "Foo BAR" 4)      => "bar"
 * (string-downcase "Foo BAR" 4 6)    => "ba"
 * @end lisp
960
 *
961
 * ,@(bold "Note"): In R7RS, |string-downcase| accepts only one argument.
eg's avatar
eg committed
962 963
doc>
 */
964
static SCM string_xxcase(int argc, SCM *argv, int (*toxx)(int),
965
                         wint_t (*towxx)(wint_t))
eg's avatar
eg committed
966
{
967
  SCM s;
eg's avatar
eg committed
968 969
  int start, end;

970
  s = control_index(argc, argv, &start, &end);
Erick's avatar
.  
Erick committed
971

972 973 974 975 976 977
  if (STk_use_utf8 && !STRING_MONOBYTE(s)) {
    uint32_t *wchars;
    int len;
    char *startp = STk_utf8_index(STRING_CHARS(s), start, STRING_SIZE(s));

    /* collect all characters in an allocated array of int and convert it */
978
    wchars = string2int(startp, end-start, &len, towxx);
979 980 981 982 983 984 985 986

    return make_string_from_int_array(wchars, end-start, len);
  } else {
    char *endp, *p, *q;
    SCM  z =  STk_makestring(end-start, NULL);

    endp = STRING_CHARS(s) + end;
    for (p=STRING_CHARS(s)+start, q=STRING_CHARS(z); p < endp; p++, q++)
987
      *q = toxx(*p);
988 989 990

    return z;
  }
eg's avatar
eg committed
991 992
}

993 994
DEFINE_PRIMITIVE("string-downcase", string_downcase, vsubr, (int argc, SCM *argv))
{
995
  return string_xxcase(argc, argv, tolower, towlower);
996 997 998
}


eg's avatar
eg committed
999 1000 1001 1002 1003
/*
<doc EXT string-downcase!
 * (string-downcase! str)
 * (string-downcase! str start)
 * (string-downcase! str start end)
Erick's avatar
.  
Erick committed
1004 1005
 *
 * This is the in-place side-effecting variant of |string-downcase|.
eg's avatar
eg committed
1006 1007 1008 1009 1010 1011
 * @lisp
 * (string-downcase! (string-copy "Foo BAR") 4)    => "Foo bar"
 * (string-downcase! (string-copy "Foo BAR") 4 6)  => "Foo baR"
 * @end lisp
doc>
*/
1012
static SCM string_dxxcase(int argc, SCM *argv, int (*toxx)(int),
1013
                         wint_t (*towxx)(wint_t))
eg's avatar
eg committed
1014 1015
{
  SCM s;
1016
  int i, start, end;
eg's avatar
eg committed
1017 1018 1019 1020

  s    = control_index(argc, argv, &start, &end);
  if (BOXED_INFO(s) & STRING_CONST) error_change_const_string(s);

1021
  if (STk_use_utf8 && !STRING_MONOBYTE(s)) {        /* multibyte string */
1022 1023 1024 1025
    uint32_t *wchars;
    int len;
    char *startp = STk_utf8_index(STRING_CHARS(s), start, STRING_SIZE(s));
    char *endp   = STk_utf8_index(STRING_CHARS(s), end, STRING_SIZE(s));
Erick's avatar
.  
Erick committed
1026

1027
    /* collect all characters in an allocated array of int and convert it */
1028
    wchars = string2int(startp, end-start, &len, towxx);
1029 1030 1031 1032 1033
    if (len == endp-startp) {
      copy_array(wchars, end-start, startp);
    }
    else {
      /* This code is inefficient, but it seems that that the converted case
1034 1035
         character always use the same length encoding. It is likely that this
         code is never used in practice
1036 1037
      */
      for (i= start; i < end; i++)
1038
        STk_string_set(s, MAKE_INT(i), MAKE_CHARACTER(*wchars++));
1039
    }
1040
  } else {                                  /* monobyte string */
1041 1042
    char *p , *endp = STRING_CHARS(s) + end;

1043
    for (p=STRING_CHARS(s)+start; p < endp; p++) *p = toxx(*p);
1044 1045 1046
  }

  return STk_void;
eg's avatar
eg committed
1047 1048
}

1049 1050 1051 1052
DEFINE_PRIMITIVE("string-downcase!", string_ddowncase, vsubr, (int argc, SCM *argv))
{
  return string_dxxcase(argc, argv, tolower, towlower);
}
1053

eg's avatar
eg committed
1054 1055 1056 1057 1058 1059
/*
<doc EXT string-upcase
 * (string-upcase str)
 * (string-upcase str start)
 * (string-upcase str start end)
 *
1060
 * Returns a string in which the lower case letters of string |str| between the
eg's avatar
eg committed
1061 1062
 * |start| and |end| indices have been replaced by their upper case equivalent.
 * If |start| is omited, it defaults to 0. If |end| is omited, it defaults to
Erick's avatar
.  
Erick committed
1063
 * the length of |str|.
1064
 *
1065
 * ,@(bold "Note"): In R7RS, |string-upcase| accepts only one argument.
eg's avatar
eg committed
1066 1067 1068 1069
doc>
 */
DEFINE_PRIMITIVE("string-upcase", string_upcase, vsubr, (int argc, SCM *argv))
{
1070
  return string_xxcase(argc, argv, toupper, towupper);
eg's avatar
eg committed
1071 1072 1073 1074 1075 1076 1077 1078
}

/*
<doc EXT string-upcase!
 * (string-upcase! str)
 * (string-upcase! str start)
 * (string-upcase! str start end)
 *
Erick's avatar
.  
Erick committed
1079
 * This is the in-place side-effecting variant of |string-upcase|.
eg's avatar
eg committed
1080 1081 1082 1083
doc>
*/
DEFINE_PRIMITIVE("string-upcase!", string_dupcase, vsubr, (int argc, SCM *argv))
{
1084 1085
  return string_dxxcase(argc, argv, toupper, towupper);
}
eg's avatar
eg committed
1086 1087


1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
/*
<doc EXT string-foldcase
 * (string-foldcase str)
 * (string-foldcase str start)
 * (string-foldcase str start end)
 *
 * Returns a string in which the Unicode simple case-folding algorithm has
 * been applied on |str| between the |start| and |end| indices.
 * If |start| is omited, it defaults to 0. If |end| is omited, it defaults to
 * the length of |str|.
1098 1099
 *
 * ,@(bold "Note"): In R7RS, |string-foldcase| accepts only one argument.
1100 1101 1102 1103 1104 1105
doc>
 */
DEFINE_PRIMITIVE("string-foldcase", string_foldcase, vsubr, (int argc, SCM *argv))
{
  return string_xxcase(argc, argv, tolower, (wint_t (*) (wint_t))STk_casefold_char);
}
Erick's avatar
.  
Erick committed
1106

1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
/*
<doc EXT string-foldcase!
 * (string-foldcase! str)
 * (string-foldcase! str start)
 * (string-foldcase! str start end)
 *
 * This is the in-place side-effecting variant of |string-foldcase|.
doc>
*/
DEFINE_PRIMITIVE("string-foldcase!", string_dfoldcase, vsubr, (int argc, SCM *argv))
{
  return string_dxxcase(argc, argv, toupper,(wint_t (*) (wint_t))STk_casefold_char);
}
1120

eg's avatar
eg committed
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130


/*
<doc EXT string-titlecase
 * (string-titlecase str)
 * (string-titlecase str start)
 * (string-titlecase str start end)
 *
 * This function returns a string.  For every character |c| in the
 * selected range of |str|, if |c| is preceded by a cased character, it
Erick's avatar
.  
Erick committed
1131 1132
 * is downcased; otherwise it is titlecased. If |start| is omited, it
 * defaults to 0. If |end| is omited, it defaults to the length of |str|.
eg's avatar
eg committed
1133 1134 1135
 * Note that if a |start| index is specified, then the character preceding
 * |s[start]| has no effect on the titlecase decision for character |s[start]|.
 * @lisp
Erick's avatar
.  
Erick committed
1136
 * (string-titlecase "--capitalize tHIS sentence.")
eg's avatar
eg committed
1137
 *          =>  "--Capitalize This Sentence."
Erick's avatar
.  
Erick committed
1138
 * (string-titlecase "see Spot run. see Nix run.")
eg's avatar
eg committed
1139
 *          =>  "See Spot Run. See Nix Run."
Erick's avatar
.  
Erick committed
1140
 * (string-titlecase "3com makes routers.")
eg's avatar
eg committed
1141
 *          =>  "3Com Makes Routers."
Erick's avatar
.  
Erick committed
1142
 * (string-titlecase "greasy fried chicken" 2)
eg's avatar
eg committed
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
 *          => "Easy Fried Chicken"
 * @end lisp
doc>
*/
DEFINE_PRIMITIVE("string-titlecase", string_titlecase, vsubr, (int argc, SCM *argv))
{
  SCM s, z;
  int start, end;
  char *endp, *p, *q;
  char prev_is_sep = 1, curr_is_sep;

  s    = control_index(argc, argv, &start, &end);
  endp = STRING_CHARS(s) + end;
  z    = STk_makestring(end-start, NULL);

  for (p=STRING_CHARS(s)+start, q=STRING_CHARS(z); p < endp; p++, q++) {
    curr_is_sep = !(isalpha(*p));
    if (curr_is_sep)
      *q = *p;
Erick's avatar
.  
Erick committed
1162
    else
eg's avatar
eg committed
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
      *q = (prev_is_sep) ? toupper(*p) : tolower(*p);
    prev_is_sep = curr_is_sep;
  }
  return z;
}

/*
<doc EXT string-titlecase!
 * (string-titlecase! str)
 * (string-titlecase! str start)
 * (string-titlecase! str start end)
 *
Erick's avatar
.  
Erick committed
1175
 * This is the in-place side-effecting variant of |string-titlecase|.
eg's avatar
eg committed
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
doc>
*/
DEFINE_PRIMITIVE("string-titlecase!", string_dtitlecase,vsubr,(int argc, SCM *argv))
{
  SCM s;
  int start, end;
  char *endp, *p;
  char prev_is_sep = 1, curr_is_sep;

  s    = control_index(argc, argv, &start, &end);
  endp = STRING_CHARS(s) + end;

  if (BOXED_INFO(s) & STRING_CONST) error_change_const_string(s);

  for (p=STRING_CHARS(s)+start; p < endp; p++) {
    curr_is_sep = !(isalpha(*p));
    if (!curr_is_sep)
      *p = (prev_is_sep) ? toupper(*p) : tolower(*p);
    prev_is_sep = curr_is_sep;
  }
  return s;
}


/*
<doc EXT string-blit!
 * (string-blit! s1 s2 offset)
Erick's avatar
.  
Erick committed
1203 1204 1205 1206
 *
 * This function places the characters of string |s2| in the string |s1|
 * starting at position |offset|. The result of |string-blit!| may modify
 * the string |s1|. Note that the characters of |s2| can be written after
eg's avatar
eg committed
1207 1208 1209 1210 1211
 * the end of |s1| (in which case a new string is allocated).
 * @lisp
 * (string-blit! (make-string 6 #\X) "abc" 2)
 *               => "XXabcX"
 * (string-blit! (make-string 10 #\X) "abc" 5)
1212
 *               => "XXXXXabcXX"
eg's avatar
eg committed
1213 1214 1215 1216 1217 1218
 * (string-blit! (make-string 6 #\X) "a" 10)
 *               => "XXXXXX\0\0\0\0a"
 * @end lisp
doc>
*/
DEFINE_PRIMITIVE("string-blit!", string_blit, subr3,
1219
                 (SCM str1, SCM str2, SCM offset))
eg's avatar
eg committed
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
{
  long off = STk_integer_value(offset);
  int len1, len2;


  if (!STRINGP(str1))  error_bad_string(str1);
  if (!STRINGP(str2))  error_bad_string(str2);
  if (off == LONG_MIN) STk_error("bad offset ~S", offset);

  if (BOXED_INFO(str1) & STRING_CONST) error_change_const_string(str1);

  len1 = STRING_SIZE(str1);
  len2 = STRING_SIZE(str2);
Erick's avatar
.  
Erick committed
1233

eg's avatar
eg committed
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
  if ((len1 == 0) && (off == 0))
    return str2;
  else if ((off + len2) < len1) {    /* str2 can be written in str1 */
    memcpy(STRING_CHARS(str1)+off, STRING_CHARS(str2), len2);
    return str1;
  } else {    /* Size of original string changes => allocate a new string */
    int newl = (len1 >= (off + len2)) ? len1: (off + len2);
    int i, j = 0;
    SCM  new;
    char *snew, *sstr1, *sstr2;
Erick's avatar
.  
Erick committed
1244

eg's avatar
eg committed
1245 1246 1247 1248 1249 1250 1251
    new    = STk_makestring(newl, NULL);
    snew   = STRING_CHARS(new);
    sstr1  = STRING_CHARS(str1);
    sstr2  = STRING_CHARS(str2);

    for (i = 0; i < newl; i++) {
      if ((i >= off) && (i < (off + len2)))
1252
        *snew++ = sstr2[j++];
eg's avatar
eg committed
1253
      else if (i < len1)
1254
        *snew++ =  sstr1[i];
eg's avatar
eg committed
1255
      else
1256
        snew++;
eg's avatar
eg committed
1257 1258 1259 1260 1261 1262
    }
    return new;
  }
}


1263 1264 1265 1266 1267 1268
/*
DEFINE_PRIMITIVE("string-pos", string_pos, subr2, (SCM str, SCM index))
{
  long k = STk_integer_value(index);
  int n;

1269
  if (!STRINGP(str))                    error_bad_string(str);
1270 1271 1272 1273 1274 1275 1276 1277 1278
  if (k < 0 || k >= STRING_LENGTH(str)) error_index_out_of_bound(str, index);

  if (STk_use_utf8 && !STRING_MONOBYTE(str))
    return MAKE_INT(STk_utf8_index(STRING_CHARS(str), STRING_SIZE(str)));
  else
    return index;
}
*/

1279 1280 1281 1282 1283 1284

DEFINE_PRIMITIVE("%use-utf8?", using_utf8, subr0, (void))
{
  return MAKE_BOOLEAN(STk_use_utf8);
}

1285 1286 1287 1288 1289 1290 1291
DEFINE_PRIMITIVE("%string-use-utf8?", string_use_utf8, subr1, (SCM str))
{
  if (!STRINGP(str)) error_bad_string(str);

  return MAKE_BOOLEAN(STk_use_utf8 && !STRING_MONOBYTE(str));
}

1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
DEFINE_PRIMITIVE("%string->bytes", string2bytes, subr1, (SCM str))
{
  SCM z;
  int i, len;

  if (!STRINGP(str)) error_bad_string(str);

  len = STRING_SIZE(str);
  z   = STk_makevect(len, NULL);

  for (i = 0; i < len; i++)
    VECTOR_DATA(z)[i] = MAKE_INT((uint8_t) (STRING_CHARS(str)[i]));

  return z;
}

1308

eg's avatar
eg committed
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
int STk_init_string(void)
{
  ADD_PRIMITIVE(stringp);
  ADD_PRIMITIVE(make_string);
  ADD_PRIMITIVE(string);
  ADD_PRIMITIVE(string_length);
  ADD_PRIMITIVE(string_ref);
  ADD_PRIMITIVE(string_set);
  ADD_PRIMITIVE(streq);
  ADD_PRIMITIVE(strlt);
  ADD_PRIMITIVE(strgt);
  ADD_PRIMITIVE(strle);
  ADD_PRIMITIVE(strge);
  ADD_PRIMITIVE(streqi);
  ADD_PRIMITIVE(strlti);
  ADD_PRIMITIVE(strgti);
  ADD_PRIMITIVE(strlei);
  ADD_PRIMITIVE(strgei);
  ADD_PRIMITIVE(substring);
  ADD_PRIMITIVE(string_append);
  ADD_PRIMITIVE(string2list);
  ADD_PRIMITIVE(list2string);
  ADD_PRIMITIVE(string_copy);
  ADD_PRIMITIVE(string_fill);

  ADD_PRIMITIVE(string_find);
  ADD_PRIMITIVE(string_index);
  ADD_PRIMITIVE(string_split);
  ADD_PRIMITIVE(string_mutable);
  ADD_PRIMITIVE(string_downcase);
  ADD_PRIMITIVE(string_ddowncase);
  ADD_PRIMITIVE(string_upcase);
  ADD_PRIMITIVE(string_dupcase);
1342 1343
  ADD_PRIMITIVE(string_foldcase);
  ADD_PRIMITIVE(string_dfoldcase);
eg's avatar
eg committed
1344 1345 1346
  ADD_PRIMITIVE(string_titlecase);
  ADD_PRIMITIVE(string_dtitlecase);
  ADD_PRIMITIVE(string_blit);
1347

1348
  ADD_PRIMITIVE(using_utf8);
1349
  ADD_PRIMITIVE(string_use_utf8);
1350
  ADD_PRIMITIVE(string2bytes);
eg's avatar
eg committed
1351 1352
  return TRUE;
}