0b7e1aaf720ffa6d7d4dea6161e5d72d25f22163
[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()  -  a smarter string tokenizer
39  */
40 void extract_token(char *dest, char *source, int parmnum, char separator)
41 {
42         int i;
43         int len;
44         int curr_parm;
45
46         strcpy(dest,"");
47         len = 0;
48         curr_parm = 0;
49
50         if (strlen(source)==0) {
51                 return;
52                 }
53
54         for (i=0; i<strlen(source); ++i) {
55                 if (source[i]==separator) {
56                         ++curr_parm;
57                 }
58                 else if (curr_parm == parmnum) {
59                         dest[len+1] = 0;
60                         dest[len++] = source[i];
61                 }
62         }
63 }
64
65 /*
66  * extract_int()  -  extract an int parm w/o supplying a buffer
67  */
68 int extract_int(char *source, int parmnum)
69 {
70         char buf[256];
71         
72         extract_token(buf, source, parmnum, '|');
73         return(atoi(buf));
74 }
75
76 /*
77  * extract_long()  -  extract an long parm w/o supplying a buffer
78  */
79 long extract_long(char *source, long int parmnum)
80 {
81         char buf[256];
82         
83         extract_token(buf, source, parmnum, '|');
84         return(atol(buf));
85 }