* Moved num_parms() and all the extract() type functions into tools.c
[citadel.git] / citadel / tools.c
1 /*
2  * tools.c -- Miscellaneous routines used by both the client and server.
3  * $Id$
4  */
5
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include "tools.h"
10
11 char *safestrncpy(char *dest, const char *src, size_t n)
12 {
13   if (dest == NULL || src == NULL)
14     {
15       fprintf(stderr, "safestrncpy: NULL argument\n");
16       abort();
17     }
18   strncpy(dest, src, n);
19   dest[n - 1] = 0;
20   return dest;
21 }
22
23
24 /*
25  * num_parms()  -  discover number of parameters...
26  */
27 int num_parms(char *source)
28 {
29         int a;
30         int count = 1;
31
32         for (a=0; a<strlen(source); ++a) 
33                 if (source[a]=='|') ++count;
34         return(count);
35         }
36
37 /*
38  * extract()  -  extract a parameter from a series of "|" separated...
39  */
40 void extract(char *dest, char *source, int parmnum)
41 {
42         char buf[256];
43         int count = 0;
44         int n;
45
46         if (strlen(source)==0) {
47                 strcpy(dest,"");
48                 return;
49                 }
50
51         n = num_parms(source);
52
53         if (parmnum >= n) {
54                 strcpy(dest,"");
55                 return;
56                 }
57         strcpy(buf,source);
58         if ( (parmnum == 0) && (n == 1) ) {
59                 strcpy(dest,buf);
60                 for (n=0; n<strlen(dest); ++n)
61                         if (dest[n]=='|') dest[n] = 0;
62                 return;
63                 }
64
65         while (count++ < parmnum) do {
66                 strcpy(buf,&buf[1]);
67                 } while( (strlen(buf)>0) && (buf[0]!='|') );
68         if (buf[0]=='|') strcpy(buf,&buf[1]);
69         for (count = 0; count<strlen(buf); ++count)
70                 if (buf[count] == '|') buf[count] = 0;
71         strcpy(dest,buf);
72         }
73
74 /*
75  * extract_int()  -  extract an int parm w/o supplying a buffer
76  */
77 int extract_int(char *source, int parmnum)
78 {
79         char buf[256];
80         
81         extract(buf,source,parmnum);
82         return(atoi(buf));
83         }
84
85 /*
86  * extract_long()  -  extract an long parm w/o supplying a buffer
87  */
88 long extract_long(char *source, long int parmnum)
89 {
90         char buf[256];
91         
92         extract(buf,source,parmnum);
93         return(atol(buf));
94         }
95
96
97