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