]> code.delx.au - gnu-emacs/blob - src/fns.c
Avoid integer overflows in string-numeric-lessp
[gnu-emacs] / src / fns.c
1 /* Random utility Lisp functions.
2
3 Copyright (C) 1985-1987, 1993-1995, 1997-2016 Free Software Foundation,
4 Inc.
5
6 This file is part of GNU Emacs.
7
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20
21 #include <config.h>
22
23 #include <unistd.h>
24 #include <intprops.h>
25 #include <vla.h>
26 #include <errno.h>
27
28 #include "lisp.h"
29 #include "character.h"
30 #include "coding.h"
31 #include "composite.h"
32 #include "buffer.h"
33 #include "intervals.h"
34 #include "window.h"
35
36 static void sort_vector_copy (Lisp_Object, ptrdiff_t,
37 Lisp_Object [restrict], Lisp_Object [restrict]);
38 static bool internal_equal (Lisp_Object, Lisp_Object, int, bool, Lisp_Object);
39
40 DEFUN ("identity", Fidentity, Sidentity, 1, 1, 0,
41 doc: /* Return the argument unchanged. */
42 attributes: const)
43 (Lisp_Object arg)
44 {
45 return arg;
46 }
47
48 DEFUN ("random", Frandom, Srandom, 0, 1, 0,
49 doc: /* Return a pseudo-random number.
50 All integers representable in Lisp, i.e. between `most-negative-fixnum'
51 and `most-positive-fixnum', inclusive, are equally likely.
52
53 With positive integer LIMIT, return random number in interval [0,LIMIT).
54 With argument t, set the random number seed from the system's entropy
55 pool if available, otherwise from less-random volatile data such as the time.
56 With a string argument, set the seed based on the string's contents.
57 Other values of LIMIT are ignored.
58
59 See Info node `(elisp)Random Numbers' for more details. */)
60 (Lisp_Object limit)
61 {
62 EMACS_INT val;
63
64 if (EQ (limit, Qt))
65 init_random ();
66 else if (STRINGP (limit))
67 seed_random (SSDATA (limit), SBYTES (limit));
68
69 val = get_random ();
70 if (INTEGERP (limit) && 0 < XINT (limit))
71 while (true)
72 {
73 /* Return the remainder, except reject the rare case where
74 get_random returns a number so close to INTMASK that the
75 remainder isn't random. */
76 EMACS_INT remainder = val % XINT (limit);
77 if (val - remainder <= INTMASK - XINT (limit) + 1)
78 return make_number (remainder);
79 val = get_random ();
80 }
81 return make_number (val);
82 }
83 \f
84 /* Heuristic on how many iterations of a tight loop can be safely done
85 before it's time to do a QUIT. This must be a power of 2. */
86 enum { QUIT_COUNT_HEURISTIC = 1 << 16 };
87
88 /* Random data-structure functions. */
89
90 static void
91 CHECK_LIST_END (Lisp_Object x, Lisp_Object y)
92 {
93 CHECK_TYPE (NILP (x), Qlistp, y);
94 }
95
96 DEFUN ("length", Flength, Slength, 1, 1, 0,
97 doc: /* Return the length of vector, list or string SEQUENCE.
98 A byte-code function object is also allowed.
99 If the string contains multibyte characters, this is not necessarily
100 the number of bytes in the string; it is the number of characters.
101 To get the number of bytes, use `string-bytes'. */)
102 (register Lisp_Object sequence)
103 {
104 register Lisp_Object val;
105
106 if (STRINGP (sequence))
107 XSETFASTINT (val, SCHARS (sequence));
108 else if (VECTORP (sequence))
109 XSETFASTINT (val, ASIZE (sequence));
110 else if (CHAR_TABLE_P (sequence))
111 XSETFASTINT (val, MAX_CHAR);
112 else if (BOOL_VECTOR_P (sequence))
113 XSETFASTINT (val, bool_vector_size (sequence));
114 else if (COMPILEDP (sequence))
115 XSETFASTINT (val, ASIZE (sequence) & PSEUDOVECTOR_SIZE_MASK);
116 else if (CONSP (sequence))
117 {
118 EMACS_INT i = 0;
119
120 do
121 {
122 ++i;
123 if ((i & (QUIT_COUNT_HEURISTIC - 1)) == 0)
124 {
125 if (MOST_POSITIVE_FIXNUM < i)
126 error ("List too long");
127 QUIT;
128 }
129 sequence = XCDR (sequence);
130 }
131 while (CONSP (sequence));
132
133 CHECK_LIST_END (sequence, sequence);
134
135 val = make_number (i);
136 }
137 else if (NILP (sequence))
138 XSETFASTINT (val, 0);
139 else
140 wrong_type_argument (Qsequencep, sequence);
141
142 return val;
143 }
144
145 DEFUN ("safe-length", Fsafe_length, Ssafe_length, 1, 1, 0,
146 doc: /* Return the length of a list, but avoid error or infinite loop.
147 This function never gets an error. If LIST is not really a list,
148 it returns 0. If LIST is circular, it returns a finite value
149 which is at least the number of distinct elements. */)
150 (Lisp_Object list)
151 {
152 Lisp_Object tail, halftail;
153 double hilen = 0;
154 uintmax_t lolen = 1;
155
156 if (! CONSP (list))
157 return make_number (0);
158
159 /* halftail is used to detect circular lists. */
160 for (tail = halftail = list; ; )
161 {
162 tail = XCDR (tail);
163 if (! CONSP (tail))
164 break;
165 if (EQ (tail, halftail))
166 break;
167 lolen++;
168 if ((lolen & 1) == 0)
169 {
170 halftail = XCDR (halftail);
171 if ((lolen & (QUIT_COUNT_HEURISTIC - 1)) == 0)
172 {
173 QUIT;
174 if (lolen == 0)
175 hilen += UINTMAX_MAX + 1.0;
176 }
177 }
178 }
179
180 /* If the length does not fit into a fixnum, return a float.
181 On all known practical machines this returns an upper bound on
182 the true length. */
183 return hilen ? make_float (hilen + lolen) : make_fixnum_or_float (lolen);
184 }
185
186 DEFUN ("string-bytes", Fstring_bytes, Sstring_bytes, 1, 1, 0,
187 doc: /* Return the number of bytes in STRING.
188 If STRING is multibyte, this may be greater than the length of STRING. */)
189 (Lisp_Object string)
190 {
191 CHECK_STRING (string);
192 return make_number (SBYTES (string));
193 }
194
195 DEFUN ("string-equal", Fstring_equal, Sstring_equal, 2, 2, 0,
196 doc: /* Return t if two strings have identical contents.
197 Case is significant, but text properties are ignored.
198 Symbols are also allowed; their print names are used instead. */)
199 (register Lisp_Object s1, Lisp_Object s2)
200 {
201 if (SYMBOLP (s1))
202 s1 = SYMBOL_NAME (s1);
203 if (SYMBOLP (s2))
204 s2 = SYMBOL_NAME (s2);
205 CHECK_STRING (s1);
206 CHECK_STRING (s2);
207
208 if (SCHARS (s1) != SCHARS (s2)
209 || SBYTES (s1) != SBYTES (s2)
210 || memcmp (SDATA (s1), SDATA (s2), SBYTES (s1)))
211 return Qnil;
212 return Qt;
213 }
214
215 DEFUN ("compare-strings", Fcompare_strings, Scompare_strings, 6, 7, 0,
216 doc: /* Compare the contents of two strings, converting to multibyte if needed.
217 The arguments START1, END1, START2, and END2, if non-nil, are
218 positions specifying which parts of STR1 or STR2 to compare. In
219 string STR1, compare the part between START1 (inclusive) and END1
220 (exclusive). If START1 is nil, it defaults to 0, the beginning of
221 the string; if END1 is nil, it defaults to the length of the string.
222 Likewise, in string STR2, compare the part between START2 and END2.
223 Like in `substring', negative values are counted from the end.
224
225 The strings are compared by the numeric values of their characters.
226 For instance, STR1 is "less than" STR2 if its first differing
227 character has a smaller numeric value. If IGNORE-CASE is non-nil,
228 characters are converted to lower-case before comparing them. Unibyte
229 strings are converted to multibyte for comparison.
230
231 The value is t if the strings (or specified portions) match.
232 If string STR1 is less, the value is a negative number N;
233 - 1 - N is the number of characters that match at the beginning.
234 If string STR1 is greater, the value is a positive number N;
235 N - 1 is the number of characters that match at the beginning. */)
236 (Lisp_Object str1, Lisp_Object start1, Lisp_Object end1, Lisp_Object str2,
237 Lisp_Object start2, Lisp_Object end2, Lisp_Object ignore_case)
238 {
239 ptrdiff_t from1, to1, from2, to2, i1, i1_byte, i2, i2_byte;
240
241 CHECK_STRING (str1);
242 CHECK_STRING (str2);
243
244 /* For backward compatibility, silently bring too-large positive end
245 values into range. */
246 if (INTEGERP (end1) && SCHARS (str1) < XINT (end1))
247 end1 = make_number (SCHARS (str1));
248 if (INTEGERP (end2) && SCHARS (str2) < XINT (end2))
249 end2 = make_number (SCHARS (str2));
250
251 validate_subarray (str1, start1, end1, SCHARS (str1), &from1, &to1);
252 validate_subarray (str2, start2, end2, SCHARS (str2), &from2, &to2);
253
254 i1 = from1;
255 i2 = from2;
256
257 i1_byte = string_char_to_byte (str1, i1);
258 i2_byte = string_char_to_byte (str2, i2);
259
260 while (i1 < to1 && i2 < to2)
261 {
262 /* When we find a mismatch, we must compare the
263 characters, not just the bytes. */
264 int c1, c2;
265
266 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c1, str1, i1, i1_byte);
267 FETCH_STRING_CHAR_AS_MULTIBYTE_ADVANCE (c2, str2, i2, i2_byte);
268
269 if (c1 == c2)
270 continue;
271
272 if (! NILP (ignore_case))
273 {
274 c1 = XINT (Fupcase (make_number (c1)));
275 c2 = XINT (Fupcase (make_number (c2)));
276 }
277
278 if (c1 == c2)
279 continue;
280
281 /* Note that I1 has already been incremented
282 past the character that we are comparing;
283 hence we don't add or subtract 1 here. */
284 if (c1 < c2)
285 return make_number (- i1 + from1);
286 else
287 return make_number (i1 - from1);
288 }
289
290 if (i1 < to1)
291 return make_number (i1 - from1 + 1);
292 if (i2 < to2)
293 return make_number (- i1 + from1 - 1);
294
295 return Qt;
296 }
297
298 DEFUN ("string-lessp", Fstring_lessp, Sstring_lessp, 2, 2, 0,
299 doc: /* Return non-nil if STRING1 is less than STRING2 in lexicographic order.
300 Case is significant.
301 Symbols are also allowed; their print names are used instead. */)
302 (register Lisp_Object string1, Lisp_Object string2)
303 {
304 register ptrdiff_t end;
305 register ptrdiff_t i1, i1_byte, i2, i2_byte;
306
307 if (SYMBOLP (string1))
308 string1 = SYMBOL_NAME (string1);
309 if (SYMBOLP (string2))
310 string2 = SYMBOL_NAME (string2);
311 CHECK_STRING (string1);
312 CHECK_STRING (string2);
313
314 i1 = i1_byte = i2 = i2_byte = 0;
315
316 end = SCHARS (string1);
317 if (end > SCHARS (string2))
318 end = SCHARS (string2);
319
320 while (i1 < end)
321 {
322 /* When we find a mismatch, we must compare the
323 characters, not just the bytes. */
324 int c1, c2;
325
326 FETCH_STRING_CHAR_ADVANCE (c1, string1, i1, i1_byte);
327 FETCH_STRING_CHAR_ADVANCE (c2, string2, i2, i2_byte);
328
329 if (c1 != c2)
330 return c1 < c2 ? Qt : Qnil;
331 }
332 return i1 < SCHARS (string2) ? Qt : Qnil;
333 }
334
335 /* Return the numerical value of a consecutive run of numerical
336 characters from STRING. The ISP and ISP_BYTE address pointer
337 pointers are increased and left at the next character after the
338 numerical characters. */
339 static size_t
340 gather_number_from_string (Lisp_Object string,
341 ptrdiff_t *isp, ptrdiff_t *isp_byte)
342 {
343 size_t number = 0;
344 char *s = SSDATA (string);
345 char *end;
346
347 errno = 0;
348 number = strtoumax (s + *isp_byte, &end, 10);
349 if (errno == ERANGE)
350 /* If we have an integer overflow, then we fall back on lexical
351 comparison. */
352 return -1;
353 else
354 {
355 size_t diff = end - (s + *isp_byte);
356 (*isp) += diff;
357 (*isp_byte) += diff;
358 return number;
359 }
360 }
361
362 DEFUN ("string-numeric-lessp", Fstring_numeric_lessp,
363 Sstring_numeric_lessp, 2, 2, 0,
364 doc: /* Return non-nil if STRING1 is less than STRING2 in 'numeric' order.
365 Sequences of non-numerical characters are compared lexicographically,
366 while sequences of numerical characters are converted into numbers,
367 and then the numbers are compared. This means that \"foo2.png\" is
368 less than \"foo12.png\" according to this predicate.
369 Case is significant.
370 Symbols are also allowed; their print names are used instead. */)
371 (register Lisp_Object string1, Lisp_Object string2)
372 {
373 ptrdiff_t end;
374 ptrdiff_t i1, i1_byte, i2, i2_byte;
375 size_t num1, num2;
376 unsigned char *chp;
377 int chlen1, chlen2;
378
379 if (SYMBOLP (string1))
380 string1 = SYMBOL_NAME (string1);
381 if (SYMBOLP (string2))
382 string2 = SYMBOL_NAME (string2);
383 CHECK_STRING (string1);
384 CHECK_STRING (string2);
385
386 i1 = i1_byte = i2 = i2_byte = 0;
387
388 end = SCHARS (string1);
389 if (end > SCHARS (string2))
390 end = SCHARS (string2);
391
392 while (i1 < end)
393 {
394 /* When we find a mismatch, we must compare the
395 characters, not just the bytes. */
396 int c1, c2;
397
398 if (STRING_MULTIBYTE (string1))
399 {
400 chp = &SDATA (string1)[i1_byte];
401 c1 = STRING_CHAR_AND_LENGTH (chp, chlen1);
402 }
403 else
404 {
405 c1 = SREF (string1, i1_byte);
406 chlen1 = 1;
407 }
408
409 if (STRING_MULTIBYTE (string2))
410 {
411 chp = &SDATA (string1)[i2_byte];
412 c2 = STRING_CHAR_AND_LENGTH (chp, chlen2);
413 }
414 else
415 {
416 c2 = SREF (string2, i2_byte);
417 chlen2 = 1;
418 }
419
420 if (c1 >= '0' && c1 <= '9' &&
421 c2 >= '0' && c2 <= '9')
422 /* Both strings are numbers, so compare them. */
423 {
424 num1 = gather_number_from_string (string1, &i1, &i1_byte);
425 num2 = gather_number_from_string (string2, &i2, &i2_byte);
426 /* If we have an integer overflow, then resort to sorting
427 the entire string lexicographically. */
428 if (num1 == -1 || num2 == -1)
429 return Fstring_lessp (string1, string2);
430 else if (num1 < num2)
431 return Qt;
432 else if (num1 > num2)
433 return Qnil;
434 }
435 else
436 {
437 if (c1 != c2)
438 return c1 < c2 ? Qt : Qnil;
439
440 i1++;
441 i2++;
442 i1_byte += chlen1;
443 i2_byte += chlen2;
444 }
445 }
446 return i1 < SCHARS (string2) ? Qt : Qnil;
447 }
448
449 DEFUN ("string-collate-lessp", Fstring_collate_lessp, Sstring_collate_lessp, 2, 4, 0,
450 doc: /* Return t if first arg string is less than second in collation order.
451 Symbols are also allowed; their print names are used instead.
452
453 This function obeys the conventions for collation order in your
454 locale settings. For example, punctuation and whitespace characters
455 might be considered less significant for sorting:
456
457 (sort \\='("11" "12" "1 1" "1 2" "1.1" "1.2") \\='string-collate-lessp)
458 => ("11" "1 1" "1.1" "12" "1 2" "1.2")
459
460 The optional argument LOCALE, a string, overrides the setting of your
461 current locale identifier for collation. The value is system
462 dependent; a LOCALE \"en_US.UTF-8\" is applicable on POSIX systems,
463 while it would be, e.g., \"enu_USA.1252\" on MS-Windows systems.
464
465 If IGNORE-CASE is non-nil, characters are converted to lower-case
466 before comparing them.
467
468 To emulate Unicode-compliant collation on MS-Windows systems,
469 bind `w32-collate-ignore-punctuation' to a non-nil value, since
470 the codeset part of the locale cannot be \"UTF-8\" on MS-Windows.
471
472 If your system does not support a locale environment, this function
473 behaves like `string-lessp'. */)
474 (Lisp_Object s1, Lisp_Object s2, Lisp_Object locale, Lisp_Object ignore_case)
475 {
476 #if defined __STDC_ISO_10646__ || defined WINDOWSNT
477 /* Check parameters. */
478 if (SYMBOLP (s1))
479 s1 = SYMBOL_NAME (s1);
480 if (SYMBOLP (s2))
481 s2 = SYMBOL_NAME (s2);
482 CHECK_STRING (s1);
483 CHECK_STRING (s2);
484 if (!NILP (locale))
485 CHECK_STRING (locale);
486
487 return (str_collate (s1, s2, locale, ignore_case) < 0) ? Qt : Qnil;
488
489 #else /* !__STDC_ISO_10646__, !WINDOWSNT */
490 return Fstring_lessp (s1, s2);
491 #endif /* !__STDC_ISO_10646__, !WINDOWSNT */
492 }
493
494 DEFUN ("string-collate-equalp", Fstring_collate_equalp, Sstring_collate_equalp, 2, 4, 0,
495 doc: /* Return t if two strings have identical contents.
496 Symbols are also allowed; their print names are used instead.
497
498 This function obeys the conventions for collation order in your locale
499 settings. For example, characters with different coding points but
500 the same meaning might be considered as equal, like different grave
501 accent Unicode characters:
502
503 (string-collate-equalp (string ?\\uFF40) (string ?\\u1FEF))
504 => t
505
506 The optional argument LOCALE, a string, overrides the setting of your
507 current locale identifier for collation. The value is system
508 dependent; a LOCALE \"en_US.UTF-8\" is applicable on POSIX systems,
509 while it would be \"enu_USA.1252\" on MS Windows systems.
510
511 If IGNORE-CASE is non-nil, characters are converted to lower-case
512 before comparing them.
513
514 To emulate Unicode-compliant collation on MS-Windows systems,
515 bind `w32-collate-ignore-punctuation' to a non-nil value, since
516 the codeset part of the locale cannot be \"UTF-8\" on MS-Windows.
517
518 If your system does not support a locale environment, this function
519 behaves like `string-equal'.
520
521 Do NOT use this function to compare file names for equality, only
522 for sorting them. */)
523 (Lisp_Object s1, Lisp_Object s2, Lisp_Object locale, Lisp_Object ignore_case)
524 {
525 #if defined __STDC_ISO_10646__ || defined WINDOWSNT
526 /* Check parameters. */
527 if (SYMBOLP (s1))
528 s1 = SYMBOL_NAME (s1);
529 if (SYMBOLP (s2))
530 s2 = SYMBOL_NAME (s2);
531 CHECK_STRING (s1);
532 CHECK_STRING (s2);
533 if (!NILP (locale))
534 CHECK_STRING (locale);
535
536 return (str_collate (s1, s2, locale, ignore_case) == 0) ? Qt : Qnil;
537
538 #else /* !__STDC_ISO_10646__, !WINDOWSNT */
539 return Fstring_equal (s1, s2);
540 #endif /* !__STDC_ISO_10646__, !WINDOWSNT */
541 }
542 \f
543 static Lisp_Object concat (ptrdiff_t nargs, Lisp_Object *args,
544 enum Lisp_Type target_type, bool last_special);
545
546 /* ARGSUSED */
547 Lisp_Object
548 concat2 (Lisp_Object s1, Lisp_Object s2)
549 {
550 return concat (2, ((Lisp_Object []) {s1, s2}), Lisp_String, 0);
551 }
552
553 /* ARGSUSED */
554 Lisp_Object
555 concat3 (Lisp_Object s1, Lisp_Object s2, Lisp_Object s3)
556 {
557 return concat (3, ((Lisp_Object []) {s1, s2, s3}), Lisp_String, 0);
558 }
559
560 DEFUN ("append", Fappend, Sappend, 0, MANY, 0,
561 doc: /* Concatenate all the arguments and make the result a list.
562 The result is a list whose elements are the elements of all the arguments.
563 Each argument may be a list, vector or string.
564 The last argument is not copied, just used as the tail of the new list.
565 usage: (append &rest SEQUENCES) */)
566 (ptrdiff_t nargs, Lisp_Object *args)
567 {
568 return concat (nargs, args, Lisp_Cons, 1);
569 }
570
571 DEFUN ("concat", Fconcat, Sconcat, 0, MANY, 0,
572 doc: /* Concatenate all the arguments and make the result a string.
573 The result is a string whose elements are the elements of all the arguments.
574 Each argument may be a string or a list or vector of characters (integers).
575 usage: (concat &rest SEQUENCES) */)
576 (ptrdiff_t nargs, Lisp_Object *args)
577 {
578 return concat (nargs, args, Lisp_String, 0);
579 }
580
581 DEFUN ("vconcat", Fvconcat, Svconcat, 0, MANY, 0,
582 doc: /* Concatenate all the arguments and make the result a vector.
583 The result is a vector whose elements are the elements of all the arguments.
584 Each argument may be a list, vector or string.
585 usage: (vconcat &rest SEQUENCES) */)
586 (ptrdiff_t nargs, Lisp_Object *args)
587 {
588 return concat (nargs, args, Lisp_Vectorlike, 0);
589 }
590
591
592 DEFUN ("copy-sequence", Fcopy_sequence, Scopy_sequence, 1, 1, 0,
593 doc: /* Return a copy of a list, vector, string or char-table.
594 The elements of a list or vector are not copied; they are shared
595 with the original. */)
596 (Lisp_Object arg)
597 {
598 if (NILP (arg)) return arg;
599
600 if (CHAR_TABLE_P (arg))
601 {
602 return copy_char_table (arg);
603 }
604
605 if (BOOL_VECTOR_P (arg))
606 {
607 EMACS_INT nbits = bool_vector_size (arg);
608 ptrdiff_t nbytes = bool_vector_bytes (nbits);
609 Lisp_Object val = make_uninit_bool_vector (nbits);
610 memcpy (bool_vector_data (val), bool_vector_data (arg), nbytes);
611 return val;
612 }
613
614 if (!CONSP (arg) && !VECTORP (arg) && !STRINGP (arg))
615 wrong_type_argument (Qsequencep, arg);
616
617 return concat (1, &arg, XTYPE (arg), 0);
618 }
619
620 /* This structure holds information of an argument of `concat' that is
621 a string and has text properties to be copied. */
622 struct textprop_rec
623 {
624 ptrdiff_t argnum; /* refer to ARGS (arguments of `concat') */
625 ptrdiff_t from; /* refer to ARGS[argnum] (argument string) */
626 ptrdiff_t to; /* refer to VAL (the target string) */
627 };
628
629 static Lisp_Object
630 concat (ptrdiff_t nargs, Lisp_Object *args,
631 enum Lisp_Type target_type, bool last_special)
632 {
633 Lisp_Object val;
634 Lisp_Object tail;
635 Lisp_Object this;
636 ptrdiff_t toindex;
637 ptrdiff_t toindex_byte = 0;
638 EMACS_INT result_len;
639 EMACS_INT result_len_byte;
640 ptrdiff_t argnum;
641 Lisp_Object last_tail;
642 Lisp_Object prev;
643 bool some_multibyte;
644 /* When we make a multibyte string, we can't copy text properties
645 while concatenating each string because the length of resulting
646 string can't be decided until we finish the whole concatenation.
647 So, we record strings that have text properties to be copied
648 here, and copy the text properties after the concatenation. */
649 struct textprop_rec *textprops = NULL;
650 /* Number of elements in textprops. */
651 ptrdiff_t num_textprops = 0;
652 USE_SAFE_ALLOCA;
653
654 tail = Qnil;
655
656 /* In append, the last arg isn't treated like the others */
657 if (last_special && nargs > 0)
658 {
659 nargs--;
660 last_tail = args[nargs];
661 }
662 else
663 last_tail = Qnil;
664
665 /* Check each argument. */
666 for (argnum = 0; argnum < nargs; argnum++)
667 {
668 this = args[argnum];
669 if (!(CONSP (this) || NILP (this) || VECTORP (this) || STRINGP (this)
670 || COMPILEDP (this) || BOOL_VECTOR_P (this)))
671 wrong_type_argument (Qsequencep, this);
672 }
673
674 /* Compute total length in chars of arguments in RESULT_LEN.
675 If desired output is a string, also compute length in bytes
676 in RESULT_LEN_BYTE, and determine in SOME_MULTIBYTE
677 whether the result should be a multibyte string. */
678 result_len_byte = 0;
679 result_len = 0;
680 some_multibyte = 0;
681 for (argnum = 0; argnum < nargs; argnum++)
682 {
683 EMACS_INT len;
684 this = args[argnum];
685 len = XFASTINT (Flength (this));
686 if (target_type == Lisp_String)
687 {
688 /* We must count the number of bytes needed in the string
689 as well as the number of characters. */
690 ptrdiff_t i;
691 Lisp_Object ch;
692 int c;
693 ptrdiff_t this_len_byte;
694
695 if (VECTORP (this) || COMPILEDP (this))
696 for (i = 0; i < len; i++)
697 {
698 ch = AREF (this, i);
699 CHECK_CHARACTER (ch);
700 c = XFASTINT (ch);
701 this_len_byte = CHAR_BYTES (c);
702 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
703 string_overflow ();
704 result_len_byte += this_len_byte;
705 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
706 some_multibyte = 1;
707 }
708 else if (BOOL_VECTOR_P (this) && bool_vector_size (this) > 0)
709 wrong_type_argument (Qintegerp, Faref (this, make_number (0)));
710 else if (CONSP (this))
711 for (; CONSP (this); this = XCDR (this))
712 {
713 ch = XCAR (this);
714 CHECK_CHARACTER (ch);
715 c = XFASTINT (ch);
716 this_len_byte = CHAR_BYTES (c);
717 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
718 string_overflow ();
719 result_len_byte += this_len_byte;
720 if (! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
721 some_multibyte = 1;
722 }
723 else if (STRINGP (this))
724 {
725 if (STRING_MULTIBYTE (this))
726 {
727 some_multibyte = 1;
728 this_len_byte = SBYTES (this);
729 }
730 else
731 this_len_byte = count_size_as_multibyte (SDATA (this),
732 SCHARS (this));
733 if (STRING_BYTES_BOUND - result_len_byte < this_len_byte)
734 string_overflow ();
735 result_len_byte += this_len_byte;
736 }
737 }
738
739 result_len += len;
740 if (MOST_POSITIVE_FIXNUM < result_len)
741 memory_full (SIZE_MAX);
742 }
743
744 if (! some_multibyte)
745 result_len_byte = result_len;
746
747 /* Create the output object. */
748 if (target_type == Lisp_Cons)
749 val = Fmake_list (make_number (result_len), Qnil);
750 else if (target_type == Lisp_Vectorlike)
751 val = Fmake_vector (make_number (result_len), Qnil);
752 else if (some_multibyte)
753 val = make_uninit_multibyte_string (result_len, result_len_byte);
754 else
755 val = make_uninit_string (result_len);
756
757 /* In `append', if all but last arg are nil, return last arg. */
758 if (target_type == Lisp_Cons && EQ (val, Qnil))
759 return last_tail;
760
761 /* Copy the contents of the args into the result. */
762 if (CONSP (val))
763 tail = val, toindex = -1; /* -1 in toindex is flag we are making a list */
764 else
765 toindex = 0, toindex_byte = 0;
766
767 prev = Qnil;
768 if (STRINGP (val))
769 SAFE_NALLOCA (textprops, 1, nargs);
770
771 for (argnum = 0; argnum < nargs; argnum++)
772 {
773 Lisp_Object thislen;
774 ptrdiff_t thisleni = 0;
775 register ptrdiff_t thisindex = 0;
776 register ptrdiff_t thisindex_byte = 0;
777
778 this = args[argnum];
779 if (!CONSP (this))
780 thislen = Flength (this), thisleni = XINT (thislen);
781
782 /* Between strings of the same kind, copy fast. */
783 if (STRINGP (this) && STRINGP (val)
784 && STRING_MULTIBYTE (this) == some_multibyte)
785 {
786 ptrdiff_t thislen_byte = SBYTES (this);
787
788 memcpy (SDATA (val) + toindex_byte, SDATA (this), SBYTES (this));
789 if (string_intervals (this))
790 {
791 textprops[num_textprops].argnum = argnum;
792 textprops[num_textprops].from = 0;
793 textprops[num_textprops++].to = toindex;
794 }
795 toindex_byte += thislen_byte;
796 toindex += thisleni;
797 }
798 /* Copy a single-byte string to a multibyte string. */
799 else if (STRINGP (this) && STRINGP (val))
800 {
801 if (string_intervals (this))
802 {
803 textprops[num_textprops].argnum = argnum;
804 textprops[num_textprops].from = 0;
805 textprops[num_textprops++].to = toindex;
806 }
807 toindex_byte += copy_text (SDATA (this),
808 SDATA (val) + toindex_byte,
809 SCHARS (this), 0, 1);
810 toindex += thisleni;
811 }
812 else
813 /* Copy element by element. */
814 while (1)
815 {
816 register Lisp_Object elt;
817
818 /* Fetch next element of `this' arg into `elt', or break if
819 `this' is exhausted. */
820 if (NILP (this)) break;
821 if (CONSP (this))
822 elt = XCAR (this), this = XCDR (this);
823 else if (thisindex >= thisleni)
824 break;
825 else if (STRINGP (this))
826 {
827 int c;
828 if (STRING_MULTIBYTE (this))
829 FETCH_STRING_CHAR_ADVANCE_NO_CHECK (c, this,
830 thisindex,
831 thisindex_byte);
832 else
833 {
834 c = SREF (this, thisindex); thisindex++;
835 if (some_multibyte && !ASCII_CHAR_P (c))
836 c = BYTE8_TO_CHAR (c);
837 }
838 XSETFASTINT (elt, c);
839 }
840 else if (BOOL_VECTOR_P (this))
841 {
842 elt = bool_vector_ref (this, thisindex);
843 thisindex++;
844 }
845 else
846 {
847 elt = AREF (this, thisindex);
848 thisindex++;
849 }
850
851 /* Store this element into the result. */
852 if (toindex < 0)
853 {
854 XSETCAR (tail, elt);
855 prev = tail;
856 tail = XCDR (tail);
857 }
858 else if (VECTORP (val))
859 {
860 ASET (val, toindex, elt);
861 toindex++;
862 }
863 else
864 {
865 int c;
866 CHECK_CHARACTER (elt);
867 c = XFASTINT (elt);
868 if (some_multibyte)
869 toindex_byte += CHAR_STRING (c, SDATA (val) + toindex_byte);
870 else
871 SSET (val, toindex_byte++, c);
872 toindex++;
873 }
874 }
875 }
876 if (!NILP (prev))
877 XSETCDR (prev, last_tail);
878
879 if (num_textprops > 0)
880 {
881 Lisp_Object props;
882 ptrdiff_t last_to_end = -1;
883
884 for (argnum = 0; argnum < num_textprops; argnum++)
885 {
886 this = args[textprops[argnum].argnum];
887 props = text_property_list (this,
888 make_number (0),
889 make_number (SCHARS (this)),
890 Qnil);
891 /* If successive arguments have properties, be sure that the
892 value of `composition' property be the copy. */
893 if (last_to_end == textprops[argnum].to)
894 make_composition_value_copy (props);
895 add_text_properties_from_list (val, props,
896 make_number (textprops[argnum].to));
897 last_to_end = textprops[argnum].to + SCHARS (this);
898 }
899 }
900
901 SAFE_FREE ();
902 return val;
903 }
904 \f
905 static Lisp_Object string_char_byte_cache_string;
906 static ptrdiff_t string_char_byte_cache_charpos;
907 static ptrdiff_t string_char_byte_cache_bytepos;
908
909 void
910 clear_string_char_byte_cache (void)
911 {
912 string_char_byte_cache_string = Qnil;
913 }
914
915 /* Return the byte index corresponding to CHAR_INDEX in STRING. */
916
917 ptrdiff_t
918 string_char_to_byte (Lisp_Object string, ptrdiff_t char_index)
919 {
920 ptrdiff_t i_byte;
921 ptrdiff_t best_below, best_below_byte;
922 ptrdiff_t best_above, best_above_byte;
923
924 best_below = best_below_byte = 0;
925 best_above = SCHARS (string);
926 best_above_byte = SBYTES (string);
927 if (best_above == best_above_byte)
928 return char_index;
929
930 if (EQ (string, string_char_byte_cache_string))
931 {
932 if (string_char_byte_cache_charpos < char_index)
933 {
934 best_below = string_char_byte_cache_charpos;
935 best_below_byte = string_char_byte_cache_bytepos;
936 }
937 else
938 {
939 best_above = string_char_byte_cache_charpos;
940 best_above_byte = string_char_byte_cache_bytepos;
941 }
942 }
943
944 if (char_index - best_below < best_above - char_index)
945 {
946 unsigned char *p = SDATA (string) + best_below_byte;
947
948 while (best_below < char_index)
949 {
950 p += BYTES_BY_CHAR_HEAD (*p);
951 best_below++;
952 }
953 i_byte = p - SDATA (string);
954 }
955 else
956 {
957 unsigned char *p = SDATA (string) + best_above_byte;
958
959 while (best_above > char_index)
960 {
961 p--;
962 while (!CHAR_HEAD_P (*p)) p--;
963 best_above--;
964 }
965 i_byte = p - SDATA (string);
966 }
967
968 string_char_byte_cache_bytepos = i_byte;
969 string_char_byte_cache_charpos = char_index;
970 string_char_byte_cache_string = string;
971
972 return i_byte;
973 }
974 \f
975 /* Return the character index corresponding to BYTE_INDEX in STRING. */
976
977 ptrdiff_t
978 string_byte_to_char (Lisp_Object string, ptrdiff_t byte_index)
979 {
980 ptrdiff_t i, i_byte;
981 ptrdiff_t best_below, best_below_byte;
982 ptrdiff_t best_above, best_above_byte;
983
984 best_below = best_below_byte = 0;
985 best_above = SCHARS (string);
986 best_above_byte = SBYTES (string);
987 if (best_above == best_above_byte)
988 return byte_index;
989
990 if (EQ (string, string_char_byte_cache_string))
991 {
992 if (string_char_byte_cache_bytepos < byte_index)
993 {
994 best_below = string_char_byte_cache_charpos;
995 best_below_byte = string_char_byte_cache_bytepos;
996 }
997 else
998 {
999 best_above = string_char_byte_cache_charpos;
1000 best_above_byte = string_char_byte_cache_bytepos;
1001 }
1002 }
1003
1004 if (byte_index - best_below_byte < best_above_byte - byte_index)
1005 {
1006 unsigned char *p = SDATA (string) + best_below_byte;
1007 unsigned char *pend = SDATA (string) + byte_index;
1008
1009 while (p < pend)
1010 {
1011 p += BYTES_BY_CHAR_HEAD (*p);
1012 best_below++;
1013 }
1014 i = best_below;
1015 i_byte = p - SDATA (string);
1016 }
1017 else
1018 {
1019 unsigned char *p = SDATA (string) + best_above_byte;
1020 unsigned char *pbeg = SDATA (string) + byte_index;
1021
1022 while (p > pbeg)
1023 {
1024 p--;
1025 while (!CHAR_HEAD_P (*p)) p--;
1026 best_above--;
1027 }
1028 i = best_above;
1029 i_byte = p - SDATA (string);
1030 }
1031
1032 string_char_byte_cache_bytepos = i_byte;
1033 string_char_byte_cache_charpos = i;
1034 string_char_byte_cache_string = string;
1035
1036 return i;
1037 }
1038 \f
1039 /* Convert STRING to a multibyte string. */
1040
1041 static Lisp_Object
1042 string_make_multibyte (Lisp_Object string)
1043 {
1044 unsigned char *buf;
1045 ptrdiff_t nbytes;
1046 Lisp_Object ret;
1047 USE_SAFE_ALLOCA;
1048
1049 if (STRING_MULTIBYTE (string))
1050 return string;
1051
1052 nbytes = count_size_as_multibyte (SDATA (string),
1053 SCHARS (string));
1054 /* If all the chars are ASCII, they won't need any more bytes
1055 once converted. In that case, we can return STRING itself. */
1056 if (nbytes == SBYTES (string))
1057 return string;
1058
1059 buf = SAFE_ALLOCA (nbytes);
1060 copy_text (SDATA (string), buf, SBYTES (string),
1061 0, 1);
1062
1063 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
1064 SAFE_FREE ();
1065
1066 return ret;
1067 }
1068
1069
1070 /* Convert STRING (if unibyte) to a multibyte string without changing
1071 the number of characters. Characters 0200 trough 0237 are
1072 converted to eight-bit characters. */
1073
1074 Lisp_Object
1075 string_to_multibyte (Lisp_Object string)
1076 {
1077 unsigned char *buf;
1078 ptrdiff_t nbytes;
1079 Lisp_Object ret;
1080 USE_SAFE_ALLOCA;
1081
1082 if (STRING_MULTIBYTE (string))
1083 return string;
1084
1085 nbytes = count_size_as_multibyte (SDATA (string), SBYTES (string));
1086 /* If all the chars are ASCII, they won't need any more bytes once
1087 converted. */
1088 if (nbytes == SBYTES (string))
1089 return make_multibyte_string (SSDATA (string), nbytes, nbytes);
1090
1091 buf = SAFE_ALLOCA (nbytes);
1092 memcpy (buf, SDATA (string), SBYTES (string));
1093 str_to_multibyte (buf, nbytes, SBYTES (string));
1094
1095 ret = make_multibyte_string ((char *) buf, SCHARS (string), nbytes);
1096 SAFE_FREE ();
1097
1098 return ret;
1099 }
1100
1101
1102 /* Convert STRING to a single-byte string. */
1103
1104 Lisp_Object
1105 string_make_unibyte (Lisp_Object string)
1106 {
1107 ptrdiff_t nchars;
1108 unsigned char *buf;
1109 Lisp_Object ret;
1110 USE_SAFE_ALLOCA;
1111
1112 if (! STRING_MULTIBYTE (string))
1113 return string;
1114
1115 nchars = SCHARS (string);
1116
1117 buf = SAFE_ALLOCA (nchars);
1118 copy_text (SDATA (string), buf, SBYTES (string),
1119 1, 0);
1120
1121 ret = make_unibyte_string ((char *) buf, nchars);
1122 SAFE_FREE ();
1123
1124 return ret;
1125 }
1126
1127 DEFUN ("string-make-multibyte", Fstring_make_multibyte, Sstring_make_multibyte,
1128 1, 1, 0,
1129 doc: /* Return the multibyte equivalent of STRING.
1130 If STRING is unibyte and contains non-ASCII characters, the function
1131 `unibyte-char-to-multibyte' is used to convert each unibyte character
1132 to a multibyte character. In this case, the returned string is a
1133 newly created string with no text properties. If STRING is multibyte
1134 or entirely ASCII, it is returned unchanged. In particular, when
1135 STRING is unibyte and entirely ASCII, the returned string is unibyte.
1136 (When the characters are all ASCII, Emacs primitives will treat the
1137 string the same way whether it is unibyte or multibyte.) */)
1138 (Lisp_Object string)
1139 {
1140 CHECK_STRING (string);
1141
1142 return string_make_multibyte (string);
1143 }
1144
1145 DEFUN ("string-make-unibyte", Fstring_make_unibyte, Sstring_make_unibyte,
1146 1, 1, 0,
1147 doc: /* Return the unibyte equivalent of STRING.
1148 Multibyte character codes are converted to unibyte according to
1149 `nonascii-translation-table' or, if that is nil, `nonascii-insert-offset'.
1150 If the lookup in the translation table fails, this function takes just
1151 the low 8 bits of each character. */)
1152 (Lisp_Object string)
1153 {
1154 CHECK_STRING (string);
1155
1156 return string_make_unibyte (string);
1157 }
1158
1159 DEFUN ("string-as-unibyte", Fstring_as_unibyte, Sstring_as_unibyte,
1160 1, 1, 0,
1161 doc: /* Return a unibyte string with the same individual bytes as STRING.
1162 If STRING is unibyte, the result is STRING itself.
1163 Otherwise it is a newly created string, with no text properties.
1164 If STRING is multibyte and contains a character of charset
1165 `eight-bit', it is converted to the corresponding single byte. */)
1166 (Lisp_Object string)
1167 {
1168 CHECK_STRING (string);
1169
1170 if (STRING_MULTIBYTE (string))
1171 {
1172 unsigned char *str = (unsigned char *) xlispstrdup (string);
1173 ptrdiff_t bytes = str_as_unibyte (str, SBYTES (string));
1174
1175 string = make_unibyte_string ((char *) str, bytes);
1176 xfree (str);
1177 }
1178 return string;
1179 }
1180
1181 DEFUN ("string-as-multibyte", Fstring_as_multibyte, Sstring_as_multibyte,
1182 1, 1, 0,
1183 doc: /* Return a multibyte string with the same individual bytes as STRING.
1184 If STRING is multibyte, the result is STRING itself.
1185 Otherwise it is a newly created string, with no text properties.
1186
1187 If STRING is unibyte and contains an individual 8-bit byte (i.e. not
1188 part of a correct utf-8 sequence), it is converted to the corresponding
1189 multibyte character of charset `eight-bit'.
1190 See also `string-to-multibyte'.
1191
1192 Beware, this often doesn't really do what you think it does.
1193 It is similar to (decode-coding-string STRING \\='utf-8-emacs).
1194 If you're not sure, whether to use `string-as-multibyte' or
1195 `string-to-multibyte', use `string-to-multibyte'. */)
1196 (Lisp_Object string)
1197 {
1198 CHECK_STRING (string);
1199
1200 if (! STRING_MULTIBYTE (string))
1201 {
1202 Lisp_Object new_string;
1203 ptrdiff_t nchars, nbytes;
1204
1205 parse_str_as_multibyte (SDATA (string),
1206 SBYTES (string),
1207 &nchars, &nbytes);
1208 new_string = make_uninit_multibyte_string (nchars, nbytes);
1209 memcpy (SDATA (new_string), SDATA (string), SBYTES (string));
1210 if (nbytes != SBYTES (string))
1211 str_as_multibyte (SDATA (new_string), nbytes,
1212 SBYTES (string), NULL);
1213 string = new_string;
1214 set_string_intervals (string, NULL);
1215 }
1216 return string;
1217 }
1218
1219 DEFUN ("string-to-multibyte", Fstring_to_multibyte, Sstring_to_multibyte,
1220 1, 1, 0,
1221 doc: /* Return a multibyte string with the same individual chars as STRING.
1222 If STRING is multibyte, the result is STRING itself.
1223 Otherwise it is a newly created string, with no text properties.
1224
1225 If STRING is unibyte and contains an 8-bit byte, it is converted to
1226 the corresponding multibyte character of charset `eight-bit'.
1227
1228 This differs from `string-as-multibyte' by converting each byte of a correct
1229 utf-8 sequence to an eight-bit character, not just bytes that don't form a
1230 correct sequence. */)
1231 (Lisp_Object string)
1232 {
1233 CHECK_STRING (string);
1234
1235 return string_to_multibyte (string);
1236 }
1237
1238 DEFUN ("string-to-unibyte", Fstring_to_unibyte, Sstring_to_unibyte,
1239 1, 1, 0,
1240 doc: /* Return a unibyte string with the same individual chars as STRING.
1241 If STRING is unibyte, the result is STRING itself.
1242 Otherwise it is a newly created string, with no text properties,
1243 where each `eight-bit' character is converted to the corresponding byte.
1244 If STRING contains a non-ASCII, non-`eight-bit' character,
1245 an error is signaled. */)
1246 (Lisp_Object string)
1247 {
1248 CHECK_STRING (string);
1249
1250 if (STRING_MULTIBYTE (string))
1251 {
1252 ptrdiff_t chars = SCHARS (string);
1253 unsigned char *str = xmalloc (chars);
1254 ptrdiff_t converted = str_to_unibyte (SDATA (string), str, chars);
1255
1256 if (converted < chars)
1257 error ("Can't convert the %"pD"dth character to unibyte", converted);
1258 string = make_unibyte_string ((char *) str, chars);
1259 xfree (str);
1260 }
1261 return string;
1262 }
1263
1264 \f
1265 DEFUN ("copy-alist", Fcopy_alist, Scopy_alist, 1, 1, 0,
1266 doc: /* Return a copy of ALIST.
1267 This is an alist which represents the same mapping from objects to objects,
1268 but does not share the alist structure with ALIST.
1269 The objects mapped (cars and cdrs of elements of the alist)
1270 are shared, however.
1271 Elements of ALIST that are not conses are also shared. */)
1272 (Lisp_Object alist)
1273 {
1274 register Lisp_Object tem;
1275
1276 CHECK_LIST (alist);
1277 if (NILP (alist))
1278 return alist;
1279 alist = concat (1, &alist, Lisp_Cons, 0);
1280 for (tem = alist; CONSP (tem); tem = XCDR (tem))
1281 {
1282 register Lisp_Object car;
1283 car = XCAR (tem);
1284
1285 if (CONSP (car))
1286 XSETCAR (tem, Fcons (XCAR (car), XCDR (car)));
1287 }
1288 return alist;
1289 }
1290
1291 /* Check that ARRAY can have a valid subarray [FROM..TO),
1292 given that its size is SIZE.
1293 If FROM is nil, use 0; if TO is nil, use SIZE.
1294 Count negative values backwards from the end.
1295 Set *IFROM and *ITO to the two indexes used. */
1296
1297 void
1298 validate_subarray (Lisp_Object array, Lisp_Object from, Lisp_Object to,
1299 ptrdiff_t size, ptrdiff_t *ifrom, ptrdiff_t *ito)
1300 {
1301 EMACS_INT f, t;
1302
1303 if (INTEGERP (from))
1304 {
1305 f = XINT (from);
1306 if (f < 0)
1307 f += size;
1308 }
1309 else if (NILP (from))
1310 f = 0;
1311 else
1312 wrong_type_argument (Qintegerp, from);
1313
1314 if (INTEGERP (to))
1315 {
1316 t = XINT (to);
1317 if (t < 0)
1318 t += size;
1319 }
1320 else if (NILP (to))
1321 t = size;
1322 else
1323 wrong_type_argument (Qintegerp, to);
1324
1325 if (! (0 <= f && f <= t && t <= size))
1326 args_out_of_range_3 (array, from, to);
1327
1328 *ifrom = f;
1329 *ito = t;
1330 }
1331
1332 DEFUN ("substring", Fsubstring, Ssubstring, 1, 3, 0,
1333 doc: /* Return a new string whose contents are a substring of STRING.
1334 The returned string consists of the characters between index FROM
1335 (inclusive) and index TO (exclusive) of STRING. FROM and TO are
1336 zero-indexed: 0 means the first character of STRING. Negative values
1337 are counted from the end of STRING. If TO is nil, the substring runs
1338 to the end of STRING.
1339
1340 The STRING argument may also be a vector. In that case, the return
1341 value is a new vector that contains the elements between index FROM
1342 (inclusive) and index TO (exclusive) of that vector argument.
1343
1344 With one argument, just copy STRING (with properties, if any). */)
1345 (Lisp_Object string, Lisp_Object from, Lisp_Object to)
1346 {
1347 Lisp_Object res;
1348 ptrdiff_t size, ifrom, ito;
1349
1350 size = CHECK_VECTOR_OR_STRING (string);
1351 validate_subarray (string, from, to, size, &ifrom, &ito);
1352
1353 if (STRINGP (string))
1354 {
1355 ptrdiff_t from_byte
1356 = !ifrom ? 0 : string_char_to_byte (string, ifrom);
1357 ptrdiff_t to_byte
1358 = ito == size ? SBYTES (string) : string_char_to_byte (string, ito);
1359 res = make_specified_string (SSDATA (string) + from_byte,
1360 ito - ifrom, to_byte - from_byte,
1361 STRING_MULTIBYTE (string));
1362 copy_text_properties (make_number (ifrom), make_number (ito),
1363 string, make_number (0), res, Qnil);
1364 }
1365 else
1366 res = Fvector (ito - ifrom, aref_addr (string, ifrom));
1367
1368 return res;
1369 }
1370
1371
1372 DEFUN ("substring-no-properties", Fsubstring_no_properties, Ssubstring_no_properties, 1, 3, 0,
1373 doc: /* Return a substring of STRING, without text properties.
1374 It starts at index FROM and ends before TO.
1375 TO may be nil or omitted; then the substring runs to the end of STRING.
1376 If FROM is nil or omitted, the substring starts at the beginning of STRING.
1377 If FROM or TO is negative, it counts from the end.
1378
1379 With one argument, just copy STRING without its properties. */)
1380 (Lisp_Object string, register Lisp_Object from, Lisp_Object to)
1381 {
1382 ptrdiff_t from_char, to_char, from_byte, to_byte, size;
1383
1384 CHECK_STRING (string);
1385
1386 size = SCHARS (string);
1387 validate_subarray (string, from, to, size, &from_char, &to_char);
1388
1389 from_byte = !from_char ? 0 : string_char_to_byte (string, from_char);
1390 to_byte =
1391 to_char == size ? SBYTES (string) : string_char_to_byte (string, to_char);
1392 return make_specified_string (SSDATA (string) + from_byte,
1393 to_char - from_char, to_byte - from_byte,
1394 STRING_MULTIBYTE (string));
1395 }
1396
1397 /* Extract a substring of STRING, giving start and end positions
1398 both in characters and in bytes. */
1399
1400 Lisp_Object
1401 substring_both (Lisp_Object string, ptrdiff_t from, ptrdiff_t from_byte,
1402 ptrdiff_t to, ptrdiff_t to_byte)
1403 {
1404 Lisp_Object res;
1405 ptrdiff_t size = CHECK_VECTOR_OR_STRING (string);
1406
1407 if (!(0 <= from && from <= to && to <= size))
1408 args_out_of_range_3 (string, make_number (from), make_number (to));
1409
1410 if (STRINGP (string))
1411 {
1412 res = make_specified_string (SSDATA (string) + from_byte,
1413 to - from, to_byte - from_byte,
1414 STRING_MULTIBYTE (string));
1415 copy_text_properties (make_number (from), make_number (to),
1416 string, make_number (0), res, Qnil);
1417 }
1418 else
1419 res = Fvector (to - from, aref_addr (string, from));
1420
1421 return res;
1422 }
1423 \f
1424 DEFUN ("nthcdr", Fnthcdr, Snthcdr, 2, 2, 0,
1425 doc: /* Take cdr N times on LIST, return the result. */)
1426 (Lisp_Object n, Lisp_Object list)
1427 {
1428 EMACS_INT i, num;
1429 CHECK_NUMBER (n);
1430 num = XINT (n);
1431 for (i = 0; i < num && !NILP (list); i++)
1432 {
1433 QUIT;
1434 CHECK_LIST_CONS (list, list);
1435 list = XCDR (list);
1436 }
1437 return list;
1438 }
1439
1440 DEFUN ("nth", Fnth, Snth, 2, 2, 0,
1441 doc: /* Return the Nth element of LIST.
1442 N counts from zero. If LIST is not that long, nil is returned. */)
1443 (Lisp_Object n, Lisp_Object list)
1444 {
1445 return Fcar (Fnthcdr (n, list));
1446 }
1447
1448 DEFUN ("elt", Felt, Selt, 2, 2, 0,
1449 doc: /* Return element of SEQUENCE at index N. */)
1450 (register Lisp_Object sequence, Lisp_Object n)
1451 {
1452 CHECK_NUMBER (n);
1453 if (CONSP (sequence) || NILP (sequence))
1454 return Fcar (Fnthcdr (n, sequence));
1455
1456 /* Faref signals a "not array" error, so check here. */
1457 CHECK_ARRAY (sequence, Qsequencep);
1458 return Faref (sequence, n);
1459 }
1460
1461 DEFUN ("member", Fmember, Smember, 2, 2, 0,
1462 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `equal'.
1463 The value is actually the tail of LIST whose car is ELT. */)
1464 (register Lisp_Object elt, Lisp_Object list)
1465 {
1466 register Lisp_Object tail;
1467 for (tail = list; !NILP (tail); tail = XCDR (tail))
1468 {
1469 register Lisp_Object tem;
1470 CHECK_LIST_CONS (tail, list);
1471 tem = XCAR (tail);
1472 if (! NILP (Fequal (elt, tem)))
1473 return tail;
1474 QUIT;
1475 }
1476 return Qnil;
1477 }
1478
1479 DEFUN ("memq", Fmemq, Smemq, 2, 2, 0,
1480 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eq'.
1481 The value is actually the tail of LIST whose car is ELT. */)
1482 (register Lisp_Object elt, Lisp_Object list)
1483 {
1484 while (1)
1485 {
1486 if (!CONSP (list) || EQ (XCAR (list), elt))
1487 break;
1488
1489 list = XCDR (list);
1490 if (!CONSP (list) || EQ (XCAR (list), elt))
1491 break;
1492
1493 list = XCDR (list);
1494 if (!CONSP (list) || EQ (XCAR (list), elt))
1495 break;
1496
1497 list = XCDR (list);
1498 QUIT;
1499 }
1500
1501 CHECK_LIST (list);
1502 return list;
1503 }
1504
1505 DEFUN ("memql", Fmemql, Smemql, 2, 2, 0,
1506 doc: /* Return non-nil if ELT is an element of LIST. Comparison done with `eql'.
1507 The value is actually the tail of LIST whose car is ELT. */)
1508 (register Lisp_Object elt, Lisp_Object list)
1509 {
1510 register Lisp_Object tail;
1511
1512 if (!FLOATP (elt))
1513 return Fmemq (elt, list);
1514
1515 for (tail = list; !NILP (tail); tail = XCDR (tail))
1516 {
1517 register Lisp_Object tem;
1518 CHECK_LIST_CONS (tail, list);
1519 tem = XCAR (tail);
1520 if (FLOATP (tem) && internal_equal (elt, tem, 0, 0, Qnil))
1521 return tail;
1522 QUIT;
1523 }
1524 return Qnil;
1525 }
1526
1527 DEFUN ("assq", Fassq, Sassq, 2, 2, 0,
1528 doc: /* Return non-nil if KEY is `eq' to the car of an element of LIST.
1529 The value is actually the first element of LIST whose car is KEY.
1530 Elements of LIST that are not conses are ignored. */)
1531 (Lisp_Object key, Lisp_Object list)
1532 {
1533 while (1)
1534 {
1535 if (!CONSP (list)
1536 || (CONSP (XCAR (list))
1537 && EQ (XCAR (XCAR (list)), key)))
1538 break;
1539
1540 list = XCDR (list);
1541 if (!CONSP (list)
1542 || (CONSP (XCAR (list))
1543 && EQ (XCAR (XCAR (list)), key)))
1544 break;
1545
1546 list = XCDR (list);
1547 if (!CONSP (list)
1548 || (CONSP (XCAR (list))
1549 && EQ (XCAR (XCAR (list)), key)))
1550 break;
1551
1552 list = XCDR (list);
1553 QUIT;
1554 }
1555
1556 return CAR (list);
1557 }
1558
1559 /* Like Fassq but never report an error and do not allow quits.
1560 Use only on lists known never to be circular. */
1561
1562 Lisp_Object
1563 assq_no_quit (Lisp_Object key, Lisp_Object list)
1564 {
1565 while (CONSP (list)
1566 && (!CONSP (XCAR (list))
1567 || !EQ (XCAR (XCAR (list)), key)))
1568 list = XCDR (list);
1569
1570 return CAR_SAFE (list);
1571 }
1572
1573 DEFUN ("assoc", Fassoc, Sassoc, 2, 2, 0,
1574 doc: /* Return non-nil if KEY is `equal' to the car of an element of LIST.
1575 The value is actually the first element of LIST whose car equals KEY. */)
1576 (Lisp_Object key, Lisp_Object list)
1577 {
1578 Lisp_Object car;
1579
1580 while (1)
1581 {
1582 if (!CONSP (list)
1583 || (CONSP (XCAR (list))
1584 && (car = XCAR (XCAR (list)),
1585 EQ (car, key) || !NILP (Fequal (car, key)))))
1586 break;
1587
1588 list = XCDR (list);
1589 if (!CONSP (list)
1590 || (CONSP (XCAR (list))
1591 && (car = XCAR (XCAR (list)),
1592 EQ (car, key) || !NILP (Fequal (car, key)))))
1593 break;
1594
1595 list = XCDR (list);
1596 if (!CONSP (list)
1597 || (CONSP (XCAR (list))
1598 && (car = XCAR (XCAR (list)),
1599 EQ (car, key) || !NILP (Fequal (car, key)))))
1600 break;
1601
1602 list = XCDR (list);
1603 QUIT;
1604 }
1605
1606 return CAR (list);
1607 }
1608
1609 /* Like Fassoc but never report an error and do not allow quits.
1610 Use only on lists known never to be circular. */
1611
1612 Lisp_Object
1613 assoc_no_quit (Lisp_Object key, Lisp_Object list)
1614 {
1615 while (CONSP (list)
1616 && (!CONSP (XCAR (list))
1617 || (!EQ (XCAR (XCAR (list)), key)
1618 && NILP (Fequal (XCAR (XCAR (list)), key)))))
1619 list = XCDR (list);
1620
1621 return CONSP (list) ? XCAR (list) : Qnil;
1622 }
1623
1624 DEFUN ("rassq", Frassq, Srassq, 2, 2, 0,
1625 doc: /* Return non-nil if KEY is `eq' to the cdr of an element of LIST.
1626 The value is actually the first element of LIST whose cdr is KEY. */)
1627 (register Lisp_Object key, Lisp_Object list)
1628 {
1629 while (1)
1630 {
1631 if (!CONSP (list)
1632 || (CONSP (XCAR (list))
1633 && EQ (XCDR (XCAR (list)), key)))
1634 break;
1635
1636 list = XCDR (list);
1637 if (!CONSP (list)
1638 || (CONSP (XCAR (list))
1639 && EQ (XCDR (XCAR (list)), key)))
1640 break;
1641
1642 list = XCDR (list);
1643 if (!CONSP (list)
1644 || (CONSP (XCAR (list))
1645 && EQ (XCDR (XCAR (list)), key)))
1646 break;
1647
1648 list = XCDR (list);
1649 QUIT;
1650 }
1651
1652 return CAR (list);
1653 }
1654
1655 DEFUN ("rassoc", Frassoc, Srassoc, 2, 2, 0,
1656 doc: /* Return non-nil if KEY is `equal' to the cdr of an element of LIST.
1657 The value is actually the first element of LIST whose cdr equals KEY. */)
1658 (Lisp_Object key, Lisp_Object list)
1659 {
1660 Lisp_Object cdr;
1661
1662 while (1)
1663 {
1664 if (!CONSP (list)
1665 || (CONSP (XCAR (list))
1666 && (cdr = XCDR (XCAR (list)),
1667 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1668 break;
1669
1670 list = XCDR (list);
1671 if (!CONSP (list)
1672 || (CONSP (XCAR (list))
1673 && (cdr = XCDR (XCAR (list)),
1674 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1675 break;
1676
1677 list = XCDR (list);
1678 if (!CONSP (list)
1679 || (CONSP (XCAR (list))
1680 && (cdr = XCDR (XCAR (list)),
1681 EQ (cdr, key) || !NILP (Fequal (cdr, key)))))
1682 break;
1683
1684 list = XCDR (list);
1685 QUIT;
1686 }
1687
1688 return CAR (list);
1689 }
1690 \f
1691 DEFUN ("delq", Fdelq, Sdelq, 2, 2, 0,
1692 doc: /* Delete members of LIST which are `eq' to ELT, and return the result.
1693 More precisely, this function skips any members `eq' to ELT at the
1694 front of LIST, then removes members `eq' to ELT from the remaining
1695 sublist by modifying its list structure, then returns the resulting
1696 list.
1697
1698 Write `(setq foo (delq element foo))' to be sure of correctly changing
1699 the value of a list `foo'. See also `remq', which does not modify the
1700 argument. */)
1701 (register Lisp_Object elt, Lisp_Object list)
1702 {
1703 Lisp_Object tail, tortoise, prev = Qnil;
1704 bool skip;
1705
1706 FOR_EACH_TAIL (tail, list, tortoise, skip)
1707 {
1708 Lisp_Object tem = XCAR (tail);
1709 if (EQ (elt, tem))
1710 {
1711 if (NILP (prev))
1712 list = XCDR (tail);
1713 else
1714 Fsetcdr (prev, XCDR (tail));
1715 }
1716 else
1717 prev = tail;
1718 }
1719 return list;
1720 }
1721
1722 DEFUN ("delete", Fdelete, Sdelete, 2, 2, 0,
1723 doc: /* Delete members of SEQ which are `equal' to ELT, and return the result.
1724 SEQ must be a sequence (i.e. a list, a vector, or a string).
1725 The return value is a sequence of the same type.
1726
1727 If SEQ is a list, this behaves like `delq', except that it compares
1728 with `equal' instead of `eq'. In particular, it may remove elements
1729 by altering the list structure.
1730
1731 If SEQ is not a list, deletion is never performed destructively;
1732 instead this function creates and returns a new vector or string.
1733
1734 Write `(setq foo (delete element foo))' to be sure of correctly
1735 changing the value of a sequence `foo'. */)
1736 (Lisp_Object elt, Lisp_Object seq)
1737 {
1738 if (VECTORP (seq))
1739 {
1740 ptrdiff_t i, n;
1741
1742 for (i = n = 0; i < ASIZE (seq); ++i)
1743 if (NILP (Fequal (AREF (seq, i), elt)))
1744 ++n;
1745
1746 if (n != ASIZE (seq))
1747 {
1748 struct Lisp_Vector *p = allocate_vector (n);
1749
1750 for (i = n = 0; i < ASIZE (seq); ++i)
1751 if (NILP (Fequal (AREF (seq, i), elt)))
1752 p->contents[n++] = AREF (seq, i);
1753
1754 XSETVECTOR (seq, p);
1755 }
1756 }
1757 else if (STRINGP (seq))
1758 {
1759 ptrdiff_t i, ibyte, nchars, nbytes, cbytes;
1760 int c;
1761
1762 for (i = nchars = nbytes = ibyte = 0;
1763 i < SCHARS (seq);
1764 ++i, ibyte += cbytes)
1765 {
1766 if (STRING_MULTIBYTE (seq))
1767 {
1768 c = STRING_CHAR (SDATA (seq) + ibyte);
1769 cbytes = CHAR_BYTES (c);
1770 }
1771 else
1772 {
1773 c = SREF (seq, i);
1774 cbytes = 1;
1775 }
1776
1777 if (!INTEGERP (elt) || c != XINT (elt))
1778 {
1779 ++nchars;
1780 nbytes += cbytes;
1781 }
1782 }
1783
1784 if (nchars != SCHARS (seq))
1785 {
1786 Lisp_Object tem;
1787
1788 tem = make_uninit_multibyte_string (nchars, nbytes);
1789 if (!STRING_MULTIBYTE (seq))
1790 STRING_SET_UNIBYTE (tem);
1791
1792 for (i = nchars = nbytes = ibyte = 0;
1793 i < SCHARS (seq);
1794 ++i, ibyte += cbytes)
1795 {
1796 if (STRING_MULTIBYTE (seq))
1797 {
1798 c = STRING_CHAR (SDATA (seq) + ibyte);
1799 cbytes = CHAR_BYTES (c);
1800 }
1801 else
1802 {
1803 c = SREF (seq, i);
1804 cbytes = 1;
1805 }
1806
1807 if (!INTEGERP (elt) || c != XINT (elt))
1808 {
1809 unsigned char *from = SDATA (seq) + ibyte;
1810 unsigned char *to = SDATA (tem) + nbytes;
1811 ptrdiff_t n;
1812
1813 ++nchars;
1814 nbytes += cbytes;
1815
1816 for (n = cbytes; n--; )
1817 *to++ = *from++;
1818 }
1819 }
1820
1821 seq = tem;
1822 }
1823 }
1824 else
1825 {
1826 Lisp_Object tail, prev;
1827
1828 for (tail = seq, prev = Qnil; !NILP (tail); tail = XCDR (tail))
1829 {
1830 CHECK_LIST_CONS (tail, seq);
1831
1832 if (!NILP (Fequal (elt, XCAR (tail))))
1833 {
1834 if (NILP (prev))
1835 seq = XCDR (tail);
1836 else
1837 Fsetcdr (prev, XCDR (tail));
1838 }
1839 else
1840 prev = tail;
1841 QUIT;
1842 }
1843 }
1844
1845 return seq;
1846 }
1847
1848 DEFUN ("nreverse", Fnreverse, Snreverse, 1, 1, 0,
1849 doc: /* Reverse order of items in a list, vector or string SEQ.
1850 If SEQ is a list, it should be nil-terminated.
1851 This function may destructively modify SEQ to produce the value. */)
1852 (Lisp_Object seq)
1853 {
1854 if (NILP (seq))
1855 return seq;
1856 else if (STRINGP (seq))
1857 return Freverse (seq);
1858 else if (CONSP (seq))
1859 {
1860 Lisp_Object prev, tail, next;
1861
1862 for (prev = Qnil, tail = seq; !NILP (tail); tail = next)
1863 {
1864 QUIT;
1865 CHECK_LIST_CONS (tail, tail);
1866 next = XCDR (tail);
1867 Fsetcdr (tail, prev);
1868 prev = tail;
1869 }
1870 seq = prev;
1871 }
1872 else if (VECTORP (seq))
1873 {
1874 ptrdiff_t i, size = ASIZE (seq);
1875
1876 for (i = 0; i < size / 2; i++)
1877 {
1878 Lisp_Object tem = AREF (seq, i);
1879 ASET (seq, i, AREF (seq, size - i - 1));
1880 ASET (seq, size - i - 1, tem);
1881 }
1882 }
1883 else if (BOOL_VECTOR_P (seq))
1884 {
1885 ptrdiff_t i, size = bool_vector_size (seq);
1886
1887 for (i = 0; i < size / 2; i++)
1888 {
1889 bool tem = bool_vector_bitref (seq, i);
1890 bool_vector_set (seq, i, bool_vector_bitref (seq, size - i - 1));
1891 bool_vector_set (seq, size - i - 1, tem);
1892 }
1893 }
1894 else
1895 wrong_type_argument (Qarrayp, seq);
1896 return seq;
1897 }
1898
1899 DEFUN ("reverse", Freverse, Sreverse, 1, 1, 0,
1900 doc: /* Return the reversed copy of list, vector, or string SEQ.
1901 See also the function `nreverse', which is used more often. */)
1902 (Lisp_Object seq)
1903 {
1904 Lisp_Object new;
1905
1906 if (NILP (seq))
1907 return Qnil;
1908 else if (CONSP (seq))
1909 {
1910 for (new = Qnil; CONSP (seq); seq = XCDR (seq))
1911 {
1912 QUIT;
1913 new = Fcons (XCAR (seq), new);
1914 }
1915 CHECK_LIST_END (seq, seq);
1916 }
1917 else if (VECTORP (seq))
1918 {
1919 ptrdiff_t i, size = ASIZE (seq);
1920
1921 new = make_uninit_vector (size);
1922 for (i = 0; i < size; i++)
1923 ASET (new, i, AREF (seq, size - i - 1));
1924 }
1925 else if (BOOL_VECTOR_P (seq))
1926 {
1927 ptrdiff_t i;
1928 EMACS_INT nbits = bool_vector_size (seq);
1929
1930 new = make_uninit_bool_vector (nbits);
1931 for (i = 0; i < nbits; i++)
1932 bool_vector_set (new, i, bool_vector_bitref (seq, nbits - i - 1));
1933 }
1934 else if (STRINGP (seq))
1935 {
1936 ptrdiff_t size = SCHARS (seq), bytes = SBYTES (seq);
1937
1938 if (size == bytes)
1939 {
1940 ptrdiff_t i;
1941
1942 new = make_uninit_string (size);
1943 for (i = 0; i < size; i++)
1944 SSET (new, i, SREF (seq, size - i - 1));
1945 }
1946 else
1947 {
1948 unsigned char *p, *q;
1949
1950 new = make_uninit_multibyte_string (size, bytes);
1951 p = SDATA (seq), q = SDATA (new) + bytes;
1952 while (q > SDATA (new))
1953 {
1954 int ch, len;
1955
1956 ch = STRING_CHAR_AND_LENGTH (p, len);
1957 p += len, q -= len;
1958 CHAR_STRING (ch, q);
1959 }
1960 }
1961 }
1962 else
1963 wrong_type_argument (Qsequencep, seq);
1964 return new;
1965 }
1966
1967 /* Sort LIST using PREDICATE, preserving original order of elements
1968 considered as equal. */
1969
1970 static Lisp_Object
1971 sort_list (Lisp_Object list, Lisp_Object predicate)
1972 {
1973 Lisp_Object front, back;
1974 Lisp_Object len, tem;
1975 EMACS_INT length;
1976
1977 front = list;
1978 len = Flength (list);
1979 length = XINT (len);
1980 if (length < 2)
1981 return list;
1982
1983 XSETINT (len, (length / 2) - 1);
1984 tem = Fnthcdr (len, list);
1985 back = Fcdr (tem);
1986 Fsetcdr (tem, Qnil);
1987
1988 front = Fsort (front, predicate);
1989 back = Fsort (back, predicate);
1990 return merge (front, back, predicate);
1991 }
1992
1993 /* Using PRED to compare, return whether A and B are in order.
1994 Compare stably when A appeared before B in the input. */
1995 static bool
1996 inorder (Lisp_Object pred, Lisp_Object a, Lisp_Object b)
1997 {
1998 return NILP (call2 (pred, b, a));
1999 }
2000
2001 /* Using PRED to compare, merge from ALEN-length A and BLEN-length B
2002 into DEST. Argument arrays must be nonempty and must not overlap,
2003 except that B might be the last part of DEST. */
2004 static void
2005 merge_vectors (Lisp_Object pred,
2006 ptrdiff_t alen, Lisp_Object const a[restrict VLA_ELEMS (alen)],
2007 ptrdiff_t blen, Lisp_Object const b[VLA_ELEMS (blen)],
2008 Lisp_Object dest[VLA_ELEMS (alen + blen)])
2009 {
2010 eassume (0 < alen && 0 < blen);
2011 Lisp_Object const *alim = a + alen;
2012 Lisp_Object const *blim = b + blen;
2013
2014 while (true)
2015 {
2016 if (inorder (pred, a[0], b[0]))
2017 {
2018 *dest++ = *a++;
2019 if (a == alim)
2020 {
2021 if (dest != b)
2022 memcpy (dest, b, (blim - b) * sizeof *dest);
2023 return;
2024 }
2025 }
2026 else
2027 {
2028 *dest++ = *b++;
2029 if (b == blim)
2030 {
2031 memcpy (dest, a, (alim - a) * sizeof *dest);
2032 return;
2033 }
2034 }
2035 }
2036 }
2037
2038 /* Using PRED to compare, sort LEN-length VEC in place, using TMP for
2039 temporary storage. LEN must be at least 2. */
2040 static void
2041 sort_vector_inplace (Lisp_Object pred, ptrdiff_t len,
2042 Lisp_Object vec[restrict VLA_ELEMS (len)],
2043 Lisp_Object tmp[restrict VLA_ELEMS (len >> 1)])
2044 {
2045 eassume (2 <= len);
2046 ptrdiff_t halflen = len >> 1;
2047 sort_vector_copy (pred, halflen, vec, tmp);
2048 if (1 < len - halflen)
2049 sort_vector_inplace (pred, len - halflen, vec + halflen, vec);
2050 merge_vectors (pred, halflen, tmp, len - halflen, vec + halflen, vec);
2051 }
2052
2053 /* Using PRED to compare, sort from LEN-length SRC into DST.
2054 Len must be positive. */
2055 static void
2056 sort_vector_copy (Lisp_Object pred, ptrdiff_t len,
2057 Lisp_Object src[restrict VLA_ELEMS (len)],
2058 Lisp_Object dest[restrict VLA_ELEMS (len)])
2059 {
2060 eassume (0 < len);
2061 ptrdiff_t halflen = len >> 1;
2062 if (halflen < 1)
2063 dest[0] = src[0];
2064 else
2065 {
2066 if (1 < halflen)
2067 sort_vector_inplace (pred, halflen, src, dest);
2068 if (1 < len - halflen)
2069 sort_vector_inplace (pred, len - halflen, src + halflen, dest);
2070 merge_vectors (pred, halflen, src, len - halflen, src + halflen, dest);
2071 }
2072 }
2073
2074 /* Sort VECTOR in place using PREDICATE, preserving original order of
2075 elements considered as equal. */
2076
2077 static void
2078 sort_vector (Lisp_Object vector, Lisp_Object predicate)
2079 {
2080 ptrdiff_t len = ASIZE (vector);
2081 if (len < 2)
2082 return;
2083 ptrdiff_t halflen = len >> 1;
2084 Lisp_Object *tmp;
2085 USE_SAFE_ALLOCA;
2086 SAFE_ALLOCA_LISP (tmp, halflen);
2087 for (ptrdiff_t i = 0; i < halflen; i++)
2088 tmp[i] = make_number (0);
2089 sort_vector_inplace (predicate, len, XVECTOR (vector)->contents, tmp);
2090 SAFE_FREE ();
2091 }
2092
2093 DEFUN ("sort", Fsort, Ssort, 2, 2, 0,
2094 doc: /* Sort SEQ, stably, comparing elements using PREDICATE.
2095 Returns the sorted sequence. SEQ should be a list or vector. SEQ is
2096 modified by side effects. PREDICATE is called with two elements of
2097 SEQ, and should return non-nil if the first element should sort before
2098 the second. */)
2099 (Lisp_Object seq, Lisp_Object predicate)
2100 {
2101 if (CONSP (seq))
2102 seq = sort_list (seq, predicate);
2103 else if (VECTORP (seq))
2104 sort_vector (seq, predicate);
2105 else if (!NILP (seq))
2106 wrong_type_argument (Qsequencep, seq);
2107 return seq;
2108 }
2109
2110 Lisp_Object
2111 merge (Lisp_Object org_l1, Lisp_Object org_l2, Lisp_Object pred)
2112 {
2113 Lisp_Object l1 = org_l1;
2114 Lisp_Object l2 = org_l2;
2115 Lisp_Object tail = Qnil;
2116 Lisp_Object value = Qnil;
2117
2118 while (1)
2119 {
2120 if (NILP (l1))
2121 {
2122 if (NILP (tail))
2123 return l2;
2124 Fsetcdr (tail, l2);
2125 return value;
2126 }
2127 if (NILP (l2))
2128 {
2129 if (NILP (tail))
2130 return l1;
2131 Fsetcdr (tail, l1);
2132 return value;
2133 }
2134
2135 Lisp_Object tem;
2136 if (inorder (pred, Fcar (l1), Fcar (l2)))
2137 {
2138 tem = l1;
2139 l1 = Fcdr (l1);
2140 org_l1 = l1;
2141 }
2142 else
2143 {
2144 tem = l2;
2145 l2 = Fcdr (l2);
2146 org_l2 = l2;
2147 }
2148 if (NILP (tail))
2149 value = tem;
2150 else
2151 Fsetcdr (tail, tem);
2152 tail = tem;
2153 }
2154 }
2155
2156 \f
2157 /* This does not check for quits. That is safe since it must terminate. */
2158
2159 DEFUN ("plist-get", Fplist_get, Splist_get, 2, 2, 0,
2160 doc: /* Extract a value from a property list.
2161 PLIST is a property list, which is a list of the form
2162 (PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
2163 corresponding to the given PROP, or nil if PROP is not one of the
2164 properties on the list. This function never signals an error. */)
2165 (Lisp_Object plist, Lisp_Object prop)
2166 {
2167 Lisp_Object tail, halftail;
2168
2169 /* halftail is used to detect circular lists. */
2170 tail = halftail = plist;
2171 while (CONSP (tail) && CONSP (XCDR (tail)))
2172 {
2173 if (EQ (prop, XCAR (tail)))
2174 return XCAR (XCDR (tail));
2175
2176 tail = XCDR (XCDR (tail));
2177 halftail = XCDR (halftail);
2178 if (EQ (tail, halftail))
2179 break;
2180 }
2181
2182 return Qnil;
2183 }
2184
2185 DEFUN ("get", Fget, Sget, 2, 2, 0,
2186 doc: /* Return the value of SYMBOL's PROPNAME property.
2187 This is the last value stored with `(put SYMBOL PROPNAME VALUE)'. */)
2188 (Lisp_Object symbol, Lisp_Object propname)
2189 {
2190 CHECK_SYMBOL (symbol);
2191 return Fplist_get (XSYMBOL (symbol)->plist, propname);
2192 }
2193
2194 DEFUN ("plist-put", Fplist_put, Splist_put, 3, 3, 0,
2195 doc: /* Change value in PLIST of PROP to VAL.
2196 PLIST is a property list, which is a list of the form
2197 (PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol and VAL is any object.
2198 If PROP is already a property on the list, its value is set to VAL,
2199 otherwise the new PROP VAL pair is added. The new plist is returned;
2200 use `(setq x (plist-put x prop val))' to be sure to use the new value.
2201 The PLIST is modified by side effects. */)
2202 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
2203 {
2204 register Lisp_Object tail, prev;
2205 Lisp_Object newcell;
2206 prev = Qnil;
2207 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
2208 tail = XCDR (XCDR (tail)))
2209 {
2210 if (EQ (prop, XCAR (tail)))
2211 {
2212 Fsetcar (XCDR (tail), val);
2213 return plist;
2214 }
2215
2216 prev = tail;
2217 QUIT;
2218 }
2219 newcell = Fcons (prop, Fcons (val, NILP (prev) ? plist : XCDR (XCDR (prev))));
2220 if (NILP (prev))
2221 return newcell;
2222 else
2223 Fsetcdr (XCDR (prev), newcell);
2224 return plist;
2225 }
2226
2227 DEFUN ("put", Fput, Sput, 3, 3, 0,
2228 doc: /* Store SYMBOL's PROPNAME property with value VALUE.
2229 It can be retrieved with `(get SYMBOL PROPNAME)'. */)
2230 (Lisp_Object symbol, Lisp_Object propname, Lisp_Object value)
2231 {
2232 CHECK_SYMBOL (symbol);
2233 set_symbol_plist
2234 (symbol, Fplist_put (XSYMBOL (symbol)->plist, propname, value));
2235 return value;
2236 }
2237 \f
2238 DEFUN ("lax-plist-get", Flax_plist_get, Slax_plist_get, 2, 2, 0,
2239 doc: /* Extract a value from a property list, comparing with `equal'.
2240 PLIST is a property list, which is a list of the form
2241 (PROP1 VALUE1 PROP2 VALUE2...). This function returns the value
2242 corresponding to the given PROP, or nil if PROP is not
2243 one of the properties on the list. */)
2244 (Lisp_Object plist, Lisp_Object prop)
2245 {
2246 Lisp_Object tail;
2247
2248 for (tail = plist;
2249 CONSP (tail) && CONSP (XCDR (tail));
2250 tail = XCDR (XCDR (tail)))
2251 {
2252 if (! NILP (Fequal (prop, XCAR (tail))))
2253 return XCAR (XCDR (tail));
2254
2255 QUIT;
2256 }
2257
2258 CHECK_LIST_END (tail, prop);
2259
2260 return Qnil;
2261 }
2262
2263 DEFUN ("lax-plist-put", Flax_plist_put, Slax_plist_put, 3, 3, 0,
2264 doc: /* Change value in PLIST of PROP to VAL, comparing with `equal'.
2265 PLIST is a property list, which is a list of the form
2266 (PROP1 VALUE1 PROP2 VALUE2 ...). PROP and VAL are any objects.
2267 If PROP is already a property on the list, its value is set to VAL,
2268 otherwise the new PROP VAL pair is added. The new plist is returned;
2269 use `(setq x (lax-plist-put x prop val))' to be sure to use the new value.
2270 The PLIST is modified by side effects. */)
2271 (Lisp_Object plist, register Lisp_Object prop, Lisp_Object val)
2272 {
2273 register Lisp_Object tail, prev;
2274 Lisp_Object newcell;
2275 prev = Qnil;
2276 for (tail = plist; CONSP (tail) && CONSP (XCDR (tail));
2277 tail = XCDR (XCDR (tail)))
2278 {
2279 if (! NILP (Fequal (prop, XCAR (tail))))
2280 {
2281 Fsetcar (XCDR (tail), val);
2282 return plist;
2283 }
2284
2285 prev = tail;
2286 QUIT;
2287 }
2288 newcell = list2 (prop, val);
2289 if (NILP (prev))
2290 return newcell;
2291 else
2292 Fsetcdr (XCDR (prev), newcell);
2293 return plist;
2294 }
2295 \f
2296 DEFUN ("eql", Feql, Seql, 2, 2, 0,
2297 doc: /* Return t if the two args are the same Lisp object.
2298 Floating-point numbers of equal value are `eql', but they may not be `eq'. */)
2299 (Lisp_Object obj1, Lisp_Object obj2)
2300 {
2301 if (FLOATP (obj1))
2302 return internal_equal (obj1, obj2, 0, 0, Qnil) ? Qt : Qnil;
2303 else
2304 return EQ (obj1, obj2) ? Qt : Qnil;
2305 }
2306
2307 DEFUN ("equal", Fequal, Sequal, 2, 2, 0,
2308 doc: /* Return t if two Lisp objects have similar structure and contents.
2309 They must have the same data type.
2310 Conses are compared by comparing the cars and the cdrs.
2311 Vectors and strings are compared element by element.
2312 Numbers are compared by value, but integers cannot equal floats.
2313 (Use `=' if you want integers and floats to be able to be equal.)
2314 Symbols must match exactly. */)
2315 (register Lisp_Object o1, Lisp_Object o2)
2316 {
2317 return internal_equal (o1, o2, 0, 0, Qnil) ? Qt : Qnil;
2318 }
2319
2320 DEFUN ("equal-including-properties", Fequal_including_properties, Sequal_including_properties, 2, 2, 0,
2321 doc: /* Return t if two Lisp objects have similar structure and contents.
2322 This is like `equal' except that it compares the text properties
2323 of strings. (`equal' ignores text properties.) */)
2324 (register Lisp_Object o1, Lisp_Object o2)
2325 {
2326 return internal_equal (o1, o2, 0, 1, Qnil) ? Qt : Qnil;
2327 }
2328
2329 /* DEPTH is current depth of recursion. Signal an error if it
2330 gets too deep.
2331 PROPS means compare string text properties too. */
2332
2333 static bool
2334 internal_equal (Lisp_Object o1, Lisp_Object o2, int depth, bool props,
2335 Lisp_Object ht)
2336 {
2337 if (depth > 10)
2338 {
2339 if (depth > 200)
2340 error ("Stack overflow in equal");
2341 if (NILP (ht))
2342 ht = CALLN (Fmake_hash_table, QCtest, Qeq);
2343 switch (XTYPE (o1))
2344 {
2345 case Lisp_Cons: case Lisp_Misc: case Lisp_Vectorlike:
2346 {
2347 struct Lisp_Hash_Table *h = XHASH_TABLE (ht);
2348 EMACS_UINT hash;
2349 ptrdiff_t i = hash_lookup (h, o1, &hash);
2350 if (i >= 0)
2351 { /* `o1' was seen already. */
2352 Lisp_Object o2s = HASH_VALUE (h, i);
2353 if (!NILP (Fmemq (o2, o2s)))
2354 return 1;
2355 else
2356 set_hash_value_slot (h, i, Fcons (o2, o2s));
2357 }
2358 else
2359 hash_put (h, o1, Fcons (o2, Qnil), hash);
2360 }
2361 default: ;
2362 }
2363 }
2364
2365 tail_recurse:
2366 QUIT;
2367 if (EQ (o1, o2))
2368 return 1;
2369 if (XTYPE (o1) != XTYPE (o2))
2370 return 0;
2371
2372 switch (XTYPE (o1))
2373 {
2374 case Lisp_Float:
2375 {
2376 double d1, d2;
2377
2378 d1 = extract_float (o1);
2379 d2 = extract_float (o2);
2380 /* If d is a NaN, then d != d. Two NaNs should be `equal' even
2381 though they are not =. */
2382 return d1 == d2 || (d1 != d1 && d2 != d2);
2383 }
2384
2385 case Lisp_Cons:
2386 if (!internal_equal (XCAR (o1), XCAR (o2), depth + 1, props, ht))
2387 return 0;
2388 o1 = XCDR (o1);
2389 o2 = XCDR (o2);
2390 /* FIXME: This inf-loops in a circular list! */
2391 goto tail_recurse;
2392
2393 case Lisp_Misc:
2394 if (XMISCTYPE (o1) != XMISCTYPE (o2))
2395 return 0;
2396 if (OVERLAYP (o1))
2397 {
2398 if (!internal_equal (OVERLAY_START (o1), OVERLAY_START (o2),
2399 depth + 1, props, ht)
2400 || !internal_equal (OVERLAY_END (o1), OVERLAY_END (o2),
2401 depth + 1, props, ht))
2402 return 0;
2403 o1 = XOVERLAY (o1)->plist;
2404 o2 = XOVERLAY (o2)->plist;
2405 goto tail_recurse;
2406 }
2407 if (MARKERP (o1))
2408 {
2409 return (XMARKER (o1)->buffer == XMARKER (o2)->buffer
2410 && (XMARKER (o1)->buffer == 0
2411 || XMARKER (o1)->bytepos == XMARKER (o2)->bytepos));
2412 }
2413 break;
2414
2415 case Lisp_Vectorlike:
2416 {
2417 register int i;
2418 ptrdiff_t size = ASIZE (o1);
2419 /* Pseudovectors have the type encoded in the size field, so this test
2420 actually checks that the objects have the same type as well as the
2421 same size. */
2422 if (ASIZE (o2) != size)
2423 return 0;
2424 /* Boolvectors are compared much like strings. */
2425 if (BOOL_VECTOR_P (o1))
2426 {
2427 EMACS_INT size = bool_vector_size (o1);
2428 if (size != bool_vector_size (o2))
2429 return 0;
2430 if (memcmp (bool_vector_data (o1), bool_vector_data (o2),
2431 bool_vector_bytes (size)))
2432 return 0;
2433 return 1;
2434 }
2435 if (WINDOW_CONFIGURATIONP (o1))
2436 return compare_window_configurations (o1, o2, 0);
2437
2438 /* Aside from them, only true vectors, char-tables, compiled
2439 functions, and fonts (font-spec, font-entity, font-object)
2440 are sensible to compare, so eliminate the others now. */
2441 if (size & PSEUDOVECTOR_FLAG)
2442 {
2443 if (((size & PVEC_TYPE_MASK) >> PSEUDOVECTOR_AREA_BITS)
2444 < PVEC_COMPILED)
2445 return 0;
2446 size &= PSEUDOVECTOR_SIZE_MASK;
2447 }
2448 for (i = 0; i < size; i++)
2449 {
2450 Lisp_Object v1, v2;
2451 v1 = AREF (o1, i);
2452 v2 = AREF (o2, i);
2453 if (!internal_equal (v1, v2, depth + 1, props, ht))
2454 return 0;
2455 }
2456 return 1;
2457 }
2458 break;
2459
2460 case Lisp_String:
2461 if (SCHARS (o1) != SCHARS (o2))
2462 return 0;
2463 if (SBYTES (o1) != SBYTES (o2))
2464 return 0;
2465 if (memcmp (SDATA (o1), SDATA (o2), SBYTES (o1)))
2466 return 0;
2467 if (props && !compare_string_intervals (o1, o2))
2468 return 0;
2469 return 1;
2470
2471 default:
2472 break;
2473 }
2474
2475 return 0;
2476 }
2477 \f
2478
2479 DEFUN ("fillarray", Ffillarray, Sfillarray, 2, 2, 0,
2480 doc: /* Store each element of ARRAY with ITEM.
2481 ARRAY is a vector, string, char-table, or bool-vector. */)
2482 (Lisp_Object array, Lisp_Object item)
2483 {
2484 register ptrdiff_t size, idx;
2485
2486 if (VECTORP (array))
2487 for (idx = 0, size = ASIZE (array); idx < size; idx++)
2488 ASET (array, idx, item);
2489 else if (CHAR_TABLE_P (array))
2490 {
2491 int i;
2492
2493 for (i = 0; i < (1 << CHARTAB_SIZE_BITS_0); i++)
2494 set_char_table_contents (array, i, item);
2495 set_char_table_defalt (array, item);
2496 }
2497 else if (STRINGP (array))
2498 {
2499 register unsigned char *p = SDATA (array);
2500 int charval;
2501 CHECK_CHARACTER (item);
2502 charval = XFASTINT (item);
2503 size = SCHARS (array);
2504 if (STRING_MULTIBYTE (array))
2505 {
2506 unsigned char str[MAX_MULTIBYTE_LENGTH];
2507 int len = CHAR_STRING (charval, str);
2508 ptrdiff_t size_byte = SBYTES (array);
2509 ptrdiff_t product;
2510
2511 if (INT_MULTIPLY_WRAPV (size, len, &product) || product != size_byte)
2512 error ("Attempt to change byte length of a string");
2513 for (idx = 0; idx < size_byte; idx++)
2514 *p++ = str[idx % len];
2515 }
2516 else
2517 for (idx = 0; idx < size; idx++)
2518 p[idx] = charval;
2519 }
2520 else if (BOOL_VECTOR_P (array))
2521 return bool_vector_fill (array, item);
2522 else
2523 wrong_type_argument (Qarrayp, array);
2524 return array;
2525 }
2526
2527 DEFUN ("clear-string", Fclear_string, Sclear_string,
2528 1, 1, 0,
2529 doc: /* Clear the contents of STRING.
2530 This makes STRING unibyte and may change its length. */)
2531 (Lisp_Object string)
2532 {
2533 ptrdiff_t len;
2534 CHECK_STRING (string);
2535 len = SBYTES (string);
2536 memset (SDATA (string), 0, len);
2537 STRING_SET_CHARS (string, len);
2538 STRING_SET_UNIBYTE (string);
2539 return Qnil;
2540 }
2541 \f
2542 /* ARGSUSED */
2543 Lisp_Object
2544 nconc2 (Lisp_Object s1, Lisp_Object s2)
2545 {
2546 return CALLN (Fnconc, s1, s2);
2547 }
2548
2549 DEFUN ("nconc", Fnconc, Snconc, 0, MANY, 0,
2550 doc: /* Concatenate any number of lists by altering them.
2551 Only the last argument is not altered, and need not be a list.
2552 usage: (nconc &rest LISTS) */)
2553 (ptrdiff_t nargs, Lisp_Object *args)
2554 {
2555 ptrdiff_t argnum;
2556 register Lisp_Object tail, tem, val;
2557
2558 val = tail = Qnil;
2559
2560 for (argnum = 0; argnum < nargs; argnum++)
2561 {
2562 tem = args[argnum];
2563 if (NILP (tem)) continue;
2564
2565 if (NILP (val))
2566 val = tem;
2567
2568 if (argnum + 1 == nargs) break;
2569
2570 CHECK_LIST_CONS (tem, tem);
2571
2572 while (CONSP (tem))
2573 {
2574 tail = tem;
2575 tem = XCDR (tail);
2576 QUIT;
2577 }
2578
2579 tem = args[argnum + 1];
2580 Fsetcdr (tail, tem);
2581 if (NILP (tem))
2582 args[argnum + 1] = tail;
2583 }
2584
2585 return val;
2586 }
2587 \f
2588 /* This is the guts of all mapping functions.
2589 Apply FN to each element of SEQ, one by one,
2590 storing the results into elements of VALS, a C vector of Lisp_Objects.
2591 LENI is the length of VALS, which should also be the length of SEQ. */
2592
2593 static void
2594 mapcar1 (EMACS_INT leni, Lisp_Object *vals, Lisp_Object fn, Lisp_Object seq)
2595 {
2596 Lisp_Object tail, dummy;
2597 EMACS_INT i;
2598
2599 if (VECTORP (seq) || COMPILEDP (seq))
2600 {
2601 for (i = 0; i < leni; i++)
2602 {
2603 dummy = call1 (fn, AREF (seq, i));
2604 if (vals)
2605 vals[i] = dummy;
2606 }
2607 }
2608 else if (BOOL_VECTOR_P (seq))
2609 {
2610 for (i = 0; i < leni; i++)
2611 {
2612 dummy = call1 (fn, bool_vector_ref (seq, i));
2613 if (vals)
2614 vals[i] = dummy;
2615 }
2616 }
2617 else if (STRINGP (seq))
2618 {
2619 ptrdiff_t i_byte;
2620
2621 for (i = 0, i_byte = 0; i < leni;)
2622 {
2623 int c;
2624 ptrdiff_t i_before = i;
2625
2626 FETCH_STRING_CHAR_ADVANCE (c, seq, i, i_byte);
2627 XSETFASTINT (dummy, c);
2628 dummy = call1 (fn, dummy);
2629 if (vals)
2630 vals[i_before] = dummy;
2631 }
2632 }
2633 else /* Must be a list, since Flength did not get an error */
2634 {
2635 tail = seq;
2636 for (i = 0; i < leni && CONSP (tail); i++)
2637 {
2638 dummy = call1 (fn, XCAR (tail));
2639 if (vals)
2640 vals[i] = dummy;
2641 tail = XCDR (tail);
2642 }
2643 }
2644 }
2645
2646 DEFUN ("mapconcat", Fmapconcat, Smapconcat, 3, 3, 0,
2647 doc: /* Apply FUNCTION to each element of SEQUENCE, and concat the results as strings.
2648 In between each pair of results, stick in SEPARATOR. Thus, " " as
2649 SEPARATOR results in spaces between the values returned by FUNCTION.
2650 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2651 (Lisp_Object function, Lisp_Object sequence, Lisp_Object separator)
2652 {
2653 Lisp_Object len;
2654 EMACS_INT leni;
2655 EMACS_INT nargs;
2656 ptrdiff_t i;
2657 Lisp_Object *args;
2658 Lisp_Object ret;
2659 USE_SAFE_ALLOCA;
2660
2661 len = Flength (sequence);
2662 if (CHAR_TABLE_P (sequence))
2663 wrong_type_argument (Qlistp, sequence);
2664 leni = XINT (len);
2665 nargs = leni + leni - 1;
2666 if (nargs < 0) return empty_unibyte_string;
2667
2668 SAFE_ALLOCA_LISP (args, nargs);
2669
2670 mapcar1 (leni, args, function, sequence);
2671
2672 for (i = leni - 1; i > 0; i--)
2673 args[i + i] = args[i];
2674
2675 for (i = 1; i < nargs; i += 2)
2676 args[i] = separator;
2677
2678 ret = Fconcat (nargs, args);
2679 SAFE_FREE ();
2680
2681 return ret;
2682 }
2683
2684 DEFUN ("mapcar", Fmapcar, Smapcar, 2, 2, 0,
2685 doc: /* Apply FUNCTION to each element of SEQUENCE, and make a list of the results.
2686 The result is a list just as long as SEQUENCE.
2687 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2688 (Lisp_Object function, Lisp_Object sequence)
2689 {
2690 register Lisp_Object len;
2691 register EMACS_INT leni;
2692 register Lisp_Object *args;
2693 Lisp_Object ret;
2694 USE_SAFE_ALLOCA;
2695
2696 len = Flength (sequence);
2697 if (CHAR_TABLE_P (sequence))
2698 wrong_type_argument (Qlistp, sequence);
2699 leni = XFASTINT (len);
2700
2701 SAFE_ALLOCA_LISP (args, leni);
2702
2703 mapcar1 (leni, args, function, sequence);
2704
2705 ret = Flist (leni, args);
2706 SAFE_FREE ();
2707
2708 return ret;
2709 }
2710
2711 DEFUN ("mapc", Fmapc, Smapc, 2, 2, 0,
2712 doc: /* Apply FUNCTION to each element of SEQUENCE for side effects only.
2713 Unlike `mapcar', don't accumulate the results. Return SEQUENCE.
2714 SEQUENCE may be a list, a vector, a bool-vector, or a string. */)
2715 (Lisp_Object function, Lisp_Object sequence)
2716 {
2717 register EMACS_INT leni;
2718
2719 leni = XFASTINT (Flength (sequence));
2720 if (CHAR_TABLE_P (sequence))
2721 wrong_type_argument (Qlistp, sequence);
2722 mapcar1 (leni, 0, function, sequence);
2723
2724 return sequence;
2725 }
2726 \f
2727 /* This is how C code calls `yes-or-no-p' and allows the user
2728 to redefine it. */
2729
2730 Lisp_Object
2731 do_yes_or_no_p (Lisp_Object prompt)
2732 {
2733 return call1 (intern ("yes-or-no-p"), prompt);
2734 }
2735
2736 DEFUN ("yes-or-no-p", Fyes_or_no_p, Syes_or_no_p, 1, 1, 0,
2737 doc: /* Ask user a yes-or-no question.
2738 Return t if answer is yes, and nil if the answer is no.
2739 PROMPT is the string to display to ask the question. It should end in
2740 a space; `yes-or-no-p' adds \"(yes or no) \" to it.
2741
2742 The user must confirm the answer with RET, and can edit it until it
2743 has been confirmed.
2744
2745 If dialog boxes are supported, a dialog box will be used
2746 if `last-nonmenu-event' is nil, and `use-dialog-box' is non-nil. */)
2747 (Lisp_Object prompt)
2748 {
2749 Lisp_Object ans;
2750
2751 CHECK_STRING (prompt);
2752
2753 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2754 && use_dialog_box && ! NILP (last_input_event))
2755 {
2756 Lisp_Object pane, menu, obj;
2757 redisplay_preserve_echo_area (4);
2758 pane = list2 (Fcons (build_string ("Yes"), Qt),
2759 Fcons (build_string ("No"), Qnil));
2760 menu = Fcons (prompt, pane);
2761 obj = Fx_popup_dialog (Qt, menu, Qnil);
2762 return obj;
2763 }
2764
2765 AUTO_STRING (yes_or_no, "(yes or no) ");
2766 prompt = CALLN (Fconcat, prompt, yes_or_no);
2767
2768 while (1)
2769 {
2770 ans = Fdowncase (Fread_from_minibuffer (prompt, Qnil, Qnil, Qnil,
2771 Qyes_or_no_p_history, Qnil,
2772 Qnil));
2773 if (SCHARS (ans) == 3 && !strcmp (SSDATA (ans), "yes"))
2774 return Qt;
2775 if (SCHARS (ans) == 2 && !strcmp (SSDATA (ans), "no"))
2776 return Qnil;
2777
2778 Fding (Qnil);
2779 Fdiscard_input ();
2780 message1 ("Please answer yes or no.");
2781 Fsleep_for (make_number (2), Qnil);
2782 }
2783 }
2784 \f
2785 DEFUN ("load-average", Fload_average, Sload_average, 0, 1, 0,
2786 doc: /* Return list of 1 minute, 5 minute and 15 minute load averages.
2787
2788 Each of the three load averages is multiplied by 100, then converted
2789 to integer.
2790
2791 When USE-FLOATS is non-nil, floats will be used instead of integers.
2792 These floats are not multiplied by 100.
2793
2794 If the 5-minute or 15-minute load averages are not available, return a
2795 shortened list, containing only those averages which are available.
2796
2797 An error is thrown if the load average can't be obtained. In some
2798 cases making it work would require Emacs being installed setuid or
2799 setgid so that it can read kernel information, and that usually isn't
2800 advisable. */)
2801 (Lisp_Object use_floats)
2802 {
2803 double load_ave[3];
2804 int loads = getloadavg (load_ave, 3);
2805 Lisp_Object ret = Qnil;
2806
2807 if (loads < 0)
2808 error ("load-average not implemented for this operating system");
2809
2810 while (loads-- > 0)
2811 {
2812 Lisp_Object load = (NILP (use_floats)
2813 ? make_number (100.0 * load_ave[loads])
2814 : make_float (load_ave[loads]));
2815 ret = Fcons (load, ret);
2816 }
2817
2818 return ret;
2819 }
2820 \f
2821 DEFUN ("featurep", Ffeaturep, Sfeaturep, 1, 2, 0,
2822 doc: /* Return t if FEATURE is present in this Emacs.
2823
2824 Use this to conditionalize execution of lisp code based on the
2825 presence or absence of Emacs or environment extensions.
2826 Use `provide' to declare that a feature is available. This function
2827 looks at the value of the variable `features'. The optional argument
2828 SUBFEATURE can be used to check a specific subfeature of FEATURE. */)
2829 (Lisp_Object feature, Lisp_Object subfeature)
2830 {
2831 register Lisp_Object tem;
2832 CHECK_SYMBOL (feature);
2833 tem = Fmemq (feature, Vfeatures);
2834 if (!NILP (tem) && !NILP (subfeature))
2835 tem = Fmember (subfeature, Fget (feature, Qsubfeatures));
2836 return (NILP (tem)) ? Qnil : Qt;
2837 }
2838
2839 DEFUN ("provide", Fprovide, Sprovide, 1, 2, 0,
2840 doc: /* Announce that FEATURE is a feature of the current Emacs.
2841 The optional argument SUBFEATURES should be a list of symbols listing
2842 particular subfeatures supported in this version of FEATURE. */)
2843 (Lisp_Object feature, Lisp_Object subfeatures)
2844 {
2845 register Lisp_Object tem;
2846 CHECK_SYMBOL (feature);
2847 CHECK_LIST (subfeatures);
2848 if (!NILP (Vautoload_queue))
2849 Vautoload_queue = Fcons (Fcons (make_number (0), Vfeatures),
2850 Vautoload_queue);
2851 tem = Fmemq (feature, Vfeatures);
2852 if (NILP (tem))
2853 Vfeatures = Fcons (feature, Vfeatures);
2854 if (!NILP (subfeatures))
2855 Fput (feature, Qsubfeatures, subfeatures);
2856 LOADHIST_ATTACH (Fcons (Qprovide, feature));
2857
2858 /* Run any load-hooks for this file. */
2859 tem = Fassq (feature, Vafter_load_alist);
2860 if (CONSP (tem))
2861 Fmapc (Qfuncall, XCDR (tem));
2862
2863 return feature;
2864 }
2865 \f
2866 /* `require' and its subroutines. */
2867
2868 /* List of features currently being require'd, innermost first. */
2869
2870 static Lisp_Object require_nesting_list;
2871
2872 static void
2873 require_unwind (Lisp_Object old_value)
2874 {
2875 require_nesting_list = old_value;
2876 }
2877
2878 DEFUN ("require", Frequire, Srequire, 1, 3, 0,
2879 doc: /* If feature FEATURE is not loaded, load it from FILENAME.
2880 If FEATURE is not a member of the list `features', then the feature
2881 is not loaded; so load the file FILENAME.
2882 If FILENAME is omitted, the printname of FEATURE is used as the file name,
2883 and `load' will try to load this name appended with the suffix `.elc',
2884 `.el', or the system-dependent suffix for dynamic module files, in that
2885 order. The name without appended suffix will not be used.
2886 See `get-load-suffixes' for the complete list of suffixes.
2887 If the optional third argument NOERROR is non-nil,
2888 then return nil if the file is not found instead of signaling an error.
2889 Normally the return value is FEATURE.
2890 The normal messages at start and end of loading FILENAME are suppressed. */)
2891 (Lisp_Object feature, Lisp_Object filename, Lisp_Object noerror)
2892 {
2893 Lisp_Object tem;
2894 bool from_file = load_in_progress;
2895
2896 CHECK_SYMBOL (feature);
2897
2898 /* Record the presence of `require' in this file
2899 even if the feature specified is already loaded.
2900 But not more than once in any file,
2901 and not when we aren't loading or reading from a file. */
2902 if (!from_file)
2903 for (tem = Vcurrent_load_list; CONSP (tem); tem = XCDR (tem))
2904 if (NILP (XCDR (tem)) && STRINGP (XCAR (tem)))
2905 from_file = 1;
2906
2907 if (from_file)
2908 {
2909 tem = Fcons (Qrequire, feature);
2910 if (NILP (Fmember (tem, Vcurrent_load_list)))
2911 LOADHIST_ATTACH (tem);
2912 }
2913 tem = Fmemq (feature, Vfeatures);
2914
2915 if (NILP (tem))
2916 {
2917 ptrdiff_t count = SPECPDL_INDEX ();
2918 int nesting = 0;
2919
2920 /* This is to make sure that loadup.el gives a clear picture
2921 of what files are preloaded and when. */
2922 if (! NILP (Vpurify_flag))
2923 error ("(require %s) while preparing to dump",
2924 SDATA (SYMBOL_NAME (feature)));
2925
2926 /* A certain amount of recursive `require' is legitimate,
2927 but if we require the same feature recursively 3 times,
2928 signal an error. */
2929 tem = require_nesting_list;
2930 while (! NILP (tem))
2931 {
2932 if (! NILP (Fequal (feature, XCAR (tem))))
2933 nesting++;
2934 tem = XCDR (tem);
2935 }
2936 if (nesting > 3)
2937 error ("Recursive `require' for feature `%s'",
2938 SDATA (SYMBOL_NAME (feature)));
2939
2940 /* Update the list for any nested `require's that occur. */
2941 record_unwind_protect (require_unwind, require_nesting_list);
2942 require_nesting_list = Fcons (feature, require_nesting_list);
2943
2944 /* Value saved here is to be restored into Vautoload_queue */
2945 record_unwind_protect (un_autoload, Vautoload_queue);
2946 Vautoload_queue = Qt;
2947
2948 /* Load the file. */
2949 tem = Fload (NILP (filename) ? Fsymbol_name (feature) : filename,
2950 noerror, Qt, Qnil, (NILP (filename) ? Qt : Qnil));
2951
2952 /* If load failed entirely, return nil. */
2953 if (NILP (tem))
2954 return unbind_to (count, Qnil);
2955
2956 tem = Fmemq (feature, Vfeatures);
2957 if (NILP (tem))
2958 error ("Required feature `%s' was not provided",
2959 SDATA (SYMBOL_NAME (feature)));
2960
2961 /* Once loading finishes, don't undo it. */
2962 Vautoload_queue = Qt;
2963 feature = unbind_to (count, feature);
2964 }
2965
2966 return feature;
2967 }
2968 \f
2969 /* Primitives for work of the "widget" library.
2970 In an ideal world, this section would not have been necessary.
2971 However, lisp function calls being as slow as they are, it turns
2972 out that some functions in the widget library (wid-edit.el) are the
2973 bottleneck of Widget operation. Here is their translation to C,
2974 for the sole reason of efficiency. */
2975
2976 DEFUN ("plist-member", Fplist_member, Splist_member, 2, 2, 0,
2977 doc: /* Return non-nil if PLIST has the property PROP.
2978 PLIST is a property list, which is a list of the form
2979 (PROP1 VALUE1 PROP2 VALUE2 ...). PROP is a symbol.
2980 Unlike `plist-get', this allows you to distinguish between a missing
2981 property and a property with the value nil.
2982 The value is actually the tail of PLIST whose car is PROP. */)
2983 (Lisp_Object plist, Lisp_Object prop)
2984 {
2985 while (CONSP (plist) && !EQ (XCAR (plist), prop))
2986 {
2987 plist = XCDR (plist);
2988 plist = CDR (plist);
2989 QUIT;
2990 }
2991 return plist;
2992 }
2993
2994 DEFUN ("widget-put", Fwidget_put, Swidget_put, 3, 3, 0,
2995 doc: /* In WIDGET, set PROPERTY to VALUE.
2996 The value can later be retrieved with `widget-get'. */)
2997 (Lisp_Object widget, Lisp_Object property, Lisp_Object value)
2998 {
2999 CHECK_CONS (widget);
3000 XSETCDR (widget, Fplist_put (XCDR (widget), property, value));
3001 return value;
3002 }
3003
3004 DEFUN ("widget-get", Fwidget_get, Swidget_get, 2, 2, 0,
3005 doc: /* In WIDGET, get the value of PROPERTY.
3006 The value could either be specified when the widget was created, or
3007 later with `widget-put'. */)
3008 (Lisp_Object widget, Lisp_Object property)
3009 {
3010 Lisp_Object tmp;
3011
3012 while (1)
3013 {
3014 if (NILP (widget))
3015 return Qnil;
3016 CHECK_CONS (widget);
3017 tmp = Fplist_member (XCDR (widget), property);
3018 if (CONSP (tmp))
3019 {
3020 tmp = XCDR (tmp);
3021 return CAR (tmp);
3022 }
3023 tmp = XCAR (widget);
3024 if (NILP (tmp))
3025 return Qnil;
3026 widget = Fget (tmp, Qwidget_type);
3027 }
3028 }
3029
3030 DEFUN ("widget-apply", Fwidget_apply, Swidget_apply, 2, MANY, 0,
3031 doc: /* Apply the value of WIDGET's PROPERTY to the widget itself.
3032 ARGS are passed as extra arguments to the function.
3033 usage: (widget-apply WIDGET PROPERTY &rest ARGS) */)
3034 (ptrdiff_t nargs, Lisp_Object *args)
3035 {
3036 Lisp_Object widget = args[0];
3037 Lisp_Object property = args[1];
3038 Lisp_Object propval = Fwidget_get (widget, property);
3039 Lisp_Object trailing_args = Flist (nargs - 2, args + 2);
3040 Lisp_Object result = CALLN (Fapply, propval, widget, trailing_args);
3041 return result;
3042 }
3043
3044 #ifdef HAVE_LANGINFO_CODESET
3045 #include <langinfo.h>
3046 #endif
3047
3048 DEFUN ("locale-info", Flocale_info, Slocale_info, 1, 1, 0,
3049 doc: /* Access locale data ITEM for the current C locale, if available.
3050 ITEM should be one of the following:
3051
3052 `codeset', returning the character set as a string (locale item CODESET);
3053
3054 `days', returning a 7-element vector of day names (locale items DAY_n);
3055
3056 `months', returning a 12-element vector of month names (locale items MON_n);
3057
3058 `paper', returning a list (WIDTH HEIGHT) for the default paper size,
3059 both measured in millimeters (locale items PAPER_WIDTH, PAPER_HEIGHT).
3060
3061 If the system can't provide such information through a call to
3062 `nl_langinfo', or if ITEM isn't from the list above, return nil.
3063
3064 See also Info node `(libc)Locales'.
3065
3066 The data read from the system are decoded using `locale-coding-system'. */)
3067 (Lisp_Object item)
3068 {
3069 char *str = NULL;
3070 #ifdef HAVE_LANGINFO_CODESET
3071 Lisp_Object val;
3072 if (EQ (item, Qcodeset))
3073 {
3074 str = nl_langinfo (CODESET);
3075 return build_string (str);
3076 }
3077 #ifdef DAY_1
3078 else if (EQ (item, Qdays)) /* e.g. for calendar-day-name-array */
3079 {
3080 Lisp_Object v = Fmake_vector (make_number (7), Qnil);
3081 const int days[7] = {DAY_1, DAY_2, DAY_3, DAY_4, DAY_5, DAY_6, DAY_7};
3082 int i;
3083 synchronize_system_time_locale ();
3084 for (i = 0; i < 7; i++)
3085 {
3086 str = nl_langinfo (days[i]);
3087 val = build_unibyte_string (str);
3088 /* Fixme: Is this coding system necessarily right, even if
3089 it is consistent with CODESET? If not, what to do? */
3090 ASET (v, i, code_convert_string_norecord (val, Vlocale_coding_system,
3091 0));
3092 }
3093 return v;
3094 }
3095 #endif /* DAY_1 */
3096 #ifdef MON_1
3097 else if (EQ (item, Qmonths)) /* e.g. for calendar-month-name-array */
3098 {
3099 Lisp_Object v = Fmake_vector (make_number (12), Qnil);
3100 const int months[12] = {MON_1, MON_2, MON_3, MON_4, MON_5, MON_6, MON_7,
3101 MON_8, MON_9, MON_10, MON_11, MON_12};
3102 int i;
3103 synchronize_system_time_locale ();
3104 for (i = 0; i < 12; i++)
3105 {
3106 str = nl_langinfo (months[i]);
3107 val = build_unibyte_string (str);
3108 ASET (v, i, code_convert_string_norecord (val, Vlocale_coding_system,
3109 0));
3110 }
3111 return v;
3112 }
3113 #endif /* MON_1 */
3114 /* LC_PAPER stuff isn't defined as accessible in glibc as of 2.3.1,
3115 but is in the locale files. This could be used by ps-print. */
3116 #ifdef PAPER_WIDTH
3117 else if (EQ (item, Qpaper))
3118 return list2i (nl_langinfo (PAPER_WIDTH), nl_langinfo (PAPER_HEIGHT));
3119 #endif /* PAPER_WIDTH */
3120 #endif /* HAVE_LANGINFO_CODESET*/
3121 return Qnil;
3122 }
3123 \f
3124 /* base64 encode/decode functions (RFC 2045).
3125 Based on code from GNU recode. */
3126
3127 #define MIME_LINE_LENGTH 76
3128
3129 #define IS_ASCII(Character) \
3130 ((Character) < 128)
3131 #define IS_BASE64(Character) \
3132 (IS_ASCII (Character) && base64_char_to_value[Character] >= 0)
3133 #define IS_BASE64_IGNORABLE(Character) \
3134 ((Character) == ' ' || (Character) == '\t' || (Character) == '\n' \
3135 || (Character) == '\f' || (Character) == '\r')
3136
3137 /* Used by base64_decode_1 to retrieve a non-base64-ignorable
3138 character or return retval if there are no characters left to
3139 process. */
3140 #define READ_QUADRUPLET_BYTE(retval) \
3141 do \
3142 { \
3143 if (i == length) \
3144 { \
3145 if (nchars_return) \
3146 *nchars_return = nchars; \
3147 return (retval); \
3148 } \
3149 c = from[i++]; \
3150 } \
3151 while (IS_BASE64_IGNORABLE (c))
3152
3153 /* Table of characters coding the 64 values. */
3154 static const char base64_value_to_char[64] =
3155 {
3156 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', /* 0- 9 */
3157 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', /* 10-19 */
3158 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', /* 20-29 */
3159 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', /* 30-39 */
3160 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', /* 40-49 */
3161 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 50-59 */
3162 '8', '9', '+', '/' /* 60-63 */
3163 };
3164
3165 /* Table of base64 values for first 128 characters. */
3166 static const short base64_char_to_value[128] =
3167 {
3168 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0- 9 */
3169 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 10- 19 */
3170 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 20- 29 */
3171 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 30- 39 */
3172 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, /* 40- 49 */
3173 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, /* 50- 59 */
3174 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, /* 60- 69 */
3175 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 70- 79 */
3176 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, /* 80- 89 */
3177 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, /* 90- 99 */
3178 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, /* 100-109 */
3179 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, /* 110-119 */
3180 49, 50, 51, -1, -1, -1, -1, -1 /* 120-127 */
3181 };
3182
3183 /* The following diagram shows the logical steps by which three octets
3184 get transformed into four base64 characters.
3185
3186 .--------. .--------. .--------.
3187 |aaaaaabb| |bbbbcccc| |ccdddddd|
3188 `--------' `--------' `--------'
3189 6 2 4 4 2 6
3190 .--------+--------+--------+--------.
3191 |00aaaaaa|00bbbbbb|00cccccc|00dddddd|
3192 `--------+--------+--------+--------'
3193
3194 .--------+--------+--------+--------.
3195 |AAAAAAAA|BBBBBBBB|CCCCCCCC|DDDDDDDD|
3196 `--------+--------+--------+--------'
3197
3198 The octets are divided into 6 bit chunks, which are then encoded into
3199 base64 characters. */
3200
3201
3202 static ptrdiff_t base64_encode_1 (const char *, char *, ptrdiff_t, bool, bool);
3203 static ptrdiff_t base64_decode_1 (const char *, char *, ptrdiff_t, bool,
3204 ptrdiff_t *);
3205
3206 DEFUN ("base64-encode-region", Fbase64_encode_region, Sbase64_encode_region,
3207 2, 3, "r",
3208 doc: /* Base64-encode the region between BEG and END.
3209 Return the length of the encoded text.
3210 Optional third argument NO-LINE-BREAK means do not break long lines
3211 into shorter lines. */)
3212 (Lisp_Object beg, Lisp_Object end, Lisp_Object no_line_break)
3213 {
3214 char *encoded;
3215 ptrdiff_t allength, length;
3216 ptrdiff_t ibeg, iend, encoded_length;
3217 ptrdiff_t old_pos = PT;
3218 USE_SAFE_ALLOCA;
3219
3220 validate_region (&beg, &end);
3221
3222 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3223 iend = CHAR_TO_BYTE (XFASTINT (end));
3224 move_gap_both (XFASTINT (beg), ibeg);
3225
3226 /* We need to allocate enough room for encoding the text.
3227 We need 33 1/3% more space, plus a newline every 76
3228 characters, and then we round up. */
3229 length = iend - ibeg;
3230 allength = length + length/3 + 1;
3231 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3232
3233 encoded = SAFE_ALLOCA (allength);
3234 encoded_length = base64_encode_1 ((char *) BYTE_POS_ADDR (ibeg),
3235 encoded, length, NILP (no_line_break),
3236 !NILP (BVAR (current_buffer, enable_multibyte_characters)));
3237 if (encoded_length > allength)
3238 emacs_abort ();
3239
3240 if (encoded_length < 0)
3241 {
3242 /* The encoding wasn't possible. */
3243 SAFE_FREE ();
3244 error ("Multibyte character in data for base64 encoding");
3245 }
3246
3247 /* Now we have encoded the region, so we insert the new contents
3248 and delete the old. (Insert first in order to preserve markers.) */
3249 SET_PT_BOTH (XFASTINT (beg), ibeg);
3250 insert (encoded, encoded_length);
3251 SAFE_FREE ();
3252 del_range_byte (ibeg + encoded_length, iend + encoded_length, 1);
3253
3254 /* If point was outside of the region, restore it exactly; else just
3255 move to the beginning of the region. */
3256 if (old_pos >= XFASTINT (end))
3257 old_pos += encoded_length - (XFASTINT (end) - XFASTINT (beg));
3258 else if (old_pos > XFASTINT (beg))
3259 old_pos = XFASTINT (beg);
3260 SET_PT (old_pos);
3261
3262 /* We return the length of the encoded text. */
3263 return make_number (encoded_length);
3264 }
3265
3266 DEFUN ("base64-encode-string", Fbase64_encode_string, Sbase64_encode_string,
3267 1, 2, 0,
3268 doc: /* Base64-encode STRING and return the result.
3269 Optional second argument NO-LINE-BREAK means do not break long lines
3270 into shorter lines. */)
3271 (Lisp_Object string, Lisp_Object no_line_break)
3272 {
3273 ptrdiff_t allength, length, encoded_length;
3274 char *encoded;
3275 Lisp_Object encoded_string;
3276 USE_SAFE_ALLOCA;
3277
3278 CHECK_STRING (string);
3279
3280 /* We need to allocate enough room for encoding the text.
3281 We need 33 1/3% more space, plus a newline every 76
3282 characters, and then we round up. */
3283 length = SBYTES (string);
3284 allength = length + length/3 + 1;
3285 allength += allength / MIME_LINE_LENGTH + 1 + 6;
3286
3287 /* We need to allocate enough room for decoding the text. */
3288 encoded = SAFE_ALLOCA (allength);
3289
3290 encoded_length = base64_encode_1 (SSDATA (string),
3291 encoded, length, NILP (no_line_break),
3292 STRING_MULTIBYTE (string));
3293 if (encoded_length > allength)
3294 emacs_abort ();
3295
3296 if (encoded_length < 0)
3297 {
3298 /* The encoding wasn't possible. */
3299 error ("Multibyte character in data for base64 encoding");
3300 }
3301
3302 encoded_string = make_unibyte_string (encoded, encoded_length);
3303 SAFE_FREE ();
3304
3305 return encoded_string;
3306 }
3307
3308 static ptrdiff_t
3309 base64_encode_1 (const char *from, char *to, ptrdiff_t length,
3310 bool line_break, bool multibyte)
3311 {
3312 int counter = 0;
3313 ptrdiff_t i = 0;
3314 char *e = to;
3315 int c;
3316 unsigned int value;
3317 int bytes;
3318
3319 while (i < length)
3320 {
3321 if (multibyte)
3322 {
3323 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3324 if (CHAR_BYTE8_P (c))
3325 c = CHAR_TO_BYTE8 (c);
3326 else if (c >= 256)
3327 return -1;
3328 i += bytes;
3329 }
3330 else
3331 c = from[i++];
3332
3333 /* Wrap line every 76 characters. */
3334
3335 if (line_break)
3336 {
3337 if (counter < MIME_LINE_LENGTH / 4)
3338 counter++;
3339 else
3340 {
3341 *e++ = '\n';
3342 counter = 1;
3343 }
3344 }
3345
3346 /* Process first byte of a triplet. */
3347
3348 *e++ = base64_value_to_char[0x3f & c >> 2];
3349 value = (0x03 & c) << 4;
3350
3351 /* Process second byte of a triplet. */
3352
3353 if (i == length)
3354 {
3355 *e++ = base64_value_to_char[value];
3356 *e++ = '=';
3357 *e++ = '=';
3358 break;
3359 }
3360
3361 if (multibyte)
3362 {
3363 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3364 if (CHAR_BYTE8_P (c))
3365 c = CHAR_TO_BYTE8 (c);
3366 else if (c >= 256)
3367 return -1;
3368 i += bytes;
3369 }
3370 else
3371 c = from[i++];
3372
3373 *e++ = base64_value_to_char[value | (0x0f & c >> 4)];
3374 value = (0x0f & c) << 2;
3375
3376 /* Process third byte of a triplet. */
3377
3378 if (i == length)
3379 {
3380 *e++ = base64_value_to_char[value];
3381 *e++ = '=';
3382 break;
3383 }
3384
3385 if (multibyte)
3386 {
3387 c = STRING_CHAR_AND_LENGTH ((unsigned char *) from + i, bytes);
3388 if (CHAR_BYTE8_P (c))
3389 c = CHAR_TO_BYTE8 (c);
3390 else if (c >= 256)
3391 return -1;
3392 i += bytes;
3393 }
3394 else
3395 c = from[i++];
3396
3397 *e++ = base64_value_to_char[value | (0x03 & c >> 6)];
3398 *e++ = base64_value_to_char[0x3f & c];
3399 }
3400
3401 return e - to;
3402 }
3403
3404
3405 DEFUN ("base64-decode-region", Fbase64_decode_region, Sbase64_decode_region,
3406 2, 2, "r",
3407 doc: /* Base64-decode the region between BEG and END.
3408 Return the length of the decoded text.
3409 If the region can't be decoded, signal an error and don't modify the buffer. */)
3410 (Lisp_Object beg, Lisp_Object end)
3411 {
3412 ptrdiff_t ibeg, iend, length, allength;
3413 char *decoded;
3414 ptrdiff_t old_pos = PT;
3415 ptrdiff_t decoded_length;
3416 ptrdiff_t inserted_chars;
3417 bool multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3418 USE_SAFE_ALLOCA;
3419
3420 validate_region (&beg, &end);
3421
3422 ibeg = CHAR_TO_BYTE (XFASTINT (beg));
3423 iend = CHAR_TO_BYTE (XFASTINT (end));
3424
3425 length = iend - ibeg;
3426
3427 /* We need to allocate enough room for decoding the text. If we are
3428 working on a multibyte buffer, each decoded code may occupy at
3429 most two bytes. */
3430 allength = multibyte ? length * 2 : length;
3431 decoded = SAFE_ALLOCA (allength);
3432
3433 move_gap_both (XFASTINT (beg), ibeg);
3434 decoded_length = base64_decode_1 ((char *) BYTE_POS_ADDR (ibeg),
3435 decoded, length,
3436 multibyte, &inserted_chars);
3437 if (decoded_length > allength)
3438 emacs_abort ();
3439
3440 if (decoded_length < 0)
3441 {
3442 /* The decoding wasn't possible. */
3443 error ("Invalid base64 data");
3444 }
3445
3446 /* Now we have decoded the region, so we insert the new contents
3447 and delete the old. (Insert first in order to preserve markers.) */
3448 TEMP_SET_PT_BOTH (XFASTINT (beg), ibeg);
3449 insert_1_both (decoded, inserted_chars, decoded_length, 0, 1, 0);
3450 SAFE_FREE ();
3451
3452 /* Delete the original text. */
3453 del_range_both (PT, PT_BYTE, XFASTINT (end) + inserted_chars,
3454 iend + decoded_length, 1);
3455
3456 /* If point was outside of the region, restore it exactly; else just
3457 move to the beginning of the region. */
3458 if (old_pos >= XFASTINT (end))
3459 old_pos += inserted_chars - (XFASTINT (end) - XFASTINT (beg));
3460 else if (old_pos > XFASTINT (beg))
3461 old_pos = XFASTINT (beg);
3462 SET_PT (old_pos > ZV ? ZV : old_pos);
3463
3464 return make_number (inserted_chars);
3465 }
3466
3467 DEFUN ("base64-decode-string", Fbase64_decode_string, Sbase64_decode_string,
3468 1, 1, 0,
3469 doc: /* Base64-decode STRING and return the result. */)
3470 (Lisp_Object string)
3471 {
3472 char *decoded;
3473 ptrdiff_t length, decoded_length;
3474 Lisp_Object decoded_string;
3475 USE_SAFE_ALLOCA;
3476
3477 CHECK_STRING (string);
3478
3479 length = SBYTES (string);
3480 /* We need to allocate enough room for decoding the text. */
3481 decoded = SAFE_ALLOCA (length);
3482
3483 /* The decoded result should be unibyte. */
3484 decoded_length = base64_decode_1 (SSDATA (string), decoded, length,
3485 0, NULL);
3486 if (decoded_length > length)
3487 emacs_abort ();
3488 else if (decoded_length >= 0)
3489 decoded_string = make_unibyte_string (decoded, decoded_length);
3490 else
3491 decoded_string = Qnil;
3492
3493 SAFE_FREE ();
3494 if (!STRINGP (decoded_string))
3495 error ("Invalid base64 data");
3496
3497 return decoded_string;
3498 }
3499
3500 /* Base64-decode the data at FROM of LENGTH bytes into TO. If
3501 MULTIBYTE, the decoded result should be in multibyte
3502 form. If NCHARS_RETURN is not NULL, store the number of produced
3503 characters in *NCHARS_RETURN. */
3504
3505 static ptrdiff_t
3506 base64_decode_1 (const char *from, char *to, ptrdiff_t length,
3507 bool multibyte, ptrdiff_t *nchars_return)
3508 {
3509 ptrdiff_t i = 0; /* Used inside READ_QUADRUPLET_BYTE */
3510 char *e = to;
3511 unsigned char c;
3512 unsigned long value;
3513 ptrdiff_t nchars = 0;
3514
3515 while (1)
3516 {
3517 /* Process first byte of a quadruplet. */
3518
3519 READ_QUADRUPLET_BYTE (e-to);
3520
3521 if (!IS_BASE64 (c))
3522 return -1;
3523 value = base64_char_to_value[c] << 18;
3524
3525 /* Process second byte of a quadruplet. */
3526
3527 READ_QUADRUPLET_BYTE (-1);
3528
3529 if (!IS_BASE64 (c))
3530 return -1;
3531 value |= base64_char_to_value[c] << 12;
3532
3533 c = (unsigned char) (value >> 16);
3534 if (multibyte && c >= 128)
3535 e += BYTE8_STRING (c, e);
3536 else
3537 *e++ = c;
3538 nchars++;
3539
3540 /* Process third byte of a quadruplet. */
3541
3542 READ_QUADRUPLET_BYTE (-1);
3543
3544 if (c == '=')
3545 {
3546 READ_QUADRUPLET_BYTE (-1);
3547
3548 if (c != '=')
3549 return -1;
3550 continue;
3551 }
3552
3553 if (!IS_BASE64 (c))
3554 return -1;
3555 value |= base64_char_to_value[c] << 6;
3556
3557 c = (unsigned char) (0xff & value >> 8);
3558 if (multibyte && c >= 128)
3559 e += BYTE8_STRING (c, e);
3560 else
3561 *e++ = c;
3562 nchars++;
3563
3564 /* Process fourth byte of a quadruplet. */
3565
3566 READ_QUADRUPLET_BYTE (-1);
3567
3568 if (c == '=')
3569 continue;
3570
3571 if (!IS_BASE64 (c))
3572 return -1;
3573 value |= base64_char_to_value[c];
3574
3575 c = (unsigned char) (0xff & value);
3576 if (multibyte && c >= 128)
3577 e += BYTE8_STRING (c, e);
3578 else
3579 *e++ = c;
3580 nchars++;
3581 }
3582 }
3583
3584
3585 \f
3586 /***********************************************************************
3587 ***** *****
3588 ***** Hash Tables *****
3589 ***** *****
3590 ***********************************************************************/
3591
3592 /* Implemented by gerd@gnu.org. This hash table implementation was
3593 inspired by CMUCL hash tables. */
3594
3595 /* Ideas:
3596
3597 1. For small tables, association lists are probably faster than
3598 hash tables because they have lower overhead.
3599
3600 For uses of hash tables where the O(1) behavior of table
3601 operations is not a requirement, it might therefore be a good idea
3602 not to hash. Instead, we could just do a linear search in the
3603 key_and_value vector of the hash table. This could be done
3604 if a `:linear-search t' argument is given to make-hash-table. */
3605
3606
3607 /* The list of all weak hash tables. Don't staticpro this one. */
3608
3609 static struct Lisp_Hash_Table *weak_hash_tables;
3610
3611 \f
3612 /***********************************************************************
3613 Utilities
3614 ***********************************************************************/
3615
3616 static void
3617 CHECK_HASH_TABLE (Lisp_Object x)
3618 {
3619 CHECK_TYPE (HASH_TABLE_P (x), Qhash_table_p, x);
3620 }
3621
3622 static void
3623 set_hash_key_and_value (struct Lisp_Hash_Table *h, Lisp_Object key_and_value)
3624 {
3625 h->key_and_value = key_and_value;
3626 }
3627 static void
3628 set_hash_next (struct Lisp_Hash_Table *h, Lisp_Object next)
3629 {
3630 h->next = next;
3631 }
3632 static void
3633 set_hash_next_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3634 {
3635 gc_aset (h->next, idx, val);
3636 }
3637 static void
3638 set_hash_hash (struct Lisp_Hash_Table *h, Lisp_Object hash)
3639 {
3640 h->hash = hash;
3641 }
3642 static void
3643 set_hash_hash_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3644 {
3645 gc_aset (h->hash, idx, val);
3646 }
3647 static void
3648 set_hash_index (struct Lisp_Hash_Table *h, Lisp_Object index)
3649 {
3650 h->index = index;
3651 }
3652 static void
3653 set_hash_index_slot (struct Lisp_Hash_Table *h, ptrdiff_t idx, Lisp_Object val)
3654 {
3655 gc_aset (h->index, idx, val);
3656 }
3657
3658 /* If OBJ is a Lisp hash table, return a pointer to its struct
3659 Lisp_Hash_Table. Otherwise, signal an error. */
3660
3661 static struct Lisp_Hash_Table *
3662 check_hash_table (Lisp_Object obj)
3663 {
3664 CHECK_HASH_TABLE (obj);
3665 return XHASH_TABLE (obj);
3666 }
3667
3668
3669 /* Value is the next integer I >= N, N >= 0 which is "almost" a prime
3670 number. A number is "almost" a prime number if it is not divisible
3671 by any integer in the range 2 .. (NEXT_ALMOST_PRIME_LIMIT - 1). */
3672
3673 EMACS_INT
3674 next_almost_prime (EMACS_INT n)
3675 {
3676 verify (NEXT_ALMOST_PRIME_LIMIT == 11);
3677 for (n |= 1; ; n += 2)
3678 if (n % 3 != 0 && n % 5 != 0 && n % 7 != 0)
3679 return n;
3680 }
3681
3682
3683 /* Find KEY in ARGS which has size NARGS. Don't consider indices for
3684 which USED[I] is non-zero. If found at index I in ARGS, set
3685 USED[I] and USED[I + 1] to 1, and return I + 1. Otherwise return
3686 0. This function is used to extract a keyword/argument pair from
3687 a DEFUN parameter list. */
3688
3689 static ptrdiff_t
3690 get_key_arg (Lisp_Object key, ptrdiff_t nargs, Lisp_Object *args, char *used)
3691 {
3692 ptrdiff_t i;
3693
3694 for (i = 1; i < nargs; i++)
3695 if (!used[i - 1] && EQ (args[i - 1], key))
3696 {
3697 used[i - 1] = 1;
3698 used[i] = 1;
3699 return i;
3700 }
3701
3702 return 0;
3703 }
3704
3705
3706 /* Return a Lisp vector which has the same contents as VEC but has
3707 at least INCR_MIN more entries, where INCR_MIN is positive.
3708 If NITEMS_MAX is not -1, do not grow the vector to be any larger
3709 than NITEMS_MAX. Entries in the resulting
3710 vector that are not copied from VEC are set to nil. */
3711
3712 Lisp_Object
3713 larger_vector (Lisp_Object vec, ptrdiff_t incr_min, ptrdiff_t nitems_max)
3714 {
3715 struct Lisp_Vector *v;
3716 ptrdiff_t incr, incr_max, old_size, new_size;
3717 ptrdiff_t C_language_max = min (PTRDIFF_MAX, SIZE_MAX) / sizeof *v->contents;
3718 ptrdiff_t n_max = (0 <= nitems_max && nitems_max < C_language_max
3719 ? nitems_max : C_language_max);
3720 eassert (VECTORP (vec));
3721 eassert (0 < incr_min && -1 <= nitems_max);
3722 old_size = ASIZE (vec);
3723 incr_max = n_max - old_size;
3724 incr = max (incr_min, min (old_size >> 1, incr_max));
3725 if (incr_max < incr)
3726 memory_full (SIZE_MAX);
3727 new_size = old_size + incr;
3728 v = allocate_vector (new_size);
3729 memcpy (v->contents, XVECTOR (vec)->contents, old_size * sizeof *v->contents);
3730 memclear (v->contents + old_size, incr * word_size);
3731 XSETVECTOR (vec, v);
3732 return vec;
3733 }
3734
3735
3736 /***********************************************************************
3737 Low-level Functions
3738 ***********************************************************************/
3739
3740 struct hash_table_test hashtest_eq, hashtest_eql, hashtest_equal;
3741
3742 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3743 HASH2 in hash table H using `eql'. Value is true if KEY1 and
3744 KEY2 are the same. */
3745
3746 static bool
3747 cmpfn_eql (struct hash_table_test *ht,
3748 Lisp_Object key1,
3749 Lisp_Object key2)
3750 {
3751 return (FLOATP (key1)
3752 && FLOATP (key2)
3753 && XFLOAT_DATA (key1) == XFLOAT_DATA (key2));
3754 }
3755
3756
3757 /* Compare KEY1 which has hash code HASH1 and KEY2 with hash code
3758 HASH2 in hash table H using `equal'. Value is true if KEY1 and
3759 KEY2 are the same. */
3760
3761 static bool
3762 cmpfn_equal (struct hash_table_test *ht,
3763 Lisp_Object key1,
3764 Lisp_Object key2)
3765 {
3766 return !NILP (Fequal (key1, key2));
3767 }
3768
3769
3770 /* Compare KEY1 which has hash code HASH1, and KEY2 with hash code
3771 HASH2 in hash table H using H->user_cmp_function. Value is true
3772 if KEY1 and KEY2 are the same. */
3773
3774 static bool
3775 cmpfn_user_defined (struct hash_table_test *ht,
3776 Lisp_Object key1,
3777 Lisp_Object key2)
3778 {
3779 return !NILP (call2 (ht->user_cmp_function, key1, key2));
3780 }
3781
3782
3783 /* Value is a hash code for KEY for use in hash table H which uses
3784 `eq' to compare keys. The hash code returned is guaranteed to fit
3785 in a Lisp integer. */
3786
3787 static EMACS_UINT
3788 hashfn_eq (struct hash_table_test *ht, Lisp_Object key)
3789 {
3790 EMACS_UINT hash = XHASH (key) ^ XTYPE (key);
3791 return hash;
3792 }
3793
3794 /* Value is a hash code for KEY for use in hash table H which uses
3795 `eql' to compare keys. The hash code returned is guaranteed to fit
3796 in a Lisp integer. */
3797
3798 static EMACS_UINT
3799 hashfn_eql (struct hash_table_test *ht, Lisp_Object key)
3800 {
3801 EMACS_UINT hash;
3802 if (FLOATP (key))
3803 hash = sxhash (key, 0);
3804 else
3805 hash = XHASH (key) ^ XTYPE (key);
3806 return hash;
3807 }
3808
3809 /* Value is a hash code for KEY for use in hash table H which uses
3810 `equal' to compare keys. The hash code returned is guaranteed to fit
3811 in a Lisp integer. */
3812
3813 static EMACS_UINT
3814 hashfn_equal (struct hash_table_test *ht, Lisp_Object key)
3815 {
3816 EMACS_UINT hash = sxhash (key, 0);
3817 return hash;
3818 }
3819
3820 /* Value is a hash code for KEY for use in hash table H which uses as
3821 user-defined function to compare keys. The hash code returned is
3822 guaranteed to fit in a Lisp integer. */
3823
3824 static EMACS_UINT
3825 hashfn_user_defined (struct hash_table_test *ht, Lisp_Object key)
3826 {
3827 Lisp_Object hash = call1 (ht->user_hash_function, key);
3828 return hashfn_eq (ht, hash);
3829 }
3830
3831 /* Allocate basically initialized hash table. */
3832
3833 static struct Lisp_Hash_Table *
3834 allocate_hash_table (void)
3835 {
3836 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Hash_Table,
3837 count, PVEC_HASH_TABLE);
3838 }
3839
3840 /* An upper bound on the size of a hash table index. It must fit in
3841 ptrdiff_t and be a valid Emacs fixnum. */
3842 #define INDEX_SIZE_BOUND \
3843 ((ptrdiff_t) min (MOST_POSITIVE_FIXNUM, PTRDIFF_MAX / word_size))
3844
3845 /* Create and initialize a new hash table.
3846
3847 TEST specifies the test the hash table will use to compare keys.
3848 It must be either one of the predefined tests `eq', `eql' or
3849 `equal' or a symbol denoting a user-defined test named TEST with
3850 test and hash functions USER_TEST and USER_HASH.
3851
3852 Give the table initial capacity SIZE, SIZE >= 0, an integer.
3853
3854 If REHASH_SIZE is an integer, it must be > 0, and this hash table's
3855 new size when it becomes full is computed by adding REHASH_SIZE to
3856 its old size. If REHASH_SIZE is a float, it must be > 1.0, and the
3857 table's new size is computed by multiplying its old size with
3858 REHASH_SIZE.
3859
3860 REHASH_THRESHOLD must be a float <= 1.0, and > 0. The table will
3861 be resized when the ratio of (number of entries in the table) /
3862 (table size) is >= REHASH_THRESHOLD.
3863
3864 WEAK specifies the weakness of the table. If non-nil, it must be
3865 one of the symbols `key', `value', `key-or-value', or `key-and-value'. */
3866
3867 Lisp_Object
3868 make_hash_table (struct hash_table_test test,
3869 Lisp_Object size, Lisp_Object rehash_size,
3870 Lisp_Object rehash_threshold, Lisp_Object weak)
3871 {
3872 struct Lisp_Hash_Table *h;
3873 Lisp_Object table;
3874 EMACS_INT index_size, sz;
3875 ptrdiff_t i;
3876 double index_float;
3877
3878 /* Preconditions. */
3879 eassert (SYMBOLP (test.name));
3880 eassert (INTEGERP (size) && XINT (size) >= 0);
3881 eassert ((INTEGERP (rehash_size) && XINT (rehash_size) > 0)
3882 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size)));
3883 eassert (FLOATP (rehash_threshold)
3884 && 0 < XFLOAT_DATA (rehash_threshold)
3885 && XFLOAT_DATA (rehash_threshold) <= 1.0);
3886
3887 if (XFASTINT (size) == 0)
3888 size = make_number (1);
3889
3890 sz = XFASTINT (size);
3891 index_float = sz / XFLOAT_DATA (rehash_threshold);
3892 index_size = (index_float < INDEX_SIZE_BOUND + 1
3893 ? next_almost_prime (index_float)
3894 : INDEX_SIZE_BOUND + 1);
3895 if (INDEX_SIZE_BOUND < max (index_size, 2 * sz))
3896 error ("Hash table too large");
3897
3898 /* Allocate a table and initialize it. */
3899 h = allocate_hash_table ();
3900
3901 /* Initialize hash table slots. */
3902 h->test = test;
3903 h->weak = weak;
3904 h->rehash_threshold = rehash_threshold;
3905 h->rehash_size = rehash_size;
3906 h->count = 0;
3907 h->key_and_value = Fmake_vector (make_number (2 * sz), Qnil);
3908 h->hash = Fmake_vector (size, Qnil);
3909 h->next = Fmake_vector (size, Qnil);
3910 h->index = Fmake_vector (make_number (index_size), Qnil);
3911
3912 /* Set up the free list. */
3913 for (i = 0; i < sz - 1; ++i)
3914 set_hash_next_slot (h, i, make_number (i + 1));
3915 h->next_free = make_number (0);
3916
3917 XSET_HASH_TABLE (table, h);
3918 eassert (HASH_TABLE_P (table));
3919 eassert (XHASH_TABLE (table) == h);
3920
3921 /* Maybe add this hash table to the list of all weak hash tables. */
3922 if (NILP (h->weak))
3923 h->next_weak = NULL;
3924 else
3925 {
3926 h->next_weak = weak_hash_tables;
3927 weak_hash_tables = h;
3928 }
3929
3930 return table;
3931 }
3932
3933
3934 /* Return a copy of hash table H1. Keys and values are not copied,
3935 only the table itself is. */
3936
3937 static Lisp_Object
3938 copy_hash_table (struct Lisp_Hash_Table *h1)
3939 {
3940 Lisp_Object table;
3941 struct Lisp_Hash_Table *h2;
3942
3943 h2 = allocate_hash_table ();
3944 *h2 = *h1;
3945 h2->key_and_value = Fcopy_sequence (h1->key_and_value);
3946 h2->hash = Fcopy_sequence (h1->hash);
3947 h2->next = Fcopy_sequence (h1->next);
3948 h2->index = Fcopy_sequence (h1->index);
3949 XSET_HASH_TABLE (table, h2);
3950
3951 /* Maybe add this hash table to the list of all weak hash tables. */
3952 if (!NILP (h2->weak))
3953 {
3954 h2->next_weak = weak_hash_tables;
3955 weak_hash_tables = h2;
3956 }
3957
3958 return table;
3959 }
3960
3961
3962 /* Resize hash table H if it's too full. If H cannot be resized
3963 because it's already too large, throw an error. */
3964
3965 static void
3966 maybe_resize_hash_table (struct Lisp_Hash_Table *h)
3967 {
3968 if (NILP (h->next_free))
3969 {
3970 ptrdiff_t old_size = HASH_TABLE_SIZE (h);
3971 EMACS_INT new_size, index_size, nsize;
3972 ptrdiff_t i;
3973 double index_float;
3974
3975 if (INTEGERP (h->rehash_size))
3976 new_size = old_size + XFASTINT (h->rehash_size);
3977 else
3978 {
3979 double float_new_size = old_size * XFLOAT_DATA (h->rehash_size);
3980 if (float_new_size < INDEX_SIZE_BOUND + 1)
3981 {
3982 new_size = float_new_size;
3983 if (new_size <= old_size)
3984 new_size = old_size + 1;
3985 }
3986 else
3987 new_size = INDEX_SIZE_BOUND + 1;
3988 }
3989 index_float = new_size / XFLOAT_DATA (h->rehash_threshold);
3990 index_size = (index_float < INDEX_SIZE_BOUND + 1
3991 ? next_almost_prime (index_float)
3992 : INDEX_SIZE_BOUND + 1);
3993 nsize = max (index_size, 2 * new_size);
3994 if (INDEX_SIZE_BOUND < nsize)
3995 error ("Hash table too large to resize");
3996
3997 #ifdef ENABLE_CHECKING
3998 if (HASH_TABLE_P (Vpurify_flag)
3999 && XHASH_TABLE (Vpurify_flag) == h)
4000 message ("Growing hash table to: %"pI"d", new_size);
4001 #endif
4002
4003 set_hash_key_and_value (h, larger_vector (h->key_and_value,
4004 2 * (new_size - old_size), -1));
4005 set_hash_next (h, larger_vector (h->next, new_size - old_size, -1));
4006 set_hash_hash (h, larger_vector (h->hash, new_size - old_size, -1));
4007 set_hash_index (h, Fmake_vector (make_number (index_size), Qnil));
4008
4009 /* Update the free list. Do it so that new entries are added at
4010 the end of the free list. This makes some operations like
4011 maphash faster. */
4012 for (i = old_size; i < new_size - 1; ++i)
4013 set_hash_next_slot (h, i, make_number (i + 1));
4014
4015 if (!NILP (h->next_free))
4016 {
4017 Lisp_Object last, next;
4018
4019 last = h->next_free;
4020 while (next = HASH_NEXT (h, XFASTINT (last)),
4021 !NILP (next))
4022 last = next;
4023
4024 set_hash_next_slot (h, XFASTINT (last), make_number (old_size));
4025 }
4026 else
4027 XSETFASTINT (h->next_free, old_size);
4028
4029 /* Rehash. */
4030 for (i = 0; i < old_size; ++i)
4031 if (!NILP (HASH_HASH (h, i)))
4032 {
4033 EMACS_UINT hash_code = XUINT (HASH_HASH (h, i));
4034 ptrdiff_t start_of_bucket = hash_code % ASIZE (h->index);
4035 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
4036 set_hash_index_slot (h, start_of_bucket, make_number (i));
4037 }
4038 }
4039 }
4040
4041
4042 /* Lookup KEY in hash table H. If HASH is non-null, return in *HASH
4043 the hash code of KEY. Value is the index of the entry in H
4044 matching KEY, or -1 if not found. */
4045
4046 ptrdiff_t
4047 hash_lookup (struct Lisp_Hash_Table *h, Lisp_Object key, EMACS_UINT *hash)
4048 {
4049 EMACS_UINT hash_code;
4050 ptrdiff_t start_of_bucket;
4051 Lisp_Object idx;
4052
4053 hash_code = h->test.hashfn (&h->test, key);
4054 eassert ((hash_code & ~INTMASK) == 0);
4055 if (hash)
4056 *hash = hash_code;
4057
4058 start_of_bucket = hash_code % ASIZE (h->index);
4059 idx = HASH_INDEX (h, start_of_bucket);
4060
4061 while (!NILP (idx))
4062 {
4063 ptrdiff_t i = XFASTINT (idx);
4064 if (EQ (key, HASH_KEY (h, i))
4065 || (h->test.cmpfn
4066 && hash_code == XUINT (HASH_HASH (h, i))
4067 && h->test.cmpfn (&h->test, key, HASH_KEY (h, i))))
4068 break;
4069 idx = HASH_NEXT (h, i);
4070 }
4071
4072 return NILP (idx) ? -1 : XFASTINT (idx);
4073 }
4074
4075
4076 /* Put an entry into hash table H that associates KEY with VALUE.
4077 HASH is a previously computed hash code of KEY.
4078 Value is the index of the entry in H matching KEY. */
4079
4080 ptrdiff_t
4081 hash_put (struct Lisp_Hash_Table *h, Lisp_Object key, Lisp_Object value,
4082 EMACS_UINT hash)
4083 {
4084 ptrdiff_t start_of_bucket, i;
4085
4086 eassert ((hash & ~INTMASK) == 0);
4087
4088 /* Increment count after resizing because resizing may fail. */
4089 maybe_resize_hash_table (h);
4090 h->count++;
4091
4092 /* Store key/value in the key_and_value vector. */
4093 i = XFASTINT (h->next_free);
4094 h->next_free = HASH_NEXT (h, i);
4095 set_hash_key_slot (h, i, key);
4096 set_hash_value_slot (h, i, value);
4097
4098 /* Remember its hash code. */
4099 set_hash_hash_slot (h, i, make_number (hash));
4100
4101 /* Add new entry to its collision chain. */
4102 start_of_bucket = hash % ASIZE (h->index);
4103 set_hash_next_slot (h, i, HASH_INDEX (h, start_of_bucket));
4104 set_hash_index_slot (h, start_of_bucket, make_number (i));
4105 return i;
4106 }
4107
4108
4109 /* Remove the entry matching KEY from hash table H, if there is one. */
4110
4111 void
4112 hash_remove_from_table (struct Lisp_Hash_Table *h, Lisp_Object key)
4113 {
4114 EMACS_UINT hash_code;
4115 ptrdiff_t start_of_bucket;
4116 Lisp_Object idx, prev;
4117
4118 hash_code = h->test.hashfn (&h->test, key);
4119 eassert ((hash_code & ~INTMASK) == 0);
4120 start_of_bucket = hash_code % ASIZE (h->index);
4121 idx = HASH_INDEX (h, start_of_bucket);
4122 prev = Qnil;
4123
4124 while (!NILP (idx))
4125 {
4126 ptrdiff_t i = XFASTINT (idx);
4127
4128 if (EQ (key, HASH_KEY (h, i))
4129 || (h->test.cmpfn
4130 && hash_code == XUINT (HASH_HASH (h, i))
4131 && h->test.cmpfn (&h->test, key, HASH_KEY (h, i))))
4132 {
4133 /* Take entry out of collision chain. */
4134 if (NILP (prev))
4135 set_hash_index_slot (h, start_of_bucket, HASH_NEXT (h, i));
4136 else
4137 set_hash_next_slot (h, XFASTINT (prev), HASH_NEXT (h, i));
4138
4139 /* Clear slots in key_and_value and add the slots to
4140 the free list. */
4141 set_hash_key_slot (h, i, Qnil);
4142 set_hash_value_slot (h, i, Qnil);
4143 set_hash_hash_slot (h, i, Qnil);
4144 set_hash_next_slot (h, i, h->next_free);
4145 h->next_free = make_number (i);
4146 h->count--;
4147 eassert (h->count >= 0);
4148 break;
4149 }
4150 else
4151 {
4152 prev = idx;
4153 idx = HASH_NEXT (h, i);
4154 }
4155 }
4156 }
4157
4158
4159 /* Clear hash table H. */
4160
4161 static void
4162 hash_clear (struct Lisp_Hash_Table *h)
4163 {
4164 if (h->count > 0)
4165 {
4166 ptrdiff_t i, size = HASH_TABLE_SIZE (h);
4167
4168 for (i = 0; i < size; ++i)
4169 {
4170 set_hash_next_slot (h, i, i < size - 1 ? make_number (i + 1) : Qnil);
4171 set_hash_key_slot (h, i, Qnil);
4172 set_hash_value_slot (h, i, Qnil);
4173 set_hash_hash_slot (h, i, Qnil);
4174 }
4175
4176 for (i = 0; i < ASIZE (h->index); ++i)
4177 ASET (h->index, i, Qnil);
4178
4179 h->next_free = make_number (0);
4180 h->count = 0;
4181 }
4182 }
4183
4184
4185 \f
4186 /************************************************************************
4187 Weak Hash Tables
4188 ************************************************************************/
4189
4190 /* Sweep weak hash table H. REMOVE_ENTRIES_P means remove
4191 entries from the table that don't survive the current GC.
4192 !REMOVE_ENTRIES_P means mark entries that are in use. Value is
4193 true if anything was marked. */
4194
4195 static bool
4196 sweep_weak_table (struct Lisp_Hash_Table *h, bool remove_entries_p)
4197 {
4198 ptrdiff_t n = gc_asize (h->index);
4199 bool marked = false;
4200
4201 for (ptrdiff_t bucket = 0; bucket < n; ++bucket)
4202 {
4203 Lisp_Object idx, next, prev;
4204
4205 /* Follow collision chain, removing entries that
4206 don't survive this garbage collection. */
4207 prev = Qnil;
4208 for (idx = HASH_INDEX (h, bucket); !NILP (idx); idx = next)
4209 {
4210 ptrdiff_t i = XFASTINT (idx);
4211 bool key_known_to_survive_p = survives_gc_p (HASH_KEY (h, i));
4212 bool value_known_to_survive_p = survives_gc_p (HASH_VALUE (h, i));
4213 bool remove_p;
4214
4215 if (EQ (h->weak, Qkey))
4216 remove_p = !key_known_to_survive_p;
4217 else if (EQ (h->weak, Qvalue))
4218 remove_p = !value_known_to_survive_p;
4219 else if (EQ (h->weak, Qkey_or_value))
4220 remove_p = !(key_known_to_survive_p || value_known_to_survive_p);
4221 else if (EQ (h->weak, Qkey_and_value))
4222 remove_p = !(key_known_to_survive_p && value_known_to_survive_p);
4223 else
4224 emacs_abort ();
4225
4226 next = HASH_NEXT (h, i);
4227
4228 if (remove_entries_p)
4229 {
4230 if (remove_p)
4231 {
4232 /* Take out of collision chain. */
4233 if (NILP (prev))
4234 set_hash_index_slot (h, bucket, next);
4235 else
4236 set_hash_next_slot (h, XFASTINT (prev), next);
4237
4238 /* Add to free list. */
4239 set_hash_next_slot (h, i, h->next_free);
4240 h->next_free = idx;
4241
4242 /* Clear key, value, and hash. */
4243 set_hash_key_slot (h, i, Qnil);
4244 set_hash_value_slot (h, i, Qnil);
4245 set_hash_hash_slot (h, i, Qnil);
4246
4247 h->count--;
4248 }
4249 else
4250 {
4251 prev = idx;
4252 }
4253 }
4254 else
4255 {
4256 if (!remove_p)
4257 {
4258 /* Make sure key and value survive. */
4259 if (!key_known_to_survive_p)
4260 {
4261 mark_object (HASH_KEY (h, i));
4262 marked = 1;
4263 }
4264
4265 if (!value_known_to_survive_p)
4266 {
4267 mark_object (HASH_VALUE (h, i));
4268 marked = 1;
4269 }
4270 }
4271 }
4272 }
4273 }
4274
4275 return marked;
4276 }
4277
4278 /* Remove elements from weak hash tables that don't survive the
4279 current garbage collection. Remove weak tables that don't survive
4280 from Vweak_hash_tables. Called from gc_sweep. */
4281
4282 NO_INLINE /* For better stack traces */
4283 void
4284 sweep_weak_hash_tables (void)
4285 {
4286 struct Lisp_Hash_Table *h, *used, *next;
4287 bool marked;
4288
4289 /* Mark all keys and values that are in use. Keep on marking until
4290 there is no more change. This is necessary for cases like
4291 value-weak table A containing an entry X -> Y, where Y is used in a
4292 key-weak table B, Z -> Y. If B comes after A in the list of weak
4293 tables, X -> Y might be removed from A, although when looking at B
4294 one finds that it shouldn't. */
4295 do
4296 {
4297 marked = 0;
4298 for (h = weak_hash_tables; h; h = h->next_weak)
4299 {
4300 if (h->header.size & ARRAY_MARK_FLAG)
4301 marked |= sweep_weak_table (h, 0);
4302 }
4303 }
4304 while (marked);
4305
4306 /* Remove tables and entries that aren't used. */
4307 for (h = weak_hash_tables, used = NULL; h; h = next)
4308 {
4309 next = h->next_weak;
4310
4311 if (h->header.size & ARRAY_MARK_FLAG)
4312 {
4313 /* TABLE is marked as used. Sweep its contents. */
4314 if (h->count > 0)
4315 sweep_weak_table (h, 1);
4316
4317 /* Add table to the list of used weak hash tables. */
4318 h->next_weak = used;
4319 used = h;
4320 }
4321 }
4322
4323 weak_hash_tables = used;
4324 }
4325
4326
4327 \f
4328 /***********************************************************************
4329 Hash Code Computation
4330 ***********************************************************************/
4331
4332 /* Maximum depth up to which to dive into Lisp structures. */
4333
4334 #define SXHASH_MAX_DEPTH 3
4335
4336 /* Maximum length up to which to take list and vector elements into
4337 account. */
4338
4339 #define SXHASH_MAX_LEN 7
4340
4341 /* Return a hash for string PTR which has length LEN. The hash value
4342 can be any EMACS_UINT value. */
4343
4344 EMACS_UINT
4345 hash_string (char const *ptr, ptrdiff_t len)
4346 {
4347 char const *p = ptr;
4348 char const *end = p + len;
4349 unsigned char c;
4350 EMACS_UINT hash = 0;
4351
4352 while (p != end)
4353 {
4354 c = *p++;
4355 hash = sxhash_combine (hash, c);
4356 }
4357
4358 return hash;
4359 }
4360
4361 /* Return a hash for string PTR which has length LEN. The hash
4362 code returned is guaranteed to fit in a Lisp integer. */
4363
4364 static EMACS_UINT
4365 sxhash_string (char const *ptr, ptrdiff_t len)
4366 {
4367 EMACS_UINT hash = hash_string (ptr, len);
4368 return SXHASH_REDUCE (hash);
4369 }
4370
4371 /* Return a hash for the floating point value VAL. */
4372
4373 static EMACS_UINT
4374 sxhash_float (double val)
4375 {
4376 EMACS_UINT hash = 0;
4377 enum {
4378 WORDS_PER_DOUBLE = (sizeof val / sizeof hash
4379 + (sizeof val % sizeof hash != 0))
4380 };
4381 union {
4382 double val;
4383 EMACS_UINT word[WORDS_PER_DOUBLE];
4384 } u;
4385 int i;
4386 u.val = val;
4387 memset (&u.val + 1, 0, sizeof u - sizeof u.val);
4388 for (i = 0; i < WORDS_PER_DOUBLE; i++)
4389 hash = sxhash_combine (hash, u.word[i]);
4390 return SXHASH_REDUCE (hash);
4391 }
4392
4393 /* Return a hash for list LIST. DEPTH is the current depth in the
4394 list. We don't recurse deeper than SXHASH_MAX_DEPTH in it. */
4395
4396 static EMACS_UINT
4397 sxhash_list (Lisp_Object list, int depth)
4398 {
4399 EMACS_UINT hash = 0;
4400 int i;
4401
4402 if (depth < SXHASH_MAX_DEPTH)
4403 for (i = 0;
4404 CONSP (list) && i < SXHASH_MAX_LEN;
4405 list = XCDR (list), ++i)
4406 {
4407 EMACS_UINT hash2 = sxhash (XCAR (list), depth + 1);
4408 hash = sxhash_combine (hash, hash2);
4409 }
4410
4411 if (!NILP (list))
4412 {
4413 EMACS_UINT hash2 = sxhash (list, depth + 1);
4414 hash = sxhash_combine (hash, hash2);
4415 }
4416
4417 return SXHASH_REDUCE (hash);
4418 }
4419
4420
4421 /* Return a hash for vector VECTOR. DEPTH is the current depth in
4422 the Lisp structure. */
4423
4424 static EMACS_UINT
4425 sxhash_vector (Lisp_Object vec, int depth)
4426 {
4427 EMACS_UINT hash = ASIZE (vec);
4428 int i, n;
4429
4430 n = min (SXHASH_MAX_LEN, ASIZE (vec));
4431 for (i = 0; i < n; ++i)
4432 {
4433 EMACS_UINT hash2 = sxhash (AREF (vec, i), depth + 1);
4434 hash = sxhash_combine (hash, hash2);
4435 }
4436
4437 return SXHASH_REDUCE (hash);
4438 }
4439
4440 /* Return a hash for bool-vector VECTOR. */
4441
4442 static EMACS_UINT
4443 sxhash_bool_vector (Lisp_Object vec)
4444 {
4445 EMACS_INT size = bool_vector_size (vec);
4446 EMACS_UINT hash = size;
4447 int i, n;
4448
4449 n = min (SXHASH_MAX_LEN, bool_vector_words (size));
4450 for (i = 0; i < n; ++i)
4451 hash = sxhash_combine (hash, bool_vector_data (vec)[i]);
4452
4453 return SXHASH_REDUCE (hash);
4454 }
4455
4456
4457 /* Return a hash code for OBJ. DEPTH is the current depth in the Lisp
4458 structure. Value is an unsigned integer clipped to INTMASK. */
4459
4460 EMACS_UINT
4461 sxhash (Lisp_Object obj, int depth)
4462 {
4463 EMACS_UINT hash;
4464
4465 if (depth > SXHASH_MAX_DEPTH)
4466 return 0;
4467
4468 switch (XTYPE (obj))
4469 {
4470 case_Lisp_Int:
4471 hash = XUINT (obj);
4472 break;
4473
4474 case Lisp_Misc:
4475 case Lisp_Symbol:
4476 hash = XHASH (obj);
4477 break;
4478
4479 case Lisp_String:
4480 hash = sxhash_string (SSDATA (obj), SBYTES (obj));
4481 break;
4482
4483 /* This can be everything from a vector to an overlay. */
4484 case Lisp_Vectorlike:
4485 if (VECTORP (obj))
4486 /* According to the CL HyperSpec, two arrays are equal only if
4487 they are `eq', except for strings and bit-vectors. In
4488 Emacs, this works differently. We have to compare element
4489 by element. */
4490 hash = sxhash_vector (obj, depth);
4491 else if (BOOL_VECTOR_P (obj))
4492 hash = sxhash_bool_vector (obj);
4493 else
4494 /* Others are `equal' if they are `eq', so let's take their
4495 address as hash. */
4496 hash = XHASH (obj);
4497 break;
4498
4499 case Lisp_Cons:
4500 hash = sxhash_list (obj, depth);
4501 break;
4502
4503 case Lisp_Float:
4504 hash = sxhash_float (XFLOAT_DATA (obj));
4505 break;
4506
4507 default:
4508 emacs_abort ();
4509 }
4510
4511 return hash;
4512 }
4513
4514
4515 \f
4516 /***********************************************************************
4517 Lisp Interface
4518 ***********************************************************************/
4519
4520
4521 DEFUN ("sxhash", Fsxhash, Ssxhash, 1, 1, 0,
4522 doc: /* Compute a hash code for OBJ and return it as integer. */)
4523 (Lisp_Object obj)
4524 {
4525 EMACS_UINT hash = sxhash (obj, 0);
4526 return make_number (hash);
4527 }
4528
4529
4530 DEFUN ("make-hash-table", Fmake_hash_table, Smake_hash_table, 0, MANY, 0,
4531 doc: /* Create and return a new hash table.
4532
4533 Arguments are specified as keyword/argument pairs. The following
4534 arguments are defined:
4535
4536 :test TEST -- TEST must be a symbol that specifies how to compare
4537 keys. Default is `eql'. Predefined are the tests `eq', `eql', and
4538 `equal'. User-supplied test and hash functions can be specified via
4539 `define-hash-table-test'.
4540
4541 :size SIZE -- A hint as to how many elements will be put in the table.
4542 Default is 65.
4543
4544 :rehash-size REHASH-SIZE - Indicates how to expand the table when it
4545 fills up. If REHASH-SIZE is an integer, increase the size by that
4546 amount. If it is a float, it must be > 1.0, and the new size is the
4547 old size multiplied by that factor. Default is 1.5.
4548
4549 :rehash-threshold THRESHOLD -- THRESHOLD must a float > 0, and <= 1.0.
4550 Resize the hash table when the ratio (number of entries / table size)
4551 is greater than or equal to THRESHOLD. Default is 0.8.
4552
4553 :weakness WEAK -- WEAK must be one of nil, t, `key', `value',
4554 `key-or-value', or `key-and-value'. If WEAK is not nil, the table
4555 returned is a weak table. Key/value pairs are removed from a weak
4556 hash table when there are no non-weak references pointing to their
4557 key, value, one of key or value, or both key and value, depending on
4558 WEAK. WEAK t is equivalent to `key-and-value'. Default value of WEAK
4559 is nil.
4560
4561 usage: (make-hash-table &rest KEYWORD-ARGS) */)
4562 (ptrdiff_t nargs, Lisp_Object *args)
4563 {
4564 Lisp_Object test, size, rehash_size, rehash_threshold, weak;
4565 struct hash_table_test testdesc;
4566 ptrdiff_t i;
4567 USE_SAFE_ALLOCA;
4568
4569 /* The vector `used' is used to keep track of arguments that
4570 have been consumed. */
4571 char *used = SAFE_ALLOCA (nargs * sizeof *used);
4572 memset (used, 0, nargs * sizeof *used);
4573
4574 /* See if there's a `:test TEST' among the arguments. */
4575 i = get_key_arg (QCtest, nargs, args, used);
4576 test = i ? args[i] : Qeql;
4577 if (EQ (test, Qeq))
4578 testdesc = hashtest_eq;
4579 else if (EQ (test, Qeql))
4580 testdesc = hashtest_eql;
4581 else if (EQ (test, Qequal))
4582 testdesc = hashtest_equal;
4583 else
4584 {
4585 /* See if it is a user-defined test. */
4586 Lisp_Object prop;
4587
4588 prop = Fget (test, Qhash_table_test);
4589 if (!CONSP (prop) || !CONSP (XCDR (prop)))
4590 signal_error ("Invalid hash table test", test);
4591 testdesc.name = test;
4592 testdesc.user_cmp_function = XCAR (prop);
4593 testdesc.user_hash_function = XCAR (XCDR (prop));
4594 testdesc.hashfn = hashfn_user_defined;
4595 testdesc.cmpfn = cmpfn_user_defined;
4596 }
4597
4598 /* See if there's a `:size SIZE' argument. */
4599 i = get_key_arg (QCsize, nargs, args, used);
4600 size = i ? args[i] : Qnil;
4601 if (NILP (size))
4602 size = make_number (DEFAULT_HASH_SIZE);
4603 else if (!INTEGERP (size) || XINT (size) < 0)
4604 signal_error ("Invalid hash table size", size);
4605
4606 /* Look for `:rehash-size SIZE'. */
4607 i = get_key_arg (QCrehash_size, nargs, args, used);
4608 rehash_size = i ? args[i] : make_float (DEFAULT_REHASH_SIZE);
4609 if (! ((INTEGERP (rehash_size) && 0 < XINT (rehash_size))
4610 || (FLOATP (rehash_size) && 1 < XFLOAT_DATA (rehash_size))))
4611 signal_error ("Invalid hash table rehash size", rehash_size);
4612
4613 /* Look for `:rehash-threshold THRESHOLD'. */
4614 i = get_key_arg (QCrehash_threshold, nargs, args, used);
4615 rehash_threshold = i ? args[i] : make_float (DEFAULT_REHASH_THRESHOLD);
4616 if (! (FLOATP (rehash_threshold)
4617 && 0 < XFLOAT_DATA (rehash_threshold)
4618 && XFLOAT_DATA (rehash_threshold) <= 1))
4619 signal_error ("Invalid hash table rehash threshold", rehash_threshold);
4620
4621 /* Look for `:weakness WEAK'. */
4622 i = get_key_arg (QCweakness, nargs, args, used);
4623 weak = i ? args[i] : Qnil;
4624 if (EQ (weak, Qt))
4625 weak = Qkey_and_value;
4626 if (!NILP (weak)
4627 && !EQ (weak, Qkey)
4628 && !EQ (weak, Qvalue)
4629 && !EQ (weak, Qkey_or_value)
4630 && !EQ (weak, Qkey_and_value))
4631 signal_error ("Invalid hash table weakness", weak);
4632
4633 /* Now, all args should have been used up, or there's a problem. */
4634 for (i = 0; i < nargs; ++i)
4635 if (!used[i])
4636 signal_error ("Invalid argument list", args[i]);
4637
4638 SAFE_FREE ();
4639 return make_hash_table (testdesc, size, rehash_size, rehash_threshold, weak);
4640 }
4641
4642
4643 DEFUN ("copy-hash-table", Fcopy_hash_table, Scopy_hash_table, 1, 1, 0,
4644 doc: /* Return a copy of hash table TABLE. */)
4645 (Lisp_Object table)
4646 {
4647 return copy_hash_table (check_hash_table (table));
4648 }
4649
4650
4651 DEFUN ("hash-table-count", Fhash_table_count, Shash_table_count, 1, 1, 0,
4652 doc: /* Return the number of elements in TABLE. */)
4653 (Lisp_Object table)
4654 {
4655 return make_number (check_hash_table (table)->count);
4656 }
4657
4658
4659 DEFUN ("hash-table-rehash-size", Fhash_table_rehash_size,
4660 Shash_table_rehash_size, 1, 1, 0,
4661 doc: /* Return the current rehash size of TABLE. */)
4662 (Lisp_Object table)
4663 {
4664 return check_hash_table (table)->rehash_size;
4665 }
4666
4667
4668 DEFUN ("hash-table-rehash-threshold", Fhash_table_rehash_threshold,
4669 Shash_table_rehash_threshold, 1, 1, 0,
4670 doc: /* Return the current rehash threshold of TABLE. */)
4671 (Lisp_Object table)
4672 {
4673 return check_hash_table (table)->rehash_threshold;
4674 }
4675
4676
4677 DEFUN ("hash-table-size", Fhash_table_size, Shash_table_size, 1, 1, 0,
4678 doc: /* Return the size of TABLE.
4679 The size can be used as an argument to `make-hash-table' to create
4680 a hash table than can hold as many elements as TABLE holds
4681 without need for resizing. */)
4682 (Lisp_Object table)
4683 {
4684 struct Lisp_Hash_Table *h = check_hash_table (table);
4685 return make_number (HASH_TABLE_SIZE (h));
4686 }
4687
4688
4689 DEFUN ("hash-table-test", Fhash_table_test, Shash_table_test, 1, 1, 0,
4690 doc: /* Return the test TABLE uses. */)
4691 (Lisp_Object table)
4692 {
4693 return check_hash_table (table)->test.name;
4694 }
4695
4696
4697 DEFUN ("hash-table-weakness", Fhash_table_weakness, Shash_table_weakness,
4698 1, 1, 0,
4699 doc: /* Return the weakness of TABLE. */)
4700 (Lisp_Object table)
4701 {
4702 return check_hash_table (table)->weak;
4703 }
4704
4705
4706 DEFUN ("hash-table-p", Fhash_table_p, Shash_table_p, 1, 1, 0,
4707 doc: /* Return t if OBJ is a Lisp hash table object. */)
4708 (Lisp_Object obj)
4709 {
4710 return HASH_TABLE_P (obj) ? Qt : Qnil;
4711 }
4712
4713
4714 DEFUN ("clrhash", Fclrhash, Sclrhash, 1, 1, 0,
4715 doc: /* Clear hash table TABLE and return it. */)
4716 (Lisp_Object table)
4717 {
4718 hash_clear (check_hash_table (table));
4719 /* Be compatible with XEmacs. */
4720 return table;
4721 }
4722
4723
4724 DEFUN ("gethash", Fgethash, Sgethash, 2, 3, 0,
4725 doc: /* Look up KEY in TABLE and return its associated value.
4726 If KEY is not found, return DFLT which defaults to nil. */)
4727 (Lisp_Object key, Lisp_Object table, Lisp_Object dflt)
4728 {
4729 struct Lisp_Hash_Table *h = check_hash_table (table);
4730 ptrdiff_t i = hash_lookup (h, key, NULL);
4731 return i >= 0 ? HASH_VALUE (h, i) : dflt;
4732 }
4733
4734
4735 DEFUN ("puthash", Fputhash, Sputhash, 3, 3, 0,
4736 doc: /* Associate KEY with VALUE in hash table TABLE.
4737 If KEY is already present in table, replace its current value with
4738 VALUE. In any case, return VALUE. */)
4739 (Lisp_Object key, Lisp_Object value, Lisp_Object table)
4740 {
4741 struct Lisp_Hash_Table *h = check_hash_table (table);
4742 ptrdiff_t i;
4743 EMACS_UINT hash;
4744
4745 i = hash_lookup (h, key, &hash);
4746 if (i >= 0)
4747 set_hash_value_slot (h, i, value);
4748 else
4749 hash_put (h, key, value, hash);
4750
4751 return value;
4752 }
4753
4754
4755 DEFUN ("remhash", Fremhash, Sremhash, 2, 2, 0,
4756 doc: /* Remove KEY from TABLE. */)
4757 (Lisp_Object key, Lisp_Object table)
4758 {
4759 struct Lisp_Hash_Table *h = check_hash_table (table);
4760 hash_remove_from_table (h, key);
4761 return Qnil;
4762 }
4763
4764
4765 DEFUN ("maphash", Fmaphash, Smaphash, 2, 2, 0,
4766 doc: /* Call FUNCTION for all entries in hash table TABLE.
4767 FUNCTION is called with two arguments, KEY and VALUE.
4768 `maphash' always returns nil. */)
4769 (Lisp_Object function, Lisp_Object table)
4770 {
4771 struct Lisp_Hash_Table *h = check_hash_table (table);
4772
4773 for (ptrdiff_t i = 0; i < HASH_TABLE_SIZE (h); ++i)
4774 if (!NILP (HASH_HASH (h, i)))
4775 call2 (function, HASH_KEY (h, i), HASH_VALUE (h, i));
4776
4777 return Qnil;
4778 }
4779
4780
4781 DEFUN ("define-hash-table-test", Fdefine_hash_table_test,
4782 Sdefine_hash_table_test, 3, 3, 0,
4783 doc: /* Define a new hash table test with name NAME, a symbol.
4784
4785 In hash tables created with NAME specified as test, use TEST to
4786 compare keys, and HASH for computing hash codes of keys.
4787
4788 TEST must be a function taking two arguments and returning non-nil if
4789 both arguments are the same. HASH must be a function taking one
4790 argument and returning an object that is the hash code of the argument.
4791 It should be the case that if (eq (funcall HASH x1) (funcall HASH x2))
4792 returns nil, then (funcall TEST x1 x2) also returns nil. */)
4793 (Lisp_Object name, Lisp_Object test, Lisp_Object hash)
4794 {
4795 return Fput (name, Qhash_table_test, list2 (test, hash));
4796 }
4797
4798
4799 \f
4800 /************************************************************************
4801 MD5, SHA-1, and SHA-2
4802 ************************************************************************/
4803
4804 #include "md5.h"
4805 #include "sha1.h"
4806 #include "sha256.h"
4807 #include "sha512.h"
4808
4809 /* ALGORITHM is a symbol: md5, sha1, sha224 and so on. */
4810
4811 static Lisp_Object
4812 secure_hash (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start,
4813 Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror,
4814 Lisp_Object binary)
4815 {
4816 int i;
4817 ptrdiff_t size, start_char = 0, start_byte, end_char = 0, end_byte;
4818 register EMACS_INT b, e;
4819 register struct buffer *bp;
4820 EMACS_INT temp;
4821 int digest_size;
4822 void *(*hash_func) (const char *, size_t, void *);
4823 Lisp_Object digest;
4824
4825 CHECK_SYMBOL (algorithm);
4826
4827 if (STRINGP (object))
4828 {
4829 if (NILP (coding_system))
4830 {
4831 /* Decide the coding-system to encode the data with. */
4832
4833 if (STRING_MULTIBYTE (object))
4834 /* use default, we can't guess correct value */
4835 coding_system = preferred_coding_system ();
4836 else
4837 coding_system = Qraw_text;
4838 }
4839
4840 if (NILP (Fcoding_system_p (coding_system)))
4841 {
4842 /* Invalid coding system. */
4843
4844 if (!NILP (noerror))
4845 coding_system = Qraw_text;
4846 else
4847 xsignal1 (Qcoding_system_error, coding_system);
4848 }
4849
4850 if (STRING_MULTIBYTE (object))
4851 object = code_convert_string (object, coding_system, Qnil, 1, 0, 1);
4852
4853 size = SCHARS (object);
4854 validate_subarray (object, start, end, size, &start_char, &end_char);
4855
4856 start_byte = !start_char ? 0 : string_char_to_byte (object, start_char);
4857 end_byte = (end_char == size
4858 ? SBYTES (object)
4859 : string_char_to_byte (object, end_char));
4860 }
4861 else
4862 {
4863 struct buffer *prev = current_buffer;
4864
4865 record_unwind_current_buffer ();
4866
4867 CHECK_BUFFER (object);
4868
4869 bp = XBUFFER (object);
4870 set_buffer_internal (bp);
4871
4872 if (NILP (start))
4873 b = BEGV;
4874 else
4875 {
4876 CHECK_NUMBER_COERCE_MARKER (start);
4877 b = XINT (start);
4878 }
4879
4880 if (NILP (end))
4881 e = ZV;
4882 else
4883 {
4884 CHECK_NUMBER_COERCE_MARKER (end);
4885 e = XINT (end);
4886 }
4887
4888 if (b > e)
4889 temp = b, b = e, e = temp;
4890
4891 if (!(BEGV <= b && e <= ZV))
4892 args_out_of_range (start, end);
4893
4894 if (NILP (coding_system))
4895 {
4896 /* Decide the coding-system to encode the data with.
4897 See fileio.c:Fwrite-region */
4898
4899 if (!NILP (Vcoding_system_for_write))
4900 coding_system = Vcoding_system_for_write;
4901 else
4902 {
4903 bool force_raw_text = 0;
4904
4905 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4906 if (NILP (coding_system)
4907 || NILP (Flocal_variable_p (Qbuffer_file_coding_system, Qnil)))
4908 {
4909 coding_system = Qnil;
4910 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4911 force_raw_text = 1;
4912 }
4913
4914 if (NILP (coding_system) && !NILP (Fbuffer_file_name (object)))
4915 {
4916 /* Check file-coding-system-alist. */
4917 Lisp_Object val = CALLN (Ffind_operation_coding_system,
4918 Qwrite_region, start, end,
4919 Fbuffer_file_name (object));
4920 if (CONSP (val) && !NILP (XCDR (val)))
4921 coding_system = XCDR (val);
4922 }
4923
4924 if (NILP (coding_system)
4925 && !NILP (BVAR (XBUFFER (object), buffer_file_coding_system)))
4926 {
4927 /* If we still have not decided a coding system, use the
4928 default value of buffer-file-coding-system. */
4929 coding_system = BVAR (XBUFFER (object), buffer_file_coding_system);
4930 }
4931
4932 if (!force_raw_text
4933 && !NILP (Ffboundp (Vselect_safe_coding_system_function)))
4934 /* Confirm that VAL can surely encode the current region. */
4935 coding_system = call4 (Vselect_safe_coding_system_function,
4936 make_number (b), make_number (e),
4937 coding_system, Qnil);
4938
4939 if (force_raw_text)
4940 coding_system = Qraw_text;
4941 }
4942
4943 if (NILP (Fcoding_system_p (coding_system)))
4944 {
4945 /* Invalid coding system. */
4946
4947 if (!NILP (noerror))
4948 coding_system = Qraw_text;
4949 else
4950 xsignal1 (Qcoding_system_error, coding_system);
4951 }
4952 }
4953
4954 object = make_buffer_string (b, e, 0);
4955 set_buffer_internal (prev);
4956 /* Discard the unwind protect for recovering the current
4957 buffer. */
4958 specpdl_ptr--;
4959
4960 if (STRING_MULTIBYTE (object))
4961 object = code_convert_string (object, coding_system, Qnil, 1, 0, 0);
4962 start_byte = 0;
4963 end_byte = SBYTES (object);
4964 }
4965
4966 if (EQ (algorithm, Qmd5))
4967 {
4968 digest_size = MD5_DIGEST_SIZE;
4969 hash_func = md5_buffer;
4970 }
4971 else if (EQ (algorithm, Qsha1))
4972 {
4973 digest_size = SHA1_DIGEST_SIZE;
4974 hash_func = sha1_buffer;
4975 }
4976 else if (EQ (algorithm, Qsha224))
4977 {
4978 digest_size = SHA224_DIGEST_SIZE;
4979 hash_func = sha224_buffer;
4980 }
4981 else if (EQ (algorithm, Qsha256))
4982 {
4983 digest_size = SHA256_DIGEST_SIZE;
4984 hash_func = sha256_buffer;
4985 }
4986 else if (EQ (algorithm, Qsha384))
4987 {
4988 digest_size = SHA384_DIGEST_SIZE;
4989 hash_func = sha384_buffer;
4990 }
4991 else if (EQ (algorithm, Qsha512))
4992 {
4993 digest_size = SHA512_DIGEST_SIZE;
4994 hash_func = sha512_buffer;
4995 }
4996 else
4997 error ("Invalid algorithm arg: %s", SDATA (Fsymbol_name (algorithm)));
4998
4999 /* allocate 2 x digest_size so that it can be re-used to hold the
5000 hexified value */
5001 digest = make_uninit_string (digest_size * 2);
5002
5003 hash_func (SSDATA (object) + start_byte,
5004 end_byte - start_byte,
5005 SSDATA (digest));
5006
5007 if (NILP (binary))
5008 {
5009 unsigned char *p = SDATA (digest);
5010 for (i = digest_size - 1; i >= 0; i--)
5011 {
5012 static char const hexdigit[16] = "0123456789abcdef";
5013 int p_i = p[i];
5014 p[2 * i] = hexdigit[p_i >> 4];
5015 p[2 * i + 1] = hexdigit[p_i & 0xf];
5016 }
5017 return digest;
5018 }
5019 else
5020 return make_unibyte_string (SSDATA (digest), digest_size);
5021 }
5022
5023 DEFUN ("md5", Fmd5, Smd5, 1, 5, 0,
5024 doc: /* Return MD5 message digest of OBJECT, a buffer or string.
5025
5026 A message digest is a cryptographic checksum of a document, and the
5027 algorithm to calculate it is defined in RFC 1321.
5028
5029 The two optional arguments START and END are character positions
5030 specifying for which part of OBJECT the message digest should be
5031 computed. If nil or omitted, the digest is computed for the whole
5032 OBJECT.
5033
5034 The MD5 message digest is computed from the result of encoding the
5035 text in a coding system, not directly from the internal Emacs form of
5036 the text. The optional fourth argument CODING-SYSTEM specifies which
5037 coding system to encode the text with. It should be the same coding
5038 system that you used or will use when actually writing the text into a
5039 file.
5040
5041 If CODING-SYSTEM is nil or omitted, the default depends on OBJECT. If
5042 OBJECT is a buffer, the default for CODING-SYSTEM is whatever coding
5043 system would be chosen by default for writing this text into a file.
5044
5045 If OBJECT is a string, the most preferred coding system (see the
5046 command `prefer-coding-system') is used.
5047
5048 If NOERROR is non-nil, silently assume the `raw-text' coding if the
5049 guesswork fails. Normally, an error is signaled in such case. */)
5050 (Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object coding_system, Lisp_Object noerror)
5051 {
5052 return secure_hash (Qmd5, object, start, end, coding_system, noerror, Qnil);
5053 }
5054
5055 DEFUN ("secure-hash", Fsecure_hash, Ssecure_hash, 2, 5, 0,
5056 doc: /* Return the secure hash of OBJECT, a buffer or string.
5057 ALGORITHM is a symbol specifying the hash to use:
5058 md5, sha1, sha224, sha256, sha384 or sha512.
5059
5060 The two optional arguments START and END are positions specifying for
5061 which part of OBJECT to compute the hash. If nil or omitted, uses the
5062 whole OBJECT.
5063
5064 If BINARY is non-nil, returns a string in binary form. */)
5065 (Lisp_Object algorithm, Lisp_Object object, Lisp_Object start, Lisp_Object end, Lisp_Object binary)
5066 {
5067 return secure_hash (algorithm, object, start, end, Qnil, Qnil, binary);
5068 }
5069 \f
5070 void
5071 syms_of_fns (void)
5072 {
5073 DEFSYM (Qmd5, "md5");
5074 DEFSYM (Qsha1, "sha1");
5075 DEFSYM (Qsha224, "sha224");
5076 DEFSYM (Qsha256, "sha256");
5077 DEFSYM (Qsha384, "sha384");
5078 DEFSYM (Qsha512, "sha512");
5079
5080 /* Hash table stuff. */
5081 DEFSYM (Qhash_table_p, "hash-table-p");
5082 DEFSYM (Qeq, "eq");
5083 DEFSYM (Qeql, "eql");
5084 DEFSYM (Qequal, "equal");
5085 DEFSYM (QCtest, ":test");
5086 DEFSYM (QCsize, ":size");
5087 DEFSYM (QCrehash_size, ":rehash-size");
5088 DEFSYM (QCrehash_threshold, ":rehash-threshold");
5089 DEFSYM (QCweakness, ":weakness");
5090 DEFSYM (Qkey, "key");
5091 DEFSYM (Qvalue, "value");
5092 DEFSYM (Qhash_table_test, "hash-table-test");
5093 DEFSYM (Qkey_or_value, "key-or-value");
5094 DEFSYM (Qkey_and_value, "key-and-value");
5095
5096 defsubr (&Ssxhash);
5097 defsubr (&Smake_hash_table);
5098 defsubr (&Scopy_hash_table);
5099 defsubr (&Shash_table_count);
5100 defsubr (&Shash_table_rehash_size);
5101 defsubr (&Shash_table_rehash_threshold);
5102 defsubr (&Shash_table_size);
5103 defsubr (&Shash_table_test);
5104 defsubr (&Shash_table_weakness);
5105 defsubr (&Shash_table_p);
5106 defsubr (&Sclrhash);
5107 defsubr (&Sgethash);
5108 defsubr (&Sputhash);
5109 defsubr (&Sremhash);
5110 defsubr (&Smaphash);
5111 defsubr (&Sdefine_hash_table_test);
5112
5113 DEFSYM (Qstring_lessp, "string-lessp");
5114 DEFSYM (Qprovide, "provide");
5115 DEFSYM (Qrequire, "require");
5116 DEFSYM (Qyes_or_no_p_history, "yes-or-no-p-history");
5117 DEFSYM (Qcursor_in_echo_area, "cursor-in-echo-area");
5118 DEFSYM (Qwidget_type, "widget-type");
5119
5120 staticpro (&string_char_byte_cache_string);
5121 string_char_byte_cache_string = Qnil;
5122
5123 require_nesting_list = Qnil;
5124 staticpro (&require_nesting_list);
5125
5126 Fset (Qyes_or_no_p_history, Qnil);
5127
5128 DEFVAR_LISP ("features", Vfeatures,
5129 doc: /* A list of symbols which are the features of the executing Emacs.
5130 Used by `featurep' and `require', and altered by `provide'. */);
5131 Vfeatures = list1 (Qemacs);
5132 DEFSYM (Qsubfeatures, "subfeatures");
5133 DEFSYM (Qfuncall, "funcall");
5134
5135 #ifdef HAVE_LANGINFO_CODESET
5136 DEFSYM (Qcodeset, "codeset");
5137 DEFSYM (Qdays, "days");
5138 DEFSYM (Qmonths, "months");
5139 DEFSYM (Qpaper, "paper");
5140 #endif /* HAVE_LANGINFO_CODESET */
5141
5142 DEFVAR_BOOL ("use-dialog-box", use_dialog_box,
5143 doc: /* Non-nil means mouse commands use dialog boxes to ask questions.
5144 This applies to `y-or-n-p' and `yes-or-no-p' questions asked by commands
5145 invoked by mouse clicks and mouse menu items.
5146
5147 On some platforms, file selection dialogs are also enabled if this is
5148 non-nil. */);
5149 use_dialog_box = 1;
5150
5151 DEFVAR_BOOL ("use-file-dialog", use_file_dialog,
5152 doc: /* Non-nil means mouse commands use a file dialog to ask for files.
5153 This applies to commands from menus and tool bar buttons even when
5154 they are initiated from the keyboard. If `use-dialog-box' is nil,
5155 that disables the use of a file dialog, regardless of the value of
5156 this variable. */);
5157 use_file_dialog = 1;
5158
5159 defsubr (&Sidentity);
5160 defsubr (&Srandom);
5161 defsubr (&Slength);
5162 defsubr (&Ssafe_length);
5163 defsubr (&Sstring_bytes);
5164 defsubr (&Sstring_equal);
5165 defsubr (&Scompare_strings);
5166 defsubr (&Sstring_lessp);
5167 defsubr (&Sstring_numeric_lessp);
5168 defsubr (&Sstring_collate_lessp);
5169 defsubr (&Sstring_collate_equalp);
5170 defsubr (&Sappend);
5171 defsubr (&Sconcat);
5172 defsubr (&Svconcat);
5173 defsubr (&Scopy_sequence);
5174 defsubr (&Sstring_make_multibyte);
5175 defsubr (&Sstring_make_unibyte);
5176 defsubr (&Sstring_as_multibyte);
5177 defsubr (&Sstring_as_unibyte);
5178 defsubr (&Sstring_to_multibyte);
5179 defsubr (&Sstring_to_unibyte);
5180 defsubr (&Scopy_alist);
5181 defsubr (&Ssubstring);
5182 defsubr (&Ssubstring_no_properties);
5183 defsubr (&Snthcdr);
5184 defsubr (&Snth);
5185 defsubr (&Selt);
5186 defsubr (&Smember);
5187 defsubr (&Smemq);
5188 defsubr (&Smemql);
5189 defsubr (&Sassq);
5190 defsubr (&Sassoc);
5191 defsubr (&Srassq);
5192 defsubr (&Srassoc);
5193 defsubr (&Sdelq);
5194 defsubr (&Sdelete);
5195 defsubr (&Snreverse);
5196 defsubr (&Sreverse);
5197 defsubr (&Ssort);
5198 defsubr (&Splist_get);
5199 defsubr (&Sget);
5200 defsubr (&Splist_put);
5201 defsubr (&Sput);
5202 defsubr (&Slax_plist_get);
5203 defsubr (&Slax_plist_put);
5204 defsubr (&Seql);
5205 defsubr (&Sequal);
5206 defsubr (&Sequal_including_properties);
5207 defsubr (&Sfillarray);
5208 defsubr (&Sclear_string);
5209 defsubr (&Snconc);
5210 defsubr (&Smapcar);
5211 defsubr (&Smapc);
5212 defsubr (&Smapconcat);
5213 defsubr (&Syes_or_no_p);
5214 defsubr (&Sload_average);
5215 defsubr (&Sfeaturep);
5216 defsubr (&Srequire);
5217 defsubr (&Sprovide);
5218 defsubr (&Splist_member);
5219 defsubr (&Swidget_put);
5220 defsubr (&Swidget_get);
5221 defsubr (&Swidget_apply);
5222 defsubr (&Sbase64_encode_region);
5223 defsubr (&Sbase64_decode_region);
5224 defsubr (&Sbase64_encode_string);
5225 defsubr (&Sbase64_decode_string);
5226 defsubr (&Smd5);
5227 defsubr (&Ssecure_hash);
5228 defsubr (&Slocale_info);
5229
5230 hashtest_eq.name = Qeq;
5231 hashtest_eq.user_hash_function = Qnil;
5232 hashtest_eq.user_cmp_function = Qnil;
5233 hashtest_eq.cmpfn = 0;
5234 hashtest_eq.hashfn = hashfn_eq;
5235
5236 hashtest_eql.name = Qeql;
5237 hashtest_eql.user_hash_function = Qnil;
5238 hashtest_eql.user_cmp_function = Qnil;
5239 hashtest_eql.cmpfn = cmpfn_eql;
5240 hashtest_eql.hashfn = hashfn_eql;
5241
5242 hashtest_equal.name = Qequal;
5243 hashtest_equal.user_hash_function = Qnil;
5244 hashtest_equal.user_cmp_function = Qnil;
5245 hashtest_equal.cmpfn = cmpfn_equal;
5246 hashtest_equal.hashfn = hashfn_equal;
5247 }