xref: /original-bsd/bin/sh/mystring.c (revision 4405f301)
1 /*-
2  * Copyright (c) 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Kenneth Almquist.
7  *
8  * %sccs.include.redist.c%
9  */
10 
11 #ifndef lint
12 static char sccsid[] = "@(#)mystring.c	8.1 (Berkeley) 05/31/93";
13 #endif /* not lint */
14 
15 /*
16  * String functions.
17  *
18  *	equal(s1, s2)		Return true if strings are equal.
19  *	scopy(from, to)		Copy a string.
20  *	scopyn(from, to, n)	Like scopy, but checks for overflow.
21  *	number(s)		Convert a string of digits to an integer.
22  *	is_number(s)		Return true if s is a string of digits.
23  */
24 
25 #include "shell.h"
26 #include "syntax.h"
27 #include "error.h"
28 #include "mystring.h"
29 
30 
31 char nullstr[1];		/* zero length string */
32 
33 /*
34  * equal - #defined in mystring.h
35  */
36 
37 /*
38  * scopy - #defined in mystring.h
39  */
40 
41 
42 /*
43  * scopyn - copy a string from "from" to "to", truncating the string
44  *		if necessary.  "To" is always nul terminated, even if
45  *		truncation is performed.  "Size" is the size of "to".
46  */
47 
48 void
49 scopyn(from, to, size)
50 	register char const *from;
51 	register char *to;
52 	register int size;
53 	{
54 
55 	while (--size > 0) {
56 		if ((*to++ = *from++) == '\0')
57 			return;
58 	}
59 	*to = '\0';
60 }
61 
62 
63 /*
64  * prefix -- see if pfx is a prefix of string.
65  */
66 
67 int
68 prefix(pfx, string)
69 	register char const *pfx;
70 	register char const *string;
71 	{
72 	while (*pfx) {
73 		if (*pfx++ != *string++)
74 			return 0;
75 	}
76 	return 1;
77 }
78 
79 
80 /*
81  * Convert a string of digits to an integer, printing an error message on
82  * failure.
83  */
84 
85 int
86 number(s)
87 	const char *s;
88 	{
89 
90 	if (! is_number(s))
91 		error2("Illegal number", (char *)s);
92 	return atoi(s);
93 }
94 
95 
96 
97 /*
98  * Check for a valid number.  This should be elsewhere.
99  */
100 
101 int
102 is_number(p)
103 	register const char *p;
104 	{
105 	do {
106 		if (! is_digit(*p))
107 			return 0;
108 	} while (*++p != '\0');
109 	return 1;
110 }
111