1 /*
2 ** strl.c - strlXXX functions
3 **
4 ** Copyright (c) 2000 Peter Eriksson <pen@lysator.liu.se>
5 **
6 ** This program is free software; you can redistribute it and/or
7 ** modify it as you wish - as long as you don't claim that you wrote
8 ** it.
9 **
10 ** This program is distributed in the hope that it will be useful,
11 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 */
14
15 #include "config.h"
16
17 #include <string.h>
18 #include <stdlib.h>
19
20 #include "plib/strl.h"
21
22
23 #ifndef HAVE_STRLCPY
24 size_t
strlcpy(char * dst,const char * src,size_t dstsize)25 strlcpy(char *dst,
26 const char *src,
27 size_t dstsize)
28 {
29 size_t srclen, tocopy;
30
31
32 srclen = strlen(src);
33
34 if (dstsize == 0)
35 return srclen;
36
37 tocopy = (srclen >= dstsize ? dstsize-1 : srclen);
38 if (tocopy > 0)
39 memcpy(dst, src, tocopy);
40 dst[tocopy] = '\0';
41
42 return srclen;
43 }
44 #endif
45
46
47 #ifndef HAVE_STRLCAT
48 size_t
strlcat(char * dst,const char * src,size_t dstsize)49 strlcat(char *dst,
50 const char *src,
51 size_t dstsize)
52 {
53 size_t dstlen, srclen, tocopy;
54
55
56 dstlen = strlen(dst);
57 srclen = strlen(src);
58
59 if (dstsize == 0)
60 return dstlen+srclen;
61
62 tocopy = (dstlen+srclen >= dstsize ? dstsize-1-dstlen : srclen);
63 if (tocopy > 0)
64 memcpy(dst+dstlen, src, tocopy);
65 dst[dstlen+tocopy] = '\0';
66
67 return dstlen+srclen;
68 }
69 #endif
70
71
72 #ifndef HAVE_STRLNCPY
73 /*
74 ** Extract at most "maxsrclen" characters from the "src" string
75 ** and copy to the "dst" string.
76 */
77 size_t
strlncpy(char * dst,const char * src,size_t dstsize,size_t maxsrclen)78 strlncpy(char *dst,
79 const char *src,
80 size_t dstsize,
81 size_t maxsrclen)
82 {
83 size_t srclen, tocopy;
84
85
86 srclen = strlen(src);
87 if (srclen > maxsrclen)
88 srclen = maxsrclen;
89
90 if (dstsize == 0)
91 return srclen;
92
93 tocopy = (srclen >= dstsize ? dstsize-1 : srclen);
94 if (tocopy > 0)
95 memcpy(dst, src, tocopy);
96 dst[tocopy] = '\0';
97
98 return srclen;
99 }
100 #endif
101
102
103 #ifndef HAVE_STRLNCAT
104 /*
105 ** Extract at most "maxsrclen" characters from the "src" string
106 ** and append to the "dst" string.
107 */
108 size_t
strlncat(char * dst,const char * src,size_t dstsize,size_t maxsrclen)109 strlncat(char *dst,
110 const char *src,
111 size_t dstsize,
112 size_t maxsrclen)
113 {
114 size_t dstlen, srclen, tocopy;
115
116
117 dstlen = strlen(dst);
118 srclen = strlen(src);
119 if (srclen > maxsrclen)
120 srclen = maxsrclen;
121
122 if (dstsize == 0)
123 return dstlen+srclen;
124
125 tocopy = (dstlen+srclen >= dstsize ? dstsize-1-dstlen : srclen);
126 if (tocopy > 0)
127 memcpy(dst+dstlen, src, tocopy);
128 dst[dstlen+tocopy] = '\0';
129
130 return dstlen+srclen;
131 }
132 #endif
133
134