Source:NetHack 3.4.3/src/hacklib.c

From NetHackWiki
(Redirected from Source:Ref/digit)
Jump to: navigation, search

Below is the full text to src/hacklib.c from NetHack 3.4.3. To link to a particular line, write [[hacklib.c#line123]], for example.

The C functions in hacklib.c are old but still work. (Today's standard C libraries provide better replacements for some of them.) They provide miscellaneous features such as handling character strings and finding the phase of the moon. The setrandom code to seed the random number generator is also here.

Top of file[edit]

  1. /*	SCCS Id: @(#)hacklib.c	3.4	2002/12/13	*/
  2. /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
  3. /* Copyright (c) Robert Patrick Rankin, 1991		  */
  4. /* NetHack may be freely redistributed.  See license for details. */

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. /* We could include only config.h, except for the overlay definitions... */
  2. #include "hack.h"
  3. /*=
  4. Assorted 'small' utility routines.	They're virtually independent of
  5. NetHack, except that rounddiv may call panic().
  6.  
  7. return type     routine name    argument type(s)
  8. 	boolean		digit		(char)
  9. 	boolean		letter		(char)
  10. 	char		highc		(char)
  11. 	char		lowc		(char)
  12. 	char *		lcase		(char *)
  13. 	char *		upstart		(char *)
  14. 	char *		mungspaces	(char *)
  15. 	char *		eos		(char *)
  16. 	char *		strkitten	(char *,char)
  17. 	char *		s_suffix	(const char *)
  18. 	char *		xcrypt		(const char *, char *)
  19. 	boolean		onlyspace	(const char *)
  20. 	char *		tabexpand	(char *)
  21. 	char *		visctrl		(char)
  22. 	const char *	ordin		(int)
  23. 	char *		sitoa		(int)
  24. 	int		sgn		(int)
  25. 	int		rounddiv	(long, int)
  26. 	int		distmin		(int, int, int, int)
  27. 	int		dist2		(int, int, int, int)
  28. 	boolean		online2		(int, int)
  29. 	boolean		pmatch		(const char *, const char *)
  30. 	int		strncmpi	(const char *, const char *, int)
  31. 	char *		strstri		(const char *, const char *)
  32. 	boolean		fuzzymatch	(const char *,const char *,const char *,boolean)
  33. 	void		setrandom	(void)
  34. 	int		getyear		(void)
  35. 	char *		yymmdd		(time_t)
  36. 	long		yyyymmdd	(time_t)
  37. 	int		phase_of_the_moon	(void)
  38. 	boolean		friday_13th	(void)
  39. 	int		night		(void)
  40. 	int		midnight	(void)
  41. =*/
  42. #ifdef LINT
  43. # define Static		/* pacify lint */
  44. #else
  45. # define Static static
  46. #endif

digit[edit]

The digit function tests if the character is a digit, any of 0 to 9 in ASCII. If we rewrote NetHack today, we would instead use the isdigit function provided by ANSI C.

  1. #ifdef OVLB
  2. boolean
  3. digit(c)		/* is 'c' a digit? */
  4. char c;
  5. {
  6. return((boolean)('0' <= c && c <= '9'));
  7. }

letter[edit]

The letter function tests if the character is a letter. One would use isalpha, but this letter function has the caveat that @ (which is the character before A) in ASCII counts as a letter, in addition to the uppercase and lowercase letters. Thus most monsters are letters, but punctuation including lizards : and sea creatures ; are not letters.

  1. boolean
  2. letter(c)		/* is 'c' a letter?  note: '@' classed as letter */
  3. char c;
  4. {
  5. return((boolean)(('@' <= c && c <= 'Z') || ('a' <= c && c <= 'z')));
  6. }
  7. #endif /* OVLB */

highc[edit]

The highc function converts any character to uppercase. It converts 'a' to 'z' into uppercase, but copies any other character. Today we would use toupper in ANSI C.

  1. #ifdef OVL1
  2. char
  3. highc(c)			/* force 'c' into uppercase */
  4. char c;
  5. {
  6. return((char)(('a' <= c && c <= 'z') ? (c & ~040) : c));
  7. }

lowc[edit]

The lowc function converts any character to lowercase, the opposite but not the inverse of highc. Today we would use tolower in ANSI C.

  1. char
  2. lowc(c)			/* force 'c' into lowercase */
  3. char c;
  4. {
  5. return((char)(('A' <= c && c <= 'Z') ? (c | 040) : c));
  6. }
  7. #endif /* OVL1 */

lcase[edit]

The lcase function converts a string buffer to lowercase in place, by overwriting not copying the string. To follow ANSI C, we could rewrite this using tolower.

  1. #ifdef OVLB
  2. char *
  3. lcase(s)		/* convert a string into all lowercase */
  4. char *s;
  5. {
  6. register char *p;
  7.  
  8. for (p = s; *p; p++)
  9. 	if ('A' <= *p && *p <= 'Z') *p |= 040;
  10. return s;
  11. }

The rewritten version would be:

/* not part of hacklib.c */
#include <ctype.h>
char *
lcase(char *s)
{
    char* p;
    for(p = s; *p; p++)
	*p = tolower(*p);
    return s;
}

The old version works if the character set is ASCII, and might be more efficient if the C compiler does not optimise well. The rewritten version is easier to understand, but there is no reason for us to replace the old lcase function that already does best.

upstart[edit]

The upstart function uppercases the first letter of a string buffer in place (by overwriting and not copying). We need this when placing nouns for monsters like "it" and "the newt" at the beginning of a sentence.

  1. char *
  2. upstart(s)		/* convert first character of a string to uppercase */
  3. char *s;
  4. {
  5. if (s) *s = highc(*s);
  6. return s;
  7. }

The if statement upon line 101 ensures that upstart((char *)0) does not dereference a null pointer. Though it is best to be safe, this check was probably unnecessary because in general we should only pass '\0'-terminated strings to functions like these.

mungspaces[edit]

The mungspaces function condenses each group of consecutive spaces or tabs (of a string buffer) into a single space in place (by overwriting and not copying). It also trims the spaces and tabs from the beginning and end of the buffer.

  1. /* remove excess whitespace from a string buffer (in place) */
  2. char *
  3. mungspaces(bp)
  4. char *bp;
  5. {
  6. register char c, *p, *p2;
  7. boolean was_space = TRUE;
  8.  
  9. for (p = p2 = bp; (c = *p) != '\0'; p++) {
  10. 	if (c == '\t') c = ' ';
  11. 	if (c != ' ' || !was_space) *p2++ = c;
  12. 	was_space = (c == ' ');
  13. }
  14. if (was_space && p2 > bp) p2--;
  15. *p2 = '\0';
  16. return bp;
  17. }
  18.  
  19. #endif /* OVLB */

To make that code easier to read, here is a pretty version:

/* not part of hacklib.c */
char *
mungspaces(char *bp)
{
    char c, *p, *p2;
    boolean was_space = TRUE; /* trim beginning of string */

    p = p2 = bp;
    while ((c = *p) != '\0') { /* until p is end of string */
	if (c == '\t') c = ' ';
	if (c != ' ' || !was_space) {
	    *p2 = c; /* copy it */
	    p2++;
	}
	was_space = (c == ' ');
	p++;
    }

    if (was_space && p2 > bp) p2--; /* trim end of string */
    *p2 = '\0';
    return bp;
}

The mungspaces function is slightly less safe than the upstart function because mungspaces((char *)0) will dereference the null pointer. However mungspaces("") will work because the p2 > bp prevents us from trying to write a '\0' before the start of the buffer.

eos[edit]

Given some string, the eos function returns a pointer to the '\0' that terminates it.

  1. #ifdef OVL0
  2. char *
  3. eos(s)			/* return the end of a string (pointing at '\0') */
  4. register char *s;
  5. {
  6. while (*s) s++;	/* s += strlen(s); */
  7. return s;
  8. }

As the comment on line 130 shows, one could just do s += strlen(s). Someone must have thought that it was a waste of performance to count the number of times we do s++ as strlen would do. Some C compilers will optimise when they see strlen, but the developers wrote NetHack for older compilers.

strkitten[edit]

The strkitten function is a baby version of strcat that has less experience points and a weaker attack; see kitten, cat.

Actually, strkitten concatenates a single character to the end of a string. Like the strcat, the strkitten modifies the string being appended to. This function uses the eos function defined above.

  1. /* strcat(s, {c,'\0'}); */
  2. char *
  3. strkitten(s, c)		/* append a character to a string (in place) */
  4. char *s;
  5. char c;
  6. {
  7. char *p = eos(s);
  8.  
  9. *p++ = c;
  10. *p = '\0';
  11. return s;
  12. }

It is important to not use the strkitten function if your buffer does not have room for one more character!

s_suffix[edit]

The s_suffix function converts a string (typically naming a monster) to the possessive form, for example gnome to gnome's. Unlike many of the above functions, this one creates a new string instead of modifying the original string in place.

  1. char *
  2. s_suffix(s)		/* return a name converted to possessive */
  3. const char *s;
  4. {
  5. Static char buf[BUFSZ];
  6.  
  7. Strcpy(buf, s);
  8. if(!strcmpi(buf, "it"))
  9. 	Strcat(buf, "s");
  10. else if(*(eos(buf)-1) == 's')
  11. 	Strcat(buf, "'");
  12. else
  13. 	Strcat(buf, "'s");
  14. return buf;
  15. }

From the above code, we determine the following rules:

  • it has s appended (as it to its, It to Its)
  • names ending in s have apostrophe appended (as "Orcus" to "Orcus'")
  • other names have s and apostrophe appended (as the gnome to the gnome's)

Unlike strcpy, this s_suffix function does not take a buffer for the new string as a parameter. Instead, s_suffix places the posessive string in its own static buffer. This has two consequences:

  • String longer than BUFSZ-1 would overflow, so we must not use very long names.
  • We can have only one possessive noun at each time. This translates the rule that whenever we call pline or any of its variants in pline.c, we can use s_suffix only once, for example "You eat the gnome's brain!" (uhitm.c#line1537) Using a second possessive from a different function like Your or mhis (a macro in you.h) does not count, for example "The gnome's helmet blocks your attack to her head!"

Programmers that use languages with garbage collection (as in Java or Perl) would write s_suffix to dynamically allocate the buffer containing the possessive noun, and not need to later free it.

xcrypt[edit]

The xcrypt function decodes the Oracle messages and rumors stored in NetHack's playground. When building NetHack, makedefs hid that information so that players looking in the playground would not become spoiled. Though the cipher is symmetric (so that encoding and decoding use the same function), makedefs has its own copy of the xcrypt function.

You pass the input string as the first argument str and an output buffer as the second argument buf; this is the reverse of the order that you would expect from strcpy and memcpy.

  1. char *
  2. xcrypt(str, buf)	/* trivial text encryption routine (see makedefs) */
  3. const char *str;
  4. char *buf;
  5. {
  6. register const char *p;
  7. register char *q;
  8. register int bitmask;
  9.  
  10. for (bitmask = 1, p = str, q = buf; *p; q++) {
  11. 	*q = *p++;
  12. 	if (*q & (32|64)) *q ^= bitmask;
  13. 	if ((bitmask <<= 1) >= 32) bitmask = 1;
  14. }
  15. *q = '\0';
  16. return buf;
  17. }
  18. #endif /* OVL0 */

As do some other symmetric ciphers, the xcrypt generates a stream of data, then exclusive-ors the generated stream with the ciphertext to decode it (or with the plaintext to encode it). Because xcrypt does not use a secret key to seed a secure random number generator, xcrypt provides only trivial security, though xcrypt does better than ROT13.

onlyspace[edit]

The onlyspace function tests if the string contains only spaces and tabs. The mungspaces function would transform such a string to the empty string "".

  1. #ifdef OVL2
  2. boolean
  3. onlyspace(s)		/* is a string entirely whitespace? */
  4. const char *s;
  5. {
  6. for (; *s; s++)
  7. 	if (*s != ' ' && *s != '\t') return FALSE;
  8. return TRUE;
  9. }
  10. #endif /* OVL2 */

tabexpand[edit]

The tabexpand function replaces tabs with spaces, as if the tab advanced to the next column and the colums were 8 characters wide. It does this expansion in place. (Actually, it does the expansion in its internal buffer, then copies the result overwriting the input buffer.)

The input buffer sbuf needs to be at least BUFSZ large to keep room for the expansion. The internal buffer char buf[BUFSZ] prevents tabexpand from handling longer expansions.

  1. #ifdef OVLB
  2. char *
  3. tabexpand(sbuf)		/* expand tabs into proper number of spaces */
  4. char *sbuf;
  5. {
  6. char buf[BUFSZ];
  7. register char *bp, *s = sbuf;
  8. register int idx;
  9.  
  10. if (!*s) return sbuf;
  11.  
  12. /* warning: no bounds checking performed */
  13. for (bp = buf, idx = 0; *s; s++)
  14. 	if (*s == '\t') {
  15. 	    do *bp++ = ' '; while (++idx % 8);
  16. 	} else {
  17. 	    *bp++ = *s;
  18. 	    idx++;
  19. 	}
  20. *bp = 0;
  21. return strcpy(sbuf, buf);
  22. }

The tabexpand function overflows if the expansion is larger than BUFSZ-1 characters. A string containing only 32 tabs would overflow the buffer when BUFSZ is 256. The comment upon line 204 warns that the function will not check against overflow, even though the programmer knew that buf holds only BUFSZ bytes.

NetHack uses tabexpand when displaying from files that contain tabs.

visctrl[edit]

The visctrl character formats an ASCII character as a visible string. Control characters are formatted like ^B by using a caret ^ and a bit flip. (This is exactly how many Unix commands (like cat -v) and Unix editors would display them.) All other characters are copied.

  1. char *
  2. visctrl(c)		/* make a displayable string from a character */
  3. char c;
  4. {
  5. Static char ccc[3];
  6.  
  7. c &= 0177;
  8.  
  9. ccc[2] = '\0';
  10. if (c < 040) {
  11. 	ccc[0] = '^';
  12. 	ccc[1] = c | 0100;	/* letter */
  13. } else if (c == 0177) {
  14. 	ccc[0] = '^';
  15. 	ccc[1] = c & ~0100;	/* '?' */
  16. } else {
  17. 	ccc[0] = c;		/* printable character */
  18. 	ccc[1] = '\0';
  19. }
  20. return ccc;
  21. }
  22. #endif /* OVLB */
Input Output
ASCII control characters from 0 to 31 (octal 0 to 040) caret and control character plus 64 (octoal 0100)
^@, ^A, ^B ... ^Y, ^Z, ^[, ^\, ^], ^^, ^_
ASCII delete character 127 (octal 0177) caret and question mark 63 (octal 077)
^?
all other characters, including spaces and characters above 127 (8-bit meta characters) copied from input

Because visctrl outputs into an internal buffer, we follow the rule of one control character per sentence fragment, similar to the rule for using s_suffix.

The BSD C library provides a function vis that does something similar. Upon BSD (but not most other platforms!), we could rewrite the visctrl function this way:

/* not part of hacklib.c */
#include <vis.h>
char *
visctrl(char c)
{
    static char ccc[3];
    vis(ccc, c, VIS_TAB | VIS_NL | VIS_NOSLASH, 0);
    return ccc;
}

The rewritten visctrl also formats meta-characters like M-B.

ordin[edit]

The ordin function returns the string constant "st" or "nd" or "rd" suffix for a number.

  1. #ifdef OVL2
  2. const char *
  3. ordin(n)		/* return the ordinal suffix of a number */
  4. int n;			/* note: should be non-negative */
  5. {
  6. register int dd = n % 10;
  7.  
  8. return (dd == 0 || dd > 3 || (n % 100) / 10 == 1) ? "th" :
  9. 	    (dd == 1) ? "st" : (dd == 2) ? "nd" : "rd";
  10. }
  11. #endif /* OVL2 */

The string from ordin does not include the number, but it should be easy to use pline or snprintf to print the number:

pline("%d%s", i, ordin(i));

sitoa[edit]

The sitoa function converts an integer to ASCII, including the sign. It uses sprintf with either "%d" or "+%d", including the + for any nonnegative number. (This should use snprintf and check for overflow, but older systems do not have snprintf and the INT_MIN of -2147483648 or INT_MAX of +2147483647 fit in 12 bytes.)

  1. #ifdef OVL1
  2. char *
  3. sitoa(n)		/* make a signed digit string from a number */
  4. int n;
  5. {
  6. Static char buf[13];
  7.  
  8. Sprintf(buf, (n < 0) ? "%d" : "+%d", n);
  9. return buf;
  10. }

The name of sitoa is short for signed integer to ascii. It is named for "itoa", the inverse of atoi. (There is no "itoa" function in NetHack or the C library.)

sgn[edit]

The sgn function extracts the sign from an integer, returning either -1 or 0 or 1. Though this is a common function (and there is a Wikipedia entry for sign function), it is not in the C library.

  1. int
  2. sgn(n)			/* return the sign of a number: -1, 0, or 1 */
  3. int n;
  4. {
  5. return (n < 0) ? -1 : (n != 0);
  6. }
  7. #endif /* OVL1 */

This could easily have been a macro function buried in global.h, like so many other simple functions from NetHack:

/* not in NetHack */
#define sgn(n) (((n) < 0) ? -1 : ((n) != 0))

rounddiv[edit]

The rounddiv function computes x divided by y, rounding the quotient toward the nearest integer, rounding multiples of 1/2 away from zero. For example,

  • rounddiv((long)4, 2) yields 2
  • rounddiv((long)-14, 3) yields 5
  • rounddiv((long)5, 2) yields 3
  • rounddiv((long)-5, 2) yields -3

NetHack has exactly one call to rounddiv; that is somewhere in eat.c.

  1. #ifdef OVLB
  2. int
  3. rounddiv(x, y)		/* calculate x/y, rounding as appropriate */
  4. long x;
  5. int  y;
  6. {
  7. int r, m;
  8. int divsgn = 1;
  9.  
  10. if (y == 0)
  11. 	panic("division by zero in rounddiv");
  12. else if (y < 0) {
  13. 	divsgn = -divsgn;  y = -y;
  14. }
  15. if (x < 0) {
  16. 	divsgn = -divsgn;  x = -x;
  17. }
  18. r = x / y;
  19. m = x % y;
  20. if (2*m >= y) r++;
  21.  
  22. return divsgn * r;
  23. }
  24. #endif /* OVLB */

The procedure is simple:

  1. If denominator y is zero, panic.
  2. Make x and y nonnegative, saving the sign in divsgn.
  3. Divide x by y to set quotient r.
  4. Compute x modulo y to set remainder m.
  5. If twice m is at least y, then add 1 to r (thus rounding it).
  6. Return divsgn times quotient r.

Today, one could use the ANSI C ldiv function integer division, however it rounds toward zero and is of no use to us.

A peculiar feature of rounddiv in NetHack is that it takes numerator x as a long but takes denominator y as an int and returns an int. It would be wrong to pass an int as x without widening it to a long. There is a (long) cast in the call to rounddiv from eat.c. (Today, everyone has ANSI C or ISO C prototypes, and the compiler will see long in the prototype and do a cast. On some systems, int and long have the same width.)

distmin[edit]

The distmin function computes the number of moves in the shortest path between two points in the dungeon, using the formula:

distmin[(x0,y0),(x1,y1)] = max[ |x0-x1|, |y0-y1| ]

Horizontal, vertical and diagonal moves each have a move of length one. If |x0-x1| > |y0-y1|, we need only horizontal and diagonal moves, so we count only |x0-x1| moves.

  1. #ifdef OVL0
  2. int
  3. distmin(x0, y0, x1, y1) /* distance between two points, in moves */
  4. int x0, y0, x1, y1;
  5. {
  6. register int dx = x0 - x1, dy = y0 - y1;
  7. if (dx < 0) dx = -dx;
  8. if (dy < 0) dy = -dy;
  9. /*  The minimum number of moves to get from (x0,y0) to (x1,y1) is the
  10. :  larger of the [absolute value of the] two deltas.
  11. */
  12. return (dx < dy) ? dy : dx;
  13. }

The mindist function gives a minimum distance in a sufficiently open dungeon, or with a cursor that ignores obstacles. In a dungeon that actually has walls, monsters, traps and other obstacles, an adventurer may need more moves.

dist2[edit]

The dist2 returns the distance squared between two points in the dungeon using Pythagoras' famous theorem.

  1. int
  2. dist2(x0, y0, x1, y1)	/* square of euclidean distance between pair of pts */
  3. int x0, y0, x1, y1;
  4. {
  5. register int dx = x0 - x1, dy = y0 - y1;
  6. return dx * dx + dy * dy;
  7. }

The returned distance is in square squares! We take the unit to be "squares", because each dungeon square has sides of length 1. Take the distance between two dungeon squares in squares, and multiply it by itself, squaring it, yielding square squares. This leads to the important corollary,

Some squares are not square.

To find the actual distance between two squares, we would need to take the square root. This would either involve floating-point arithmetic or the digging of a tree. The dist2 square squares are square enough for ordered comparisons.

Both distmin and dist2 have several uses throughout the source code of NetHack. Sometimes, two horizontal moves have as much length as two diagonal moves, but sometimes the diagonal moves have more length.

In fact, the 2 in dist2 does not refer to the squaring, but to the 2 points in the arguments. The hack.h file has a distu macro that supplies your position as one of the points.

online2[edit]

The online2 function answers the question, can I shoot you? If I am a kobold, but you the adventurer are not on the same horizontal, vertical or diagonal as me, then I will not throw my darts.

  1. boolean
  2. online2(x0, y0, x1, y1) /* are two points lined up (on a straight line)? */
  3. int x0, y0, x1, y1;
  4. {
  5. int dx = x0 - x1, dy = y0 - y1;
  6. /*  If either delta is zero then they're on an orthogonal line,
  7. *  else if the deltas are equal (signs ignored) they're on a diagonal.
  8. */
  9. return((boolean)(!dy || !dx || (dy == dx) || (dy + dx == 0)));	/* (dy == -dx) */
  10. }
  11.  
  12. #endif /* OVL0 */

The onlineu macro in hack.h supplies your position as one of the arguments.

pmatch[edit]

The pmatch is a simple pattern matcher that treats the characters * and ? like the Unix shell. That is, a * in the pattern matches any zero or more characters in the string, while a ? in the pattern matches any one character in the string.

NetHack rarely uses this function, but there are a few calls to pmatch in pager.c, pickup.c and sounds.c.

  1. #ifdef OVLB
  2.  
  3. boolean
  4. pmatch(patrn, strng)	/* match a string against a pattern */
  5. const char *patrn, *strng;
  6. {
  7. char s, p;
  8. /*
  9. :  Simple pattern matcher:  '*' matches 0 or more characters, '?' matches
  10. :  any single character.  Returns TRUE if 'strng' matches 'patrn'.
  11. */
  12. pmatch_top:
  13. s = *strng++;  p = *patrn++;	/* get next chars and pre-advance */
  14. if (!p)			/* end of pattern */
  15. 	return((boolean)(s == '\0'));		/* matches iff end of string too */
  16. else if (p == '*')		/* wildcard reached */
  17. 	return((boolean)((!*patrn || pmatch(patrn, strng-1)) ? TRUE :
  18. 		s ? pmatch(patrn-1, strng) : FALSE));
  19. else if (p != s && (p != '?' || !s))  /* check single character */
  20. 	return FALSE;		/* doesn't match */
  21. else				/* return pmatch(patrn, strng); */
  22. 	goto pmatch_top;	/* optimize tail recursion */
  23. }
  24. #endif /* OVLB */

The comments in the source explain how it works. The function returns either TRUE or FALSE, those constants having been defined in global.h. The goto statement of line 350, along with the ++ operators of 341, "optimize tail recursion" into iteration, though some compilers can also do this. A while loop or for loop might have made an easier read.

We could rewrite this function with the fnmatch function in the C libraries of Unix systems:

/* not part of NetHack */
#include <fnmatch.h>
#include <stdbool.h> /* C99 bool type */
bool pmatch(const char *patrn, const char *strng)
{
    int r;

    r = fnmatch(patrn, strng, FNM_NOESCAPE);
    if (r == FNM_NOMATCH)
	return false;
    else
	return true;
}

But then:

  • the square brackets [ and ] would also have special meanings in the pattern.
  • the function would not be portable.

strncmpi[edit]

  1. #ifdef OVL2
  2. #ifndef STRNCMPI
  3. int
  4. strncmpi(s1, s2, n)	/* case insensitive counted string comparison */
  5. register const char *s1, *s2;
  6. register int n; /*(should probably be size_t, which is usually unsigned)*/
  7. {					/*{ aka strncasecmp }*/
  8. register char t1, t2;
  9.  
  10. while (n--) {
  11. 	if (!*s2) return (*s1 != 0);	/* s1 >= s2 */
  12. 	else if (!*s1) return -1;	/* s1  < s2 */
  13. 	t1 = lowc(*s1++);
  14. 	t2 = lowc(*s2++);
  15. 	if (t1 != t2) return (t1 > t2) ? 1 : -1;
  16. }
  17. return 0;				/* s1 == s2 */
  18. }
  19. #endif	/* STRNCMPI */
  20. #endif /* OVL2 */

strncmpi() compares the first n characters of the two strings s1 and s2, ignoring case.

strstri[edit]

  1. #ifdef OVLB
  2. #ifndef STRSTRI
  3.  
  4. char *
  5. strstri(str, sub)	/* case insensitive substring search */
  6. const char *str;
  7. const char *sub;
  8. {
  9. register const char *s1, *s2;
  10. register int i, k;
  11. # define TABSIZ 0x20	/* 0x40 would be case-sensitive */
  12. char tstr[TABSIZ], tsub[TABSIZ];	/* nibble count tables */
  13. # if 0
  14. assert( (TABSIZ & ~(TABSIZ-1)) == TABSIZ ); /* must be exact power of 2 */
  15. assert( &lowc != 0 );			/* can't be unsafe macro */
  16. # endif
  17.  
  18. /* special case: empty substring */
  19. if (!*sub)	return (char *) str;
  20.  
  21. /* do some useful work while determining relative lengths */
  22. for (i = 0; i < TABSIZ; i++)  tstr[i] = tsub[i] = 0;	/* init */
  23. for (k = 0, s1 = str; *s1; k++)  tstr[*s1++ & (TABSIZ-1)]++;
  24. for (	s2 = sub; *s2; --k)  tsub[*s2++ & (TABSIZ-1)]++;
  25.  
  26. /* evaluate the info we've collected */
  27. if (k < 0)	return (char *) 0;  /* sub longer than str, so can't match */
  28. for (i = 0; i < TABSIZ; i++)	/* does sub have more 'x's than str? */
  29. 	if (tsub[i] > tstr[i])	return (char *) 0;  /* match not possible */
  30.  
  31. /* now actually compare the substring repeatedly to parts of the string */
  32. for (i = 0; i <= k; i++) {
  33. 	s1 = &str[i];
  34. 	s2 = sub;
  35. 	while (lowc(*s1++) == lowc(*s2++))
  36. 	    if (!*s2)  return (char *) &str[i];		/* full match */
  37. }
  38. return (char *) 0;	/* not found */
  39. }
  40. #endif	/* STRSTRI */

fuzzymatch[edit]

  1. /* compare two strings for equality, ignoring the presence of specified
  2. characters (typically whitespace) and possibly ignoring case */
  3. boolean
  4. fuzzymatch(s1, s2, ignore_chars, caseblind)
  5. const char *s1, *s2;
  6. const char *ignore_chars;
  7. boolean caseblind;
  8. {
  9. register char c1, c2;
  10.  
  11. do {
  12. 	while ((c1 = *s1++) != '\0' && index(ignore_chars, c1) != 0) continue;
  13. 	while ((c2 = *s2++) != '\0' && index(ignore_chars, c2) != 0) continue;
  14. 	if (!c1 || !c2) break;	/* stop when end of either string is reached */
  15.  
  16. 	if (caseblind) {
  17. 	    c1 = lowc(c1);
  18. 	    c2 = lowc(c2);
  19. 	}
  20. } while (c1 == c2);
  21.  
  22. /* match occurs only when the end of both strings has been reached */
  23. return (boolean)(!c1 && !c2);
  24. }
  25.  
  26. #endif /* OVLB */

Time routines[edit]

  1. #ifdef OVL2
  2.  
  3. /*
  4. * Time routines
  5. *
  6. * The time is used for:
  7. *	- seed for rand()
  8. *	- year on tombstone and yyyymmdd in record file
  9. *	- phase of the moon (various monsters react to NEW_MOON or FULL_MOON)
  10. *	- night and midnight (the undead are dangerous at midnight)
  11. *	- determination of what files are "very old"
  12. */
  13.  
  14. #if defined(AMIGA) && !defined(AZTEC_C) && !defined(__SASC_60) && !defined(_DCC) && !defined(__GNUC__)
  15. extern struct tm *FDECL(localtime,(time_t *));
  16. #endif
  17. static struct tm *NDECL(getlt);

setrandom[edit]

  1. void
  2. setrandom()
  3. {
  4. 	/* the types are different enough here that sweeping the different
  5. 	 * routine names into one via #defines is even more confusing
  6. 	 */
  7. #ifdef RANDOM	/* srandom() from sys/share/random.c */
  8. 	srandom((unsigned int) time((time_t *)0));
  9. #else
  10. # if defined(__APPLE__) || defined(BSD) || defined(LINUX) || defined(ULTRIX) || defined(CYGWIN32) /* system srandom() */
  11. #  if defined(BSD) && !defined(POSIX_TYPES)
  12. #   if defined(SUNOS4)
  13. 	(void)
  14. #   endif
  15. 		srandom((int) time((long *)0));
  16. #  else
  17. 		srandom((int) time((time_t *)0));
  18. #  endif
  19. # else
  20. #  ifdef UNIX	/* system srand48() */
  21. 	srand48((long) time((time_t *)0));
  22. #  else		/* poor quality system routine */
  23. 	srand((int) time((time_t *)0));
  24. #  endif
  25. # endif
  26. #endif
  27. }

getlt[edit]

  1. static struct tm *
  2. getlt()
  3. {
  4. 	time_t date;
  5.  
  6. #if defined(BSD) && !defined(POSIX_TYPES)
  7. 	(void) time((long *)(&date));
  8. #else
  9. 	(void) time(&date);
  10. #endif
  11. #if (defined(ULTRIX) && !(defined(ULTRIX_PROTO) || defined(NHSTDC))) || (defined(BSD) && !defined(POSIX_TYPES))
  12. 	return(localtime((long *)(&date)));
  13. #else
  14. 	return(localtime(&date));
  15. #endif
  16. }

getyear[edit]

  1. int
  2. getyear()
  3. {
  4. 	return(1900 + getlt()->tm_year);
  5. }

yymmdd[edit]

  1. #if 0
  2. /* This routine is no longer used since in 2000 it will yield "100mmdd". */
  3. char *
  4. yymmdd(date)
  5. time_t date;
  6. {
  7. 	Static char datestr[10];
  8. 	struct tm *lt;
  9.  
  10. 	if (date == 0)
  11. 		lt = getlt();
  12. 	else
  13. #if (defined(ULTRIX) && !(defined(ULTRIX_PROTO) || defined(NHSTDC))) || defined(BSD)
  14. 		lt = localtime((long *)(&date));
  15. #else
  16. 		lt = localtime(&date);
  17. #endif
  18.  
  19. 	Sprintf(datestr, "%02d%02d%02d",
  20. 		lt->tm_year, lt->tm_mon + 1, lt->tm_mday);
  21. 	return(datestr);
  22. }
  23. #endif

yyyymmdd[edit]

  1. long
  2. yyyymmdd(date)
  3. time_t date;
  4. {
  5. 	long datenum;
  6. 	struct tm *lt;
  7.  
  8. 	if (date == 0)
  9. 		lt = getlt();
  10. 	else
  11. #if (defined(ULTRIX) && !(defined(ULTRIX_PROTO) || defined(NHSTDC))) || (defined(BSD) && !defined(POSIX_TYPES))
  12. 		lt = localtime((long *)(&date));
  13. #else
  14. 		lt = localtime(&date);
  15. #endif
  16.  
  17. 	/* just in case somebody's localtime supplies (year % 100)
  18. 	   rather than the expected (year - 1900) */
  19. 	if (lt->tm_year < 70)
  20. 	    datenum = (long)lt->tm_year + 2000L;
  21. 	else
  22. 	    datenum = (long)lt->tm_year + 1900L;
  23. 	/* yyyy --> yyyymm */
  24. 	datenum = datenum * 100L + (long)(lt->tm_mon + 1);
  25. 	/* yyyymm --> yyyymmdd */
  26. 	datenum = datenum * 100L + (long)lt->tm_mday;
  27. 	return datenum;
  28. }

phase_of_the_moon[edit]

  1. /*
  2. * moon period = 29.53058 days ~= 30, year = 365.2422 days
  3. * days moon phase advances on first day of year compared to preceding year
  4. *	= 365.2422 - 12*29.53058 ~= 11
  5. * years in Metonic cycle (time until same phases fall on the same days of
  6. *	the month) = 18.6 ~= 19
  7. * moon phase on first day of year (epact) ~= (11*(year%19) + 29) % 30
  8. *	(29 as initial condition)
  9. * current phase in days = first day phase + days elapsed in year
  10. * 6 moons ~= 177 days
  11. * 177 ~= 8 reported phases * 22
  12. * + 11/22 for rounding
  13. */
  14. int
  15. phase_of_the_moon()		/* 0-7, with 0: new, 4: full */
  16. {
  17. 	register struct tm *lt = getlt();
  18. 	register int epact, diy, goldn;
  19.  
  20. 	diy = lt->tm_yday;
  21. 	goldn = (lt->tm_year % 19) + 1;
  22. 	epact = (11 * goldn + 18) % 30;
  23. 	if ((epact == 25 && goldn > 11) || epact == 24)
  24. 		epact++;
  25.  
  26. 	return( (((((diy + epact) * 6) + 11) % 177) / 22) & 7 );
  27. }

friday_13th[edit]

  1. boolean
  2. friday_13th()
  3. {
  4. 	register struct tm *lt = getlt();
  5.  
  6. 	return((boolean)(lt->tm_wday == 5 /* friday */ && lt->tm_mday == 13));
  7. }

night[edit]

  1. int
  2. night()
  3. {
  4. 	register int hour = getlt()->tm_hour;
  5.  
  6. 	return(hour < 6 || hour > 21);
  7. }

midnight[edit]

  1. int
  2. midnight()
  3. {
  4. 	return(getlt()->tm_hour == 0);
  5. }
  6. #endif /* OVL2 */
  7.  
  8. /*hacklib.c*/