Source:NetHack 5.0.0/src/hacklib.c

From NetHackWiki
Jump to navigation Jump to search

Below is the full text to hacklib.c from the source code of NetHack 5.0.0. To link to a particular line, write [[Source:NetHack 5.0.0/src/hacklib.c#line12]], for example.

The NetHack General Public License applies to screenshots, source code and other content from NetHack.

This content was modified from the original NetHack source code distribution (by splitting up NetHack content between wiki pages, and possibly further editing). See the page history for a list of who changed it, and on what dates.

1. /* NetHack 5.0	hacklib.c	$NHDT-Date: 1706213796 2024/01/25 20:16:36 $  $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.116 $ */
2. /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
3. /*-Copyright (c) Michael Allison, 2007. */
4. /* Copyright (c) Robert Patrick Rankin, 1991                      */
5. /* NetHack may be freely redistributed.  See license for details. */
6. 
7. #include "hack.h" /* for config.h+extern.h */
8. 
9. /*=
10.     Assorted 'small' utility routines.  They're virtually independent of
11.     NetHack.
12. 
13.       return type     routine name    argument type(s)
14.         boolean         digit           (char)
15.         boolean         letter          (char)
16.         char            highc           (char)
17.         char            lowc            (char)
18.         char *          lcase           (char *)
19.         char *          ucase           (char *)
20.         char *          upstart         (char *)
21.         char *          upwords         (char *)
22.         char *          mungspaces      (char *)
23.         char *          trimspaces      (char *)
24.         char *          strip_newline   (char *)
25.         char *          stripchars      (char *, const char *, const char *)
26.         char *          stripdigits     (char *)
27.         char *          eos             (char *)
28.         const char *    c_eos           (const char *)
29.         boolean         str_start_is    (const char *, const char *, boolean)
30.         boolean         str_end_is      (const char *, const char *)
31.         int             str_lines_maxlen (const char *)
32.         char *          strkitten       (char *,char)
33.         void            copynchars      (char *,const char *,int)
34.         char            chrcasecpy      (int,int)
35.         char *          strcasecpy      (char *,const char *)
36.         char *          s_suffix        (const char *)
37.         char *          ing_suffix      (const char *)
38.         char *          xcrypt          (const char *, char *)
39.         boolean         onlyspace       (const char *)
40.         char *          tabexpand       (char *)
41.         char *          visctrl         (char)
42.         char *          strsubst        (char *, const char *, const char *)
43.         int             strNsubst       (char *,const char *,const char *,int)
44.         const char *    findword        (const char *,const char *,int,boolean)
45.         const char *    ordin           (int)
46.         char *          sitoa           (int)
47.         int             sgn             (int)
48.         int             distmin         (coordxy, coordxy, coordxy, coordxy)
49.         int             dist2           (coordxy, coordxy, coordxy, coordxy)
50.         boolean         online2         (coordxy, coordxy)
51.         int             strncmpi        (const char *, const char *, int)
52.         char *          strstri         (const char *, const char *)
53.         boolean         fuzzymatch      (const char *, const char *,
54.                                          const char *, boolean)
55.         int             swapbits        (int, int, int)
56.         void            nh_snprintf     (const char *, int, char *, size_t,
57.                                          const char *, ...)
58. =*/
59. 
60. /* is 'c' a digit? */
61. boolean
62. digit(char c)
63. {
64.     return (boolean) ('0' <= c && c <= '9');
65. }
66. 
67. /* is 'c' a letter?  note: '@' classed as letter */
68. boolean
69. letter(char c)
70. {
71.     return (boolean) ('@' <= c && c <= 'Z') || ('a' <= c && c <= 'z');
72. }
73. 
74. /* force 'c' into uppercase */
75. char
76. highc(char c)
77. {
78.     return (char) (('a' <= c && c <= 'z') ? (c & ~040) : c);
79. }
80. 
81. /* force 'c' into lowercase */
82. char
83. lowc(char c)
84. {
85.     return (char) (('A' <= c && c <= 'Z') ? (c | 040) : c);
86. }
87. 
88. /* convert a string into all lowercase */
89. char *
90. lcase(char *s)
91. {
92.     char *p;
93. 
94.     for (p = s; *p; p++)
95.         if ('A' <= *p && *p <= 'Z')
96.             *p |= 040;
97.     return s;
98. }
99. 
100. /* convert a string into all uppercase */
101. char *
102. ucase(char *s)
103. {
104.     char *p;
105. 
106.     for (p = s; *p; p++)
107.         if ('a' <= *p && *p <= 'z')
108.             *p &= ~040;
109.     return s;
110. }
111. 
112. /* convert first character of a string to uppercase */
113. char *
114. upstart(char *s)
115. {
116.     if (s)
117.         *s = highc(*s);
118.     return s;
119. }
120. 
121. /* capitalize first letter of every word in a string (in place) */
122. char *
123. upwords(char *s)
124. {
125.     char *p;
126.     boolean space = TRUE;
127. 
128.     for (p = s; *p; p++)
129.         if (*p == ' ') {
130.             space = TRUE;
131.         } else if (space && letter(*p)) {
132.             *p = highc(*p);
133.             space = FALSE;
134.         } else {
135.             space = FALSE;
136.         }
137.     return s;
138. }
139. 
140. /* remove excess whitespace from a string buffer (in place) */
141. char *
142. mungspaces(char *bp)
143. {
144.     char c, *p, *p2;
145.     boolean was_space = TRUE;
146. 
147.     for (p = p2 = bp; (c = *p) != '\0'; p++) {
148.         if (c == '\n')
149.             break; /* treat newline the same as end-of-string */
150.         if (c == '\t')
151.             c = ' ';
152.         if (c != ' ' || !was_space)
153.             *p2++ = c;
154.         was_space = (c == ' ');
155.     }
156.     if (was_space && p2 > bp)
157.         p2--;
158.     *p2 = '\0';
159.     return bp;
160. }
161. 
162. /* skip leading whitespace; remove trailing whitespace, in place */
163. char *
164. trimspaces(char *txt)
165. {
166.     char *end;
167. 
168.     /* leading whitespace will remain in the buffer */
169.     while (*txt == ' ' || *txt == '\t')
170.         txt++;
171.     end = eos(txt);
172.     while (--end >= txt && (*end == ' ' || *end == '\t'))
173.         *end = '\0';
174. 
175.     return txt;
176. }
177. 
178. /* remove \n from end of line; remove \r too if one is there */
179. char *
180. strip_newline(char *str)
181. {
182.     char *p = strrchr(str, '\n');
183. 
184.     if (p) {
185.         if (p > str && *(p - 1) == '\r')
186.             --p;
187.         *p = '\0';
188.     }
189.     return str;
190. }
191. 
192. /* return the end of a string (pointing at '\0') */
193. char *
194. eos(char *s)
195. {
196.     while (*s)
197.         s++; /* s += strlen(s); */
198.     return s;
199. }
200. 
201. /* version of eos() which takes a const* arg and returns that result */
202. const char *
203. c_eos(const char *s)
204. {
205.     while (*s)
206.         s++; /* s += strlen(s); */
207.     return s;
208. }
209. 
210. /* determine whether 'str' starts with 'chkstr', possibly ignoring case;
211.  * panics on huge strings */
212. boolean
213. str_start_is(
214.     const char *str,
215.     const char *chkstr,
216.     boolean caseblind)
217. {
218.     char t1, t2;
219.     int n = LARGEST_INT;
220. 
221.     while (--n) {
222.         if (!*str)
223.             return (*chkstr == 0); /* chkstr >= str */
224.         else if (!*chkstr)
225.             return TRUE; /* chkstr < str */
226.         t1 = caseblind ? lowc(*str) : *str;
227.         t2 = caseblind ? lowc(*chkstr) : *chkstr;
228.         str++, chkstr++;
229.         if (t1 != t2)
230.             return FALSE;
231.     }
232. #if 0
233.     if (n == 0)
234.         panic("string too long");
235. #endif
236.     return TRUE;
237. }
238. 
239. /* determine whether 'str' ends in 'chkstr' */
240. boolean
241. str_end_is(const char *str, const char *chkstr)
242. {
243.     int clen = (int) strlen(chkstr);
244. 
245.     if ((int) strlen(str) >= clen)
246.         return (boolean) (!strncmp(eos((char *) str) - clen, chkstr, clen));
247.     return FALSE;
248. }
249. 
250. /* return max line length from buffer comprising newline-separated strings */
251. int
252. str_lines_maxlen(const char *str)
253. {
254.     const char *s1, *s2;
255.     int len, max_len = 0;
256. 
257.     s1 = str;
258.     while (s1 && *s1) {
259.         s2 = strchr(s1, '\n');
260.         if (s2) {
261.             len = (int) (s2 - s1);
262.             s1 = s2 + 1;
263.         } else {
264.             len = (int) strlen(s1);
265.             s1 = (char *) 0;
266.         }
267.         if (len > max_len)
268.             max_len = len;
269.     }
270. 
271.     return max_len;
272. }
273. 
274. /* append a character to a string (in place): strcat(s, {c,'\0'}); */
275. char *
276. strkitten(char *s, char c)
277. {
278.     char *p = eos(s);
279. 
280.     *p++ = c;
281.     *p = '\0';
282.     return s;
283. }
284. 
285. /* truncating string copy */
286. void
287. copynchars(char *dst, const char *src, int n)
288. {
289.     /* copies at most n characters, stopping sooner if terminator reached;
290.        treats newline as input terminator; unlike strncpy, always supplies
291.        '\0' terminator so dst must be able to hold at least n+1 characters */
292.     while (n > 0 && *src != '\0' && *src != '\n') {
293.         *dst++ = *src++;
294.         --n;
295.     }
296.     *dst = '\0';
297. }
298. 
299. /* convert char nc into oc's case; mostly used by strcasecpy */
300. char
301. chrcasecpy(int oc, int nc)
302. {
303. #if 0 /* this will be necessary if we switch to <ctype.h> */
304.     oc = (int) (unsigned char) oc;
305.     nc = (int) (unsigned char) nc;
306. #endif
307.     if ('a' <= oc && oc <= 'z') {
308.         /* old char is lower case; if new char is upper case, downcase it */
309.         if ('A' <= nc && nc <= 'Z')
310.             nc += 'a' - 'A'; /* lowc(nc) */
311.     } else if ('A' <= oc && oc <= 'Z') {
312.         /* old char is upper case; if new char is lower case, upcase it */
313.         if ('a' <= nc && nc <= 'z')
314.             nc += 'A' - 'a'; /* highc(nc) */
315.     }
316.     return (char) nc;
317. }
318. 
319. /* overwrite string, preserving old chars' case;
320.    for case-insensitive editions of makeplural() and makesingular();
321.    src might be shorter, same length, or longer than dst */
322. char *
323. strcasecpy(char *dst, const char *src)
324. {
325.     char *result = dst;
326.     int ic, oc, dst_exhausted = 0;
327. 
328.     /* while dst has characters, replace each one with corresponding
329.        character from src, converting case in the process if they differ;
330.        once dst runs out, propagate the case of its last character to any
331.        remaining src; if dst starts empty, it must be a pointer to the
332.        tail of some other string because we examine the char at dst[-1] */
333.     while ((ic = (int) *src++) != '\0') {
334.         if (!dst_exhausted && !*dst)
335.             dst_exhausted = 1;
336.         oc = (int) *(dst - dst_exhausted);
337.         *dst++ = chrcasecpy(oc, ic);
338.     }
339.     *dst = '\0';
340.     return result;
341. }
342. 
343. /* return a name converted to possessive */
344. char *
345. s_suffix(const char *s)
346. {
347.     static char buf[BUFSZ];
348. 
349.     Strcpy(buf, s);
350.     if (!strcmpi(buf, "it")) /* it -> its */
351.         Strcat(buf, "s");
352.     else if (!strcmpi(buf, "you")) /* you -> your */
353.         Strcat(buf, "r");
354.     else if (*(eos(buf) - 1) == 's') /* Xs -> Xs' */
355.         Strcat(buf, "'");
356.     else /* X -> X's */
357.         Strcat(buf, "'s");
358.     return buf;
359. }
360. 
361. /* construct a gerund (a verb formed by appending "ing" to a noun) */
362. char *
363. ing_suffix(const char *s)
364. {
365.     static const char vowel[] = "aeiouwy";
366.     static char buf[BUFSZ];
367.     char onoff[10];
368.     char *p;
369. 
370.     Strcpy(buf, s);
371.     p = eos(buf);
372.     onoff[0] = *p = *(p + 1) = '\0';
373.     if ((p >= &buf[3] && !strcmpi(p - 3, " on"))
374.         || (p >= &buf[4] && !strcmpi(p - 4, " off"))
375.         || (p >= &buf[5] && !strcmpi(p - 5, " with"))) {
376.         p = strrchr(buf, ' ');
377.         Strcpy(onoff, p);
378.         *p = '\0';
379.     }
380.     if (p >= &buf[2] && !strcmpi(p - 2, "er")) { /* slither + ing */
381.         /* nothing here */
382.     } else if (p >= &buf[3] && !strchr(vowel, *(p - 1))
383.         && strchr(vowel, *(p - 2)) && !strchr(vowel, *(p - 3))) {
384.         /* tip -> tipp + ing */
385.         *p = *(p - 1);
386.         *(p + 1) = '\0';
387.     } else if (p >= &buf[2] && !strcmpi(p - 2, "ie")) { /* vie -> vy + ing */
388.         *(p - 2) = 'y';
389.         *(p - 1) = '\0';
390.     } else if (p >= &buf[1] && *(p - 1) == 'e') /* grease -> greas + ing */
391.         *(p - 1) = '\0';
392.     Strcat(buf, "ing");
393.     if (onoff[0])
394.         Strcat(buf, onoff);
395.     return buf;
396. }
397. 
398. /* trivial text encryption routine (see makedefs) */
399. char *
400. xcrypt(const char *str, char *buf)
401. {
402.     const char *p;
403.     char *q;
404.     int bitmask;
405. 
406.     for (bitmask = 1, p = str, q = buf; *p; q++) {
407.         *q = *p++;
408.         if (*q & (32 | 64))
409.             *q ^= bitmask;
410.         if ((bitmask <<= 1) >= 32)
411.             bitmask = 1;
412.     }
413.     *q = '\0';
414.     return buf;
415. }
416. 
417. /* is a string entirely whitespace? */
418. boolean
419. onlyspace(const char *s)
420. {
421.     for (; *s; s++)
422.         if (*s != ' ' && *s != '\t')
423.             return FALSE;
424.     return TRUE;
425. }
426. 
427. /* expand tabs into proper number of spaces (in place) */
428. char *
429. tabexpand(
430.     char *sbuf) /* assumed to be [BUFSZ] but can be smaller provided that
431.                  * expanded string fits; expansion bigger than BUFSZ-1
432.                  * will be truncated */
433. {
434.     char buf[BUFSZ + 10];
435.     char *bp, *s = sbuf;
436.     int idx;
437. 
438.     if (!*s)
439.         return sbuf;
440.     for (bp = buf, idx = 0; *s; s++) {
441.         if (*s == '\t') {
442.             /*
443.              * clang-8's optimizer at -Os has been observed to mis-compile
444.              * this code.  Symptom is nethack getting stuck in an apparent
445.              * infinite loop (or perhaps just an extremely long one) when
446.              * examining data.base entries.
447.              * clang-9 doesn't exhibit this problem.  [Was the incorrect
448.              * optimization fixed or just disabled?]
449.              */
450.             do
451.                 *bp++ = ' ';
452.             while (++idx % 8);
453.         } else {
454.             *bp++ = *s;
455.             ++idx;
456.         }
457.         if (idx >= BUFSZ) {
458.             bp = &buf[BUFSZ - 1];
459.             break;
460.         }
461.     }
462.     *bp = 0;
463.     return strcpy(sbuf, buf);
464. }
465. 
466. #define VISCTRL_NBUF 5
467. /* make a displayable string from a character */
468. char *
469. visctrl(char c)
470. {
471.     static char visctrl_bufs[VISCTRL_NBUF][5];
472.     static int nbuf = 0;
473.     int i = 0;
474.     char *ccc = visctrl_bufs[nbuf];
475.     nbuf = (nbuf + 1) % VISCTRL_NBUF;
476. 
477.     if ((uchar) c & 0200) {
478.         ccc[i++] = 'M';
479.         ccc[i++] = '-';
480.     }
481.     c &= 0177;
482.     if (c < 040) {
483.         ccc[i++] = '^';
484.         ccc[i++] = c | 0100; /* letter */
485.     } else if (c == 0177) {
486.         ccc[i++] = '^';
487.         ccc[i++] = c & ~0100; /* '?' */
488.     } else {
489.         ccc[i++] = c; /* printable character */
490.     }
491.     ccc[i] = '\0';
492.     return ccc;
493. }
494. 
495. /* strip all the chars in stuff_to_strip from orig */
496. /* caller is responsible for ensuring that bp is a
497.    valid pointer to a BUFSZ buffer */
498. char *
499. stripchars(
500.     char *bp,
501.     const char *stuff_to_strip,
502.     const char *orig)
503. {
504.     int i = 0;
505.     char *s = bp;
506. 
507.     while (*orig && i < (BUFSZ - 1)) {
508.         if (!strchr(stuff_to_strip, *orig)) {
509.             *s++ = *orig;
510.             i++;
511.         }
512.         orig++;
513.     }
514.     *s = '\0';
515. 
516.     return bp;
517. }
518. 
519. /* remove digits from string */
520. char *
521. stripdigits(char *s)
522. {
523.     char *s1, *s2;
524. 
525.     for (s1 = s2 = s; *s1; s1++)
526.         if (*s1 < '0' || *s1 > '9')
527.             *s2++ = *s1;
528.     *s2 = '\0';
529. 
530.     return s;
531. }
532. 
533. /* substitute a word or phrase in a string (in place);
534.    caller is responsible for ensuring that bp points to big enough buffer */
535. char *
536. strsubst(
537.     char *bp,
538.     const char *orig,
539.     const char *replacement)
540. {
541.     char *found, buf[BUFSZ];
542.     /* [this could be replaced by strNsubst(bp, orig, replacement, 1)] */
543. 
544.     found = strstr(bp, orig);
545.     if (found) {
546.         Strcpy(buf, found + strlen(orig));
547.         Strcpy(found, replacement);
548.         Strcat(bp, buf);
549.     }
550.     return bp;
551. }
552. 
553. /* substitute the Nth occurrence of a substring within a string (in place);
554.    if N is 0, substitute all occurrences; returns the number of substitutions;
555.    maximum output length is BUFSZ (BUFSZ-1 chars + terminating '\0') */
556. int
557. strNsubst(
558.     char *inoutbuf,   /* current string, and result buffer */
559.     const char *orig, /* old substring; if "", insert in front of Nth char */
560.     const char *replacement, /* new substring; if "", delete old substring */
561.     int n) /* which occurrence to replace; 0 => all */
562. {
563.     char *bp, *op, workbuf[BUFSZ];
564.     const char *rp;
565.     unsigned len = (unsigned) strlen(orig);
566.     int ocount = 0, /* number of times 'orig' has been matched */
567.         rcount = 0; /* number of substitutions made */
568. 
569.     for (bp = inoutbuf, op = workbuf; *bp && op < &workbuf[BUFSZ - 1]; ) {
570.         if ((!len || !strncmp(bp, orig, len)) && (++ocount == n || n == 0)) {
571.             /* Nth match found */
572.             for (rp = replacement; *rp && op < &workbuf[BUFSZ - 1]; )
573.                 *op++ = *rp++;
574.             ++rcount;
575.             if (len) {
576.                 bp += len; /* skip 'orig' */
577.                 continue;
578.             }
579.         }
580.         /* no match (or len==0) so retain current character */
581.         *op++ = *bp++;
582.     }
583.     if (!len && n == ocount + 1) {
584.         /* special case: orig=="" (!len) and n==strlen(inoutbuf)+1,
585.            insert in front of terminator (in other words, append);
586.            [when orig=="", ocount will have been incremented once for
587.            each input char] */
588.         for (rp = replacement; *rp && op < &workbuf[BUFSZ - 1]; )
589.             *op++ = *rp++;
590.         ++rcount;
591.     }
592.     if (rcount) {
593.         *op = '\0';
594.         Strcpy(inoutbuf, workbuf);
595.     }
596.     return rcount;
597. }
598. 
599. /* search for a word in a space-separated list; returns non-Null if found */
600. const char *
601. findword(
602.     const char *list,   /* string of space-separated words */
603.     const char *word,   /* word to try to find */
604.     int wordlen,        /* so that it isn't required to be \0 terminated */
605.     boolean ignorecase) /* T: case-blind, F: case-sensitive */
606. {
607.     const char *p = list;
608. 
609.     while (p) {
610.         while (*p == ' ')
611.             ++p;
612.         if (!*p)
613.             break;
614.         if ((ignorecase ? !strncmpi(p, word, wordlen)
615.                         : !strncmp(p, word, wordlen))
616.             && (p[wordlen] == '\0' || p[wordlen] == ' '))
617.             return p;
618.         p = strchr(p + 1, ' ');
619.     }
620.     return (const char *) 0;
621. }
622. 
623. /* return the ordinal suffix of a number */
624. const char *
625. ordin(int n)               /* note: should be non-negative */
626. {
627.     int dd = n % 10;
628. 
629.     return (dd == 0 || dd > 3 || (n % 100) / 10 == 1) ? "th"
630.                : (dd == 1) ? "st" : (dd == 2) ? "nd" : "rd";
631. }
632. 
633. DISABLE_WARNING_FORMAT_NONLITERAL  /* one compiler complains about
634.                                       result of ?: for format string */
635. 
636. /* make a signed digit string from a number */
637. char *
638. sitoa(int n)
639. {
640.     static char buf[13];
641. 
642.     Sprintf(buf, (n < 0) ? "%d" : "+%d", n);
643.     return buf;
644. }
645. 
646. RESTORE_WARNING_FORMAT_NONLITERAL
647. 
648. /* return the sign of a number: -1, 0, or 1 */
649. int
650. sgn(int n)
651. {
652.     return (n < 0) ? -1 : (n != 0);
653. }
654. 
655. /* distance between two points, in moves */
656. int
657. distmin(coordxy x0, coordxy y0, coordxy x1, coordxy y1)
658. {
659.     coordxy dx = x0 - x1, dy = y0 - y1;
660. 
661.     if (dx < 0)
662.         dx = -dx;
663.     if (dy < 0)
664.         dy = -dy;
665.     /*  The minimum number of moves to get from (x0,y0) to (x1,y1) is the
666.      *  larger of the [absolute value of the] two deltas.
667.      */
668.     return (dx < dy) ? dy : dx;
669. }
670. 
671. /* square of Euclidean distance between pair of pts */
672. int
673. dist2(coordxy x0, coordxy y0, coordxy x1, coordxy y1)
674. {
675.     coordxy dx = x0 - x1, dy = y0 - y1;
676. 
677.     return dx * dx + dy * dy;
678. }
679. 
680. /* integer square root function without using floating point */
681. int
682. isqrt(int val)
683. {
684.     int rt = 0;
685.     int odd = 1;
686.     /*
687.      * This could be replaced by a faster algorithm, but has not been because:
688.      * + the simple algorithm is easy to read;
689.      * + this algorithm does not require 64-bit support;
690.      * + in current usage, the values passed to isqrt() are not really that
691.      *   large, so the performance difference is negligible;
692.      * + isqrt() is used in only few places, which are not bottle-necks.
693.      */
694.     while (val >= odd) {
695.         val = val - odd;
696.         odd = odd + 2;
697.         rt = rt + 1;
698.     }
699.     return rt;
700. }
701. 
702. /* are two points lined up (on a straight line)? */
703. boolean
704. online2(coordxy x0, coordxy y0, coordxy x1, coordxy y1)
705. {
706.     int dx = x0 - x1, dy = y0 - y1;
707.     /*  If either delta is zero then they're on an orthogonal line,
708.      *  else if the deltas are equal (signs ignored) they're on a diagonal.
709.      */
710.     return (boolean) (!dy || !dx || dy == dx || dy == -dx);
711. }
712. 
713. #ifndef STRNCMPI
714. /* case-insensitive counted string comparison */
715. /*{ aka strncasecmp }*/
716. int
717. strncmpi(
718.     const char *s1, const char *s2,
719.     int n) /*(should probably be size_t, which is unsigned)*/
720. {
721.     char t1, t2;
722. 
723.     while (n--) {
724.         if (!*s2)
725.             return (*s1 != 0); /* s1 >= s2 */
726.         else if (!*s1)
727.             return -1; /* s1  < s2 */
728.         t1 = lowc(*s1++);
729.         t2 = lowc(*s2++);
730.         if (t1 != t2)
731.             return (t1 > t2) ? 1 : -1;
732.     }
733.     return 0; /* s1 == s2 */
734. }
735. #endif /* STRNCMPI */
736. 
737. #ifndef STRSTRI
738. /* case-insensitive substring search */
739. char *
740. strstri(const char *str, const char *sub)
741. {
742.     const char *s1, *s2;
743.     int i, k;
744. #define TABSIZ 0x20                  /* 0x40 would be case-sensitive */
745.     char tstr[TABSIZ], tsub[TABSIZ]; /* nibble count tables */
746. #if 0
747.     assert( (TABSIZ & ~(TABSIZ-1)) == TABSIZ ); /* must be exact power of 2 */
748.     assert( &lowc != 0 );                       /* can't be unsafe macro */
749. #endif
750. 
751.     /* special case: empty substring */
752.     if (!*sub)
753.         return (char *) str;
754. 
755.     /* do some useful work while determining relative lengths */
756.     for (i = 0; i < TABSIZ; i++)
757.         tstr[i] = tsub[i] = 0; /* init */
758.     for (k = 0, s1 = str; *s1; k++)
759.         tstr[*s1++ & (TABSIZ - 1)]++;
760.     for (s2 = sub; *s2; --k)
761.         tsub[*s2++ & (TABSIZ - 1)]++;
762. 
763.     /* evaluate the info we've collected */
764.     if (k < 0)
765.         return (char *) 0;       /* sub longer than str, so can't match */
766.     for (i = 0; i < TABSIZ; i++) /* does sub have more 'x's than str? */
767.         if (tsub[i] > tstr[i])
768.             return (char *) 0; /* match not possible */
769. 
770.     /* now actually compare the substring repeatedly to parts of the string */
771.     for (i = 0; i <= k; i++) {
772.         s1 = &str[i];
773.         s2 = sub;
774.         while (lowc(*s1++) == lowc(*s2++))
775.             if (!*s2)
776.                 return (char *) &str[i]; /* full match */
777.     }
778.     return (char *) 0; /* not found */
779. }
780. #endif /* STRSTRI */
781. 
782. /* compare two strings for equality, ignoring the presence of specified
783.    characters (typically whitespace) and possibly ignoring case */
784. boolean
785. fuzzymatch(
786.     const char *s1, const char *s2,
787.     const char *ignore_chars,
788.     boolean caseblind)
789. {
790.     char c1, c2;
791. 
792.     do {
793.         while ((c1 = *s1++) != '\0' && strchr(ignore_chars, c1) != 0)
794.             continue;
795.         while ((c2 = *s2++) != '\0' && strchr(ignore_chars, c2) != 0)
796.             continue;
797.         if (!c1 || !c2)
798.             break; /* stop when end of either string is reached */
799. 
800.         if (caseblind) {
801.             c1 = lowc(c1);
802.             c2 = lowc(c2);
803.         }
804.     } while (c1 == c2);
805. 
806.     /* match occurs only when the end of both strings has been reached */
807.     return (boolean) (!c1 && !c2);
808. }
809. 
810. /*
811.  * Time routines
812.  *
813.  * The time is used for:
814.  *  - seed for rand()
815.  *  - year on tombstone and yyyymmdd in record file
816.  *  - phase of the moon (various monsters react to NEW_MOON or FULL_MOON)
817.  *  - night and midnight (the undead are dangerous at midnight)
818.  *  - determination of what files are "very old"
819.  */
820. 
821. /* TIME_type: type of the argument to time(); we actually use &(time_t);
822.    you might need to define either or both of these to 'long *' in *conf.h */
823. #ifndef TIME_type
824. #define TIME_type time_t *
825. #endif
826. #ifndef LOCALTIME_type
827. #define LOCALTIME_type time_t *
828. #endif
829. 
830. /* swapbits(val, bita, bitb) swaps bit a with bit b in val */
831. int
832. swapbits(int val, int bita, int bitb)
833. {
834.     int tmp = ((val >> bita) & 1) ^ ((val >> bitb) & 1);
835. 
836.     return (val ^ ((tmp << bita) | (tmp << bitb)));
837. }
838. 
839. DISABLE_WARNING_FORMAT_NONLITERAL
840. 
841. /*
842.  * Wrap snprintf for use in the main code.
843.  *
844.  * Wrap reasons:
845.  *   1. If there are any platform issues, we have one spot to fix them -
846.  *      snprintf is a routine with a troubling history of bad implementations.
847.  *   2. Add cumbersome error checking in one spot.  Problems with text
848.  *      wrangling do not have to be fatal.
849.  *   3. Gcc 9+ will issue a warning unless the return value is used.
850.  *      Annoyingly, explicitly casting to void does not remove the error.
851.  *      So, use the result - see reason #2.
852.  */
853. void
854. nh_snprintf(
855.     const char *func UNUSED, int line UNUSED,
856.     char *str, size_t size,
857.     const char *fmt, ...)
858. {
859.     va_list ap;
860.     int n;
861. 
862.     va_start(ap, fmt);
863.     n = vsnprintf(str, size, fmt, ap);
864.     va_end(ap);
865.     if (n < 0 || (size_t) n >= size) { /* is there a problem? */
866. #if 0
867. TODO: add set_impossible(), impossible -> func pointer,
868.  test funcpointer before call
869.         impossible("snprintf %s: func %s, file line %d",
870.                    (n < 0) ? "format error" : "overflow",
871.                    func, line);
872. #endif
873.         str[size - 1] = '\0'; /* make sure it is nul terminated */
874.     }
875. }
876. 
877. RESTORE_WARNING_FORMAT_NONLITERAL
878. 
879. /* Unicode routines */
880. 
881. int
882. unicodeval_to_utf8str(int uval, uint8 *buffer, size_t bufsz)
883. {
884.     //    static uint8 buffer[7];
885.     uint8 *b = buffer;
886. 
887.     if (bufsz < 5)
888.         return 0;
889.     /*
890.      *   Binary   Hex        Comments
891.      *   0xxxxxxx 0x00..0x7F Only byte of a 1-byte character encoding
892.      *   10xxxxxx 0x80..0xBF Continuation byte : one of 1-3 bytes following
893.      * first 110xxxxx 0xC0..0xDF First byte of a 2-byte character encoding
894.      *   1110xxxx 0xE0..0xEF First byte of a 3-byte character encoding
895.      *   11110xxx 0xF0..0xF7 First byte of a 4-byte character encoding
896.      */
897.     *b = '\0';
898.     if (uval < 0x80) {
899.         *b++ = uval;
900.     } else if (uval < 0x800) {
901.         *b++ = 192 + uval / 64;
902.         *b++ = 128 + uval % 64;
903.     } else if (uval - 0xd800u < 0x800) {
904.         return 0;
905.     } else if (uval < 0x10000) {
906.         *b++ = 224 + uval / 4096;
907.         *b++ = 128 + uval / 64 % 64;
908.         *b++ = 128 + uval % 64;
909.     } else if (uval < 0x110000) {
910.         *b++ = 240 + uval / 262144;
911.         *b++ = 128 + uval / 4096 % 64;
912.         *b++ = 128 + uval / 64 % 64;
913.         *b++ = 128 + uval % 64;
914.     } else {
915.         return 0;
916.     }
917.     *b = '\0'; /* NUL terminate */
918.     return 1;
919. }
920. 
921. int
922. case_insensitive_comp(const char *s1, const char *s2)
923. {
924.     uchar u1, u2;
925. 
926.     for (;; s1++, s2++) {
927.         u1 = (uchar) *s1;
928.         if (isupper(u1))
929.             u1 = (uchar) tolower(u1);
930.         u2 = (uchar) *s2;
931.         if (isupper(u2))
932.             u2 = (uchar) tolower(u2);
933.         if (u1 == '\0' || u1 != u2)
934.             break;
935.     }
936.     return u1 - u2;
937. }
938. 
939. #if defined(MACOS)
940. #define RETTYPE ssize_t
941. #else
942. #define RETTYPE int
943. #endif
944. 
945. boolean
946. copy_bytes(int ifd, int ofd)
947. {
948.     char buf[BUFSIZ];
949.     RETTYPE nfrom, nto;
950. 
951.     do {
952.         nto = 0;
953.         nfrom = read(ifd, buf, BUFSIZ);
954.         /* read can return -1 */
955.         if (nfrom >= 0 && nfrom <= BUFSIZ)
956.             nto = write(ofd, buf, nfrom);
957.         if (nto != nfrom || nfrom < 0)
958.             return FALSE;
959.     } while (nfrom == (RETTYPE) BUFSIZ);
960.     return TRUE;
961. }
962. #undef RETTYPE
963. 
964. #define MAX_D 5
965. struct datamodel_information {
966.     int sz[MAX_D];
967.     const char *datamodel;
968.     const char *dmplatform;
969. };
970. 
971. static struct datamodel_information dm[] = {
972.     { { (int) sizeof(short), (int) sizeof(int), (int) sizeof(long),
973.         (int) sizeof(long long), (int) sizeof(genericptr_t) },
974.       "", "" },
975.     { { 2, 4, 4, 8, 4 }, "ILP32LL64", "x86 32-bit" }, /* Windows or Unix */
976.     { { 2, 4, 4, 8, 8 }, "IL32LLP64", "Windows x64 64-bit" },
977.     { { 2, 4, 8, 8, 8 }, "I32LP64", "Unix 64-bit"}, 
978.     { { 2, 8, 8, 8, 8 }, "ILP64", "Unix ILP64"},      /* HAL, SPARC64 */
979. };
980. 
981. const char *
982. datamodel(int retidx)
983. {
984.     int i, j, matchcount;
985.     static const char *unknown = "Unknown";
986. 
987.     for (i = 1; i < SIZE(dm); ++i) {
988.         matchcount = 0;
989.         for (j = 0; j < MAX_D; ++j) {
990.             if (dm[0].sz[j] == dm[i].sz[j])
991.                 ++matchcount;
992.         }
993.         if (matchcount == MAX_D)
994.             return (retidx == 0) ? dm[i].datamodel : dm[i].dmplatform;
995.     }
996.     return unknown;
997. }
998. 
999. const char *
1000. what_datamodel_is_this(int retidx, int szshort, int szint, int szlong, int szll,
1001.                        int szptr)
1002. {
1003.     int i;
1004.     static const char *unknown = "Unknown";
1005. 
1006.     for (i = 1; i < SIZE(dm); ++i) {
1007.         if (szshort == dm[i].sz[0] && szint == dm[i].sz[1]
1008.             && szlong == dm[i].sz[2] && szll == dm[i].sz[3]
1009.             && szptr == dm[i].sz[4])
1010.             return (retidx == 0) ? dm[i].datamodel : dm[i].dmplatform;
1011.     }
1012.     return unknown;
1013. }
1014. #undef MAX_D
1015. /*hacklib.c*/