xref: /csrg-svn/usr.bin/window/string.c (revision 33514)
1 /*
2  * Copyright (c) 1983 Regents of the University of California.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that this notice is preserved and that due credit is given
7  * to the University of California at Berkeley. The name of the University
8  * may not be used to endorse or promote products derived from this
9  * software without specific prior written permission. This software
10  * is provided ``as is'' without express or implied warranty.
11  */
12 
13 #ifndef lint
14 static char sccsid[] = "@(#)string.c	3.10 (Berkeley) 02/21/88";
15 #endif /* not lint */
16 
17 #include "string.h"
18 
19 char *malloc();
20 
21 char *
22 str_cpy(s)
23 register char *s;
24 {
25 	char *str;
26 	register char *p;
27 
28 	str = p = str_alloc(strlen(s) + 1);
29 	if (p == 0)
30 		return 0;
31 	while (*p++ = *s++)
32 		;
33 	return str;
34 }
35 
36 char *
37 str_ncpy(s, n)
38 register char *s;
39 register n;
40 {
41 	int l = strlen(s);
42 	char *str;
43 	register char *p;
44 
45 	if (n > l)
46 		n = l;
47 	str = p = str_alloc(n + 1);
48 	if (p == 0)
49 		return 0;
50 	while (--n >= 0)
51 		*p++ = *s++;
52 	*p = 0;
53 	return str;
54 }
55 
56 char *
57 str_itoa(i)
58 int i;
59 {
60 	char buf[30];
61 
62 	(void) sprintf(buf, "%d", i);
63 	return str_cpy(buf);
64 }
65 
66 char *
67 str_cat(s1, s2)
68 char *s1, *s2;
69 {
70 	char *str;
71 	register char *p, *q;
72 
73 	str = p = str_alloc(strlen(s1) + strlen(s2) + 1);
74 	if (p == 0)
75 		return 0;
76 	for (q = s1; *p++ = *q++;)
77 		;
78 	for (q = s2, p--; *p++ = *q++;)
79 		;
80 	return str;
81 }
82 
83 /*
84  * match s against p.
85  * s can be a prefix of p with at least min characters.
86  */
87 str_match(s, p, min)
88 register char *s, *p;
89 register min;
90 {
91 	for (; *s && *p && *s == *p; s++, p++, min--)
92 		;
93 	return *s == *p || *s == 0 && min <= 0;
94 }
95 
96 #ifdef STR_DEBUG
97 char *
98 str_alloc(l)
99 int l;
100 {
101 	register struct string *s;
102 
103 	s = (struct string *) malloc((unsigned)l + str_offset);
104 	if (s == 0)
105 		return 0;
106 	if (str_head.s_forw == 0)
107 		str_head.s_forw = str_head.s_back = &str_head;
108 	s->s_forw = str_head.s_forw;
109 	s->s_back = &str_head;
110 	str_head.s_forw = s;
111 	s->s_forw->s_back = s;
112 	return s->s_data;
113 }
114 
115 str_free(str)
116 char *str;
117 {
118 	register struct string *s;
119 
120 	for (s = str_head.s_forw; s != &str_head && s->s_data != str;
121 	     s = s->s_forw)
122 		;
123 	if (s == &str_head)
124 		abort();
125 	s->s_back->s_forw = s->s_forw;
126 	s->s_forw->s_back = s->s_back;
127 	free((char *)s);
128 }
129 #endif
130