1 /*
2  * include/import/ist.h
3  * Very simple indirect string manipulation functions.
4  *
5  * Copyright (C) 2014-2020 Willy Tarreau - w@1wt.eu
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining
8  * a copy of this software and associated documentation files (the
9  * "Software"), to deal in the Software without restriction, including
10  * without limitation the rights to use, copy, modify, merge, publish,
11  * distribute, sublicense, and/or sell copies of the Software, and to
12  * permit persons to whom the Software is furnished to do so, subject to
13  * the following conditions:
14  *
15  * The above copyright notice and this permission notice shall be
16  * included in all copies or substantial portions of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20  * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
22  * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
23  * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25  * OTHER DEALINGS IN THE SOFTWARE.
26  */
27 
28 #ifndef _IMPORT_IST_H
29 #define _IMPORT_IST_H
30 
31 #include <sys/types.h>
32 #include <ctype.h>
33 #include <stddef.h>
34 #include <string.h>
35 
36 #ifndef IST_FREESTANDING
37 #include <stdlib.h>
38 #endif
39 
40 /* ASCII to lower case conversion table */
41 #define _IST_LC ((const unsigned char[256]){            \
42 	0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, \
43 	0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, \
44 	0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, \
45 	0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, \
46 	0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, \
47 	0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, \
48 	0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, \
49 	0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, \
50 	0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, \
51 	0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, \
52 	0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, \
53 	0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, \
54 	0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, \
55 	0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, \
56 	0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, \
57 	0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, \
58 	0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, \
59 	0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, \
60 	0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, \
61 	0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, \
62 	0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, \
63 	0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, \
64 	0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, \
65 	0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, \
66 	0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, \
67 	0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, \
68 	0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, \
69 	0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, \
70 	0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, \
71 	0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, \
72 	0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, \
73 	0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, \
74 })
75 
76 /* ASCII to upper case conversion table */
77 #define _IST_UC ((const unsigned char[256]){            \
78 	0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, \
79 	0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, \
80 	0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, \
81 	0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, \
82 	0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, \
83 	0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, \
84 	0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, \
85 	0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, \
86 	0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, \
87 	0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, \
88 	0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, \
89 	0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, \
90 	0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, \
91 	0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, \
92 	0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, \
93 	0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, \
94 	0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, \
95 	0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, \
96 	0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, \
97 	0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, \
98 	0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, \
99 	0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, \
100 	0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, \
101 	0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, \
102 	0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, \
103 	0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, \
104 	0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, \
105 	0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, \
106 	0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, \
107 	0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, \
108 	0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, \
109 	0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, \
110 })
111 
112 #ifdef USE_OBSOLETE_LINKER
113 /* some old linkers and some non-ELF platforms have issues with the weak
114  * attribute so we turn these arrays to literals there.
115  */
116 #define ist_lc _IST_LC
117 #define ist_uc _IST_UC
118 #else
119 const unsigned char ist_lc[256] __attribute__((weak)) = _IST_LC;
120 const unsigned char ist_uc[256] __attribute__((weak)) = _IST_UC;
121 #endif
122 
123 /* This string definition will most often be used to represent a read-only
124  * string returned from a function, based on the starting point and its length
125  * in bytes. No storage is provided, only a pointer and a length. The types
126  * here are important as we only want to have 2 native machine words there so
127  * that on modern architectures the compiler is capable of efficiently
128  * returning a register pair without having to allocate stack room from the
129  * caller. This is done with -freg-struct which is often enabled by default.
130  */
131 struct ist {
132 	char  *ptr;
133 	size_t len;
134 };
135 
136 /* makes a constant ist from a constant string, for use in array declarations */
137 #define IST(str) { .ptr = str "", .len = (sizeof str "") - 1 }
138 
139 /* IST_NULL is equivalent to an `ist` with `.ptr = NULL` and `.len = 0` */
140 #define IST_NULL ((const struct ist){ .ptr = 0, .len = 0 })
141 
142 /* makes an ist from a regular zero terminated string. Null has length 0.
143  * Constants are detected and replaced with constant initializers. Other values
144  * are measured by hand without strlen() as it's much cheaper and inlinable on
145  * small strings. The construct is complex because we must never call
146  * __builtin_strlen() with an expression otherwise it involves a real
147  * measurement.
148  */
149 #if __GNUC__ >= 4
150 // gcc >= 4 detects constant propagation of str through __x and resolves the
151 // length of constant strings easily.
152 #define ist(str) ({                                                    \
153 	char *__x = (void *)(str);                                     \
154 	(struct ist){                                                  \
155 		.ptr = __x,                                            \
156 		.len = __builtin_constant_p(str) ?                     \
157 			((void *)str == (void *)0) ? 0 :               \
158 			__builtin_strlen(__x) :                        \
159 			({                                             \
160 				size_t __l = 0;                        \
161 				if (__x) for (__l--; __x[++__l]; ) ;   \
162 				__l;                                   \
163 			})                                             \
164 	};                                                             \
165 })
166 #else
167 // gcc < 4 can't do this, and the side effect is a warning each time a NULL is
168 // passed to ist() due to the check on __builtin_strlen(). It doesn't have the
169 // ability to know that this code is never called.
170 #define ist(str) ({                                                    \
171 	char *__x = (void *)(str);                                     \
172 	(struct ist){                                                  \
173 		.ptr = __x,                                            \
174 		.len = __builtin_constant_p(str) ?                     \
175 			((void *)str == (void *)0) ? 0 :               \
176 			__builtin_strlen(str) :                        \
177 			({                                             \
178 				size_t __l = 0;                        \
179 				if (__x) for (__l--; __x[++__l]; ) ;   \
180 				__l;                                   \
181 			})                                             \
182 	};                                                             \
183 })
184 #endif
185 
186 /* makes an ist struct from a string and a length */
ist2(const void * ptr,size_t len)187 static inline struct ist ist2(const void *ptr, size_t len)
188 {
189 	return (struct ist){ .ptr = (char *)ptr, .len = len };
190 }
191 
192 /* returns the result of `ist.ptr != NULL` */
isttest(const struct ist ist)193 static inline int isttest(const struct ist ist)
194 {
195 	return ist.ptr != NULL;
196 }
197 
198 /* This function MODIFIES the string to add a zero AFTER the end, and returns
199  * the start pointer. The purpose is to use it on strings extracted by parsers
200  * from larger strings cut with delimiters that are not important and can be
201  * destroyed. It allows any such string to be used with regular string
202  * functions. It's also convenient to use with printf() to show data extracted
203  * from writable areas. The caller is obviously responsible for ensuring that
204  * the string is valid and that the first byte past the end is writable. If
205  * these conditions cannot be satisfied, use istpad() below instead.
206  */
ist0(struct ist ist)207 static inline char *ist0(struct ist ist)
208 {
209 	ist.ptr[ist.len] = 0;
210 	return ist.ptr;
211 }
212 
213 /* returns the pointer of the string */
istptr(const struct ist ist)214 static inline char *istptr(const struct ist ist)
215 {
216 	return ist.ptr;
217 }
218 
219 /* returns the length of the string */
istlen(const struct ist ist)220 static inline size_t istlen(const struct ist ist)
221 {
222 	return ist.len;
223 }
224 
225 /* returns the pointer to the end the string */
istend(const struct ist ist)226 static inline char *istend(const struct ist ist)
227 {
228 	return (ist.ptr + ist.len);
229 }
230 
231 /* skips to next character in the string, always stops at the end */
istnext(const struct ist ist)232 static inline struct ist istnext(const struct ist ist)
233 {
234 	struct ist ret = ist;
235 
236 	if (ret.len) {
237 		ret.len--;
238 		ret.ptr++;
239 	}
240 	return ret;
241 }
242 
243 /* Returns the first character of the <ist> and advances the <ist> by 1.
244  * If the <ist> is empty the result is undefined.
245  */
istshift(struct ist * ist)246 static inline char istshift(struct ist *ist)
247 {
248 	if (ist->len) {
249 		char c = *ist->ptr;
250 		*ist = istnext(*ist);
251 
252 		return c;
253 	}
254 
255 	return 0;
256 }
257 
258 /* copies the contents from string <ist> to buffer <buf> and adds a trailing
259  * zero. The caller must ensure <buf> is large enough.
260  */
istpad(void * buf,const struct ist ist)261 static inline struct ist istpad(void *buf, const struct ist ist)
262 {
263 	struct ist ret = { .ptr = buf, .len = ist.len };
264 
265 	for (ret.len = 0; ret.len < ist.len; ret.len++)
266 		ret.ptr[ret.len] = ist.ptr[ret.len];
267 
268 	ret.ptr[ret.len] = 0;
269 	return ret;
270 }
271 
272 /* trims string <ist> to no more than <size> characters. The string is
273  * returned.
274  */
isttrim(const struct ist ist,size_t size)275 static inline struct ist isttrim(const struct ist ist, size_t size)
276 {
277 	struct ist ret = ist;
278 
279 	if (ret.len > size)
280 		ret.len = size;
281 	return ret;
282 }
283 
284 /* Sets the <len> of the <ist> to zero and returns the previous length.
285  *
286  * This function is meant to be used in functions that receive an ist containing
287  * the destination buffer and the buffer's size. The returned size must be stored
288  * to prevent an overflow of such a destination buffer.
289  *
290  * If you simply want to clear an ist and do not care about the previous length
291  * then you should use `isttrim(ist, 0)`.
292  *
293  * Example Usage (fill the complete buffer with 'x'):
294  *
295  * void my_func(struct ist* dst)
296  * {
297  * 	size_t dst_size = istclear(dst);
298  * 	size_t i;
299  *
300  * 	for (i = 0; i < dst_size; i++)
301  * 		*dst = __istappend(*dst, 'x');
302  * }
303  */
304 __attribute__((warn_unused_result))
istclear(struct ist * ist)305 static inline size_t istclear(struct ist* ist)
306 {
307 	size_t len = ist->len;
308 
309 	ist->len = 0;
310 
311 	return len;
312 }
313 
314 /* trims string <ist> to no more than <size>-1 characters and ensures that a
315  * zero is placed after <ist.len> (possibly reduced by one) and before <size>,
316  * unless <size> is already zero. The string is returned. This is mostly aimed
317  * at building printable strings that need to be zero-terminated.
318  */
istzero(const struct ist ist,size_t size)319 static inline struct ist istzero(const struct ist ist, size_t size)
320 {
321 	struct ist ret = ist;
322 
323 	if (!size)
324 		ret.len = 0;
325 	else {
326 		if (ret.len > size - 1)
327 			ret.len = size - 1;
328 		ret.ptr[ret.len] = 0;
329 	}
330 	return ret;
331 }
332 
333 /* returns the ordinal difference between two strings :
334  *    < 0 if ist1 < ist2
335  *    = 0 if ist1 == ist2
336  *    > 0 if ist1 > ist2
337  */
istdiff(const struct ist ist1,const struct ist ist2)338 static inline int istdiff(const struct ist ist1, const struct ist ist2)
339 {
340 	struct ist l = ist1;
341 	struct ist r = ist2;
342 
343 	do {
344 		if (!l.len--)
345 			return -r.len;
346 		if (!r.len--)
347 			return 1;
348 	} while (*l.ptr++ == *r.ptr++);
349 
350 	return *(unsigned char *)(l.ptr - 1) - *(unsigned char *)(r.ptr - 1);
351 }
352 
353 /* returns non-zero if <ist1> starts like <ist2> (empty strings do match) */
istmatch(const struct ist ist1,const struct ist ist2)354 static inline int istmatch(const struct ist ist1, const struct ist ist2)
355 {
356 	struct ist l = ist1;
357 	struct ist r = ist2;
358 
359 	if (l.len < r.len)
360 		return 0;
361 
362 	while (r.len--) {
363 		if (*l.ptr++ != *r.ptr++)
364 			return 0;
365 	}
366 	return 1;
367 }
368 
369 /* returns non-zero if <ist1> starts like <ist2>, ignoring the case (empty strings do match) */
istmatchi(const struct ist ist1,const struct ist ist2)370 static inline int istmatchi(const struct ist ist1, const struct ist ist2)
371 {
372 	struct ist l = ist1;
373 	struct ist r = ist2;
374 
375 	if (l.len < r.len)
376 		return 0;
377 
378 	while (r.len--) {
379 		if (*l.ptr != *r.ptr &&
380 		    ist_lc[(unsigned char)*l.ptr] != ist_lc[(unsigned char)*r.ptr])
381 			return 0;
382 
383 		l.ptr++;
384 		r.ptr++;
385 	}
386 	return 1;
387 }
388 
389 /* returns non-zero if <ist1> starts like <ist2> on the first <count>
390  * characters (empty strings do match).
391  */
istnmatch(const struct ist ist1,const struct ist ist2,size_t count)392 static inline int istnmatch(const struct ist ist1, const struct ist ist2, size_t count)
393 {
394 	struct ist l = ist1;
395 	struct ist r = ist2;
396 
397 	if (l.len > count)
398 		l.len = count;
399 	if (r.len > count)
400 		r.len = count;
401 	return istmatch(l, r);
402 }
403 
404 /* returns non-zero if <ist1> equals <ist2> (empty strings are equal) */
isteq(const struct ist ist1,const struct ist ist2)405 static inline int isteq(const struct ist ist1, const struct ist ist2)
406 {
407 	struct ist l = ist1;
408 	struct ist r = ist2;
409 
410 	if (l.len != r.len)
411 		return 0;
412 
413 	while (l.len--) {
414 		if (*l.ptr++ != *r.ptr++)
415 			return 0;
416 	}
417 	return 1;
418 }
419 
420 /* returns non-zero if <ist1> equals <ist2>, ignoring the case (empty strings are equal) */
isteqi(const struct ist ist1,const struct ist ist2)421 static inline int isteqi(const struct ist ist1, const struct ist ist2)
422 {
423 	struct ist l = ist1;
424 	struct ist r = ist2;
425 
426 	if (l.len != r.len)
427 		return 0;
428 
429 	while (l.len--) {
430 		if (*l.ptr != *r.ptr &&
431 		    ist_lc[(unsigned char)*l.ptr] != ist_lc[(unsigned char)*r.ptr])
432 			return 0;
433 
434 		l.ptr++;
435 		r.ptr++;
436 	}
437 	return 1;
438 }
439 
440 /* returns non-zero if <ist1> equals <ist2> on the first <count> characters
441  * (empty strings are equal).
442  */
istneq(const struct ist ist1,const struct ist ist2,size_t count)443 static inline int istneq(const struct ist ist1, const struct ist ist2, size_t count)
444 {
445 	struct ist l = ist1;
446 	struct ist r = ist2;
447 
448 	if (l.len > count)
449 		l.len = count;
450 	if (r.len > count)
451 		r.len = count;
452 	return isteq(l, r);
453 }
454 
455 /* appends <src> after <dst>. The caller must ensure that the underlying buffer
456  * is large enough to fit the character.
457  */
__istappend(struct ist dst,const char src)458 static inline struct ist __istappend(struct ist dst, const char src)
459 {
460 	dst.ptr[dst.len++] = src;
461 
462 	return dst;
463 }
464 
465 /* copies <src> over <dst> for a maximum of <count> bytes. Returns the number
466  * of characters copied (src.len), or -1 if it does not fit. In all cases, the
467  * contents are copied prior to reporting an error, so that the destination
468  * at least contains a valid but truncated string.
469  */
istcpy(struct ist * dst,const struct ist src,size_t count)470 static inline ssize_t istcpy(struct ist *dst, const struct ist src, size_t count)
471 {
472 	dst->len = 0;
473 
474 	if (count > src.len)
475 		count = src.len;
476 
477 	while (dst->len < count) {
478 		dst->ptr[dst->len] = src.ptr[dst->len];
479 		dst->len++;
480 	}
481 
482 	if (dst->len == src.len)
483 		return src.len;
484 
485 	return -1;
486 }
487 
488 /* copies <src> over <dst> for a maximum of <count> bytes. Returns the number
489  * of characters copied, or -1 if it does not fit. A (possibly truncated) valid
490  * copy of <src> is always left into <dst>, and a trailing \0 is appended as
491  * long as <count> is not null, even if that results in reducing the string by
492  * one character.
493  */
istscpy(struct ist * dst,const struct ist src,size_t count)494 static inline ssize_t istscpy(struct ist *dst, const struct ist src, size_t count)
495 {
496 	dst->len = 0;
497 
498 	if (!count)
499 		goto fail;
500 
501 	if (count > src.len)
502 		count = src.len + 1;
503 
504 	while (dst->len < count - 1) {
505 		dst->ptr[dst->len] = src.ptr[dst->len];
506 		dst->len++;
507 	}
508 
509 	dst->ptr[dst->len] = 0;
510 	if (dst->len == src.len)
511 		return src.len;
512  fail:
513 	return -1;
514 }
515 
516 /* appends <src> after <dst> for a maximum of <count> total bytes in <dst> after
517  * the copy. <dst> is assumed to be <count> or less before the call. The new
518  * string's length is returned, or -1 if a truncation happened. In all cases,
519  * the contents are copied prior to reporting an error, so that the destination
520  * at least contains a valid but truncated string.
521  */
istcat(struct ist * dst,const struct ist src,size_t count)522 static inline ssize_t istcat(struct ist *dst, const struct ist src, size_t count)
523 {
524 	const char *s = src.ptr;
525 
526 	while (dst->len < count && s != src.ptr + src.len)
527 		dst->ptr[dst->len++] = *s++;
528 
529 	if (s == src.ptr + src.len)
530 		return dst->len;
531 
532 	return -1;
533 }
534 
535 /* appends <src> after <dst> for a maximum of <count> total bytes in <dst> after
536  * the copy. <dst> is assumed to be <count> or less before the call. The new
537  * string's length is returned, or -1 if a truncation happened. In all cases,
538  * the contents are copied prior to reporting an error, so that the destination
539  * at least contains a valid but truncated string.
540  */
istscat(struct ist * dst,const struct ist src,size_t count)541 static inline ssize_t istscat(struct ist *dst, const struct ist src, size_t count)
542 {
543 	const char *s = src.ptr;
544 
545 	if (!count)
546 		goto fail;
547 
548 	while (dst->len < count - 1 && s != src.ptr + src.len) {
549 		dst->ptr[dst->len++] = *s++;
550 	}
551 
552 	dst->ptr[dst->len] = 0;
553 	if (s == src.ptr + src.len)
554 		return dst->len;
555  fail:
556 	return -1;
557 }
558 
559 /* copies the entire <src> over <dst>, which must be allocated large enough to
560  * hold the whole contents. No trailing zero is appended, this is mainly used
561  * for protocol processing where the frame length has already been checked. An
562  * ist made of the output and its length are returned. The destination is not
563  * touched if src.len is null.
564  */
ist2bin(char * dst,const struct ist src)565 static inline struct ist ist2bin(char *dst, const struct ist src)
566 {
567 	size_t ofs = 0;
568 
569 	/* discourage the compiler from trying to optimize for large strings,
570 	 * but tell it that most of our strings are not empty.
571 	 */
572 	if (__builtin_expect(ofs < src.len, 1)) {
573 		do {
574 			dst[ofs] = src.ptr[ofs];
575 			ofs++;
576 		} while (__builtin_expect(ofs < src.len, 0));
577 	}
578 	return ist2(dst, ofs);
579 }
580 
581 /* copies the entire <src> over <dst>, which must be allocated large enough to
582  * hold the whole contents as well as a trailing zero which is always appended.
583  * This is mainly used for protocol conversions where the frame length has
584  * already been checked. An ist made of the output and its length (not counting
585  * the trailing zero) are returned.
586  */
ist2str(char * dst,const struct ist src)587 static inline struct ist ist2str(char *dst, const struct ist src)
588 {
589 	size_t ofs = 0;
590 
591 	/* discourage the compiler from trying to optimize for large strings,
592 	 * but tell it that most of our strings are not empty.
593 	 */
594 	if (__builtin_expect(ofs < src.len, 1)) {
595 		do {
596 			dst[ofs] = src.ptr[ofs];
597 			ofs++;
598 		} while (__builtin_expect(ofs < src.len, 0));
599 	}
600 	dst[ofs] = 0;
601 	return ist2(dst, ofs);
602 }
603 
604 /* makes a lower case copy of the entire <src> into <dst>, which must have been
605  * allocated large enough to hold the whole contents. No trailing zero is
606  * appended, this is mainly used for protocol processing where the frame length
607  * has already been checked. An ist made of the output and its length are
608  * returned. The destination is not touched if src.len is null.
609  */
ist2bin_lc(char * dst,const struct ist src)610 static inline struct ist ist2bin_lc(char *dst, const struct ist src)
611 {
612 	size_t ofs = 0;
613 
614 	/* discourage the compiler from trying to optimize for large strings,
615 	 * but tell it that most of our strings are not empty.
616 	 */
617 	if (__builtin_expect(ofs < src.len, 1)) {
618 		do {
619 			dst[ofs] = ist_lc[(unsigned char)src.ptr[ofs]];
620 			ofs++;
621 		} while (__builtin_expect(ofs < src.len, 0));
622 	}
623 	return ist2(dst, ofs);
624 }
625 
626 /* makes a lower case copy of the entire <src> into <dst>, which must have been
627  * allocated large enough to hold the whole contents as well as a trailing zero
628  * which is always appended. This is mainly used for protocol conversions where
629  * the frame length has already been checked. An ist made of the output and its
630  * length (not counting the trailing zero) are returned.
631  */
ist2str_lc(char * dst,const struct ist src)632 static inline struct ist ist2str_lc(char *dst, const struct ist src)
633 {
634 	size_t ofs = 0;
635 
636 	/* discourage the compiler from trying to optimize for large strings,
637 	 * but tell it that most of our strings are not empty.
638 	 */
639 	if (__builtin_expect(ofs < src.len, 1)) {
640 		do {
641 			dst[ofs] = ist_lc[(unsigned char)src.ptr[ofs]];
642 			ofs++;
643 		} while (__builtin_expect(ofs < src.len, 0));
644 	}
645 	dst[ofs] = 0;
646 	return ist2(dst, ofs);
647 }
648 
649 /* makes an upper case copy of the entire <src> into <dst>, which must have
650  * been allocated large enough to hold the whole contents. No trailing zero is
651  * appended, this is mainly used for protocol processing where the frame length
652  * has already been checked. An ist made of the output and its length are
653  * returned. The destination is not touched if src.len is null.
654  */
ist2bin_uc(char * dst,const struct ist src)655 static inline struct ist ist2bin_uc(char *dst, const struct ist src)
656 {
657 	size_t ofs = 0;
658 
659 	/* discourage the compiler from trying to optimize for large strings,
660 	 * but tell it that most of our strings are not empty.
661 	 */
662 	if (__builtin_expect(ofs < src.len, 1)) {
663 		do {
664 			dst[ofs] = ist_uc[(unsigned char)src.ptr[ofs]];
665 			ofs++;
666 		} while (__builtin_expect(ofs < src.len, 0));
667 	}
668 	return ist2(dst, ofs);
669 }
670 
671 /* makes an upper case copy of the entire <src> into <dst>, which must have been
672  * allocated large enough to hold the whole contents as well as a trailing zero
673  * which is always appended. This is mainly used for protocol conversions where
674  * the frame length has already been checked. An ist made of the output and its
675  * length (not counting the trailing zero) are returned.
676  */
ist2str_uc(char * dst,const struct ist src)677 static inline struct ist ist2str_uc(char *dst, const struct ist src)
678 {
679 	size_t ofs = 0;
680 
681 	/* discourage the compiler from trying to optimize for large strings,
682 	 * but tell it that most of our strings are not empty.
683 	 */
684 	if (__builtin_expect(ofs < src.len, 1)) {
685 		do {
686 			dst[ofs] = ist_uc[(unsigned char)src.ptr[ofs]];
687 			ofs++;
688 		} while (__builtin_expect(ofs < src.len, 0));
689 	}
690 	dst[ofs] = 0;
691 	return ist2(dst, ofs);
692 }
693 
694 /* looks for first occurrence of character <chr> in string <ist>. Returns the
695  * pointer if found, or NULL if not found.
696  */
istchr(const struct ist ist,char chr)697 static inline char *istchr(const struct ist ist, char chr)
698 {
699 	char *s = ist.ptr;
700 
701 	do {
702 		if (s >= ist.ptr + ist.len)
703 			return NULL;
704 	} while (*s++ != chr);
705 	return s - 1;
706 }
707 
708 /* Returns a pointer to the first control character found in <ist>, or NULL if
709  * none is present. A control character is defined as a byte whose value is
710  * between 0x00 and 0x1F included. The function is optimized for strings having
711  * no CTL chars by processing up to sizeof(long) bytes at once on architectures
712  * supporting efficient unaligned accesses. Despite this it is not very fast
713  * (~0.43 byte/cycle) and should mostly be used on low match probability when
714  * it can save a call to a much slower function.
715  */
ist_find_ctl(const struct ist ist)716 static inline const char *ist_find_ctl(const struct ist ist)
717 {
718 	const union { unsigned long v; } __attribute__((packed)) *u;
719 	const char *curr = (void *)ist.ptr - sizeof(long);
720 	const char *last = curr + ist.len;
721 	unsigned long l1, l2;
722 
723 	do {
724 		curr += sizeof(long);
725 		if (curr > last)
726 			break;
727 		u = (void *)curr;
728 		/* subtract 0x202020...20 to the value to generate a carry in
729 		 * the lower byte if the byte contains a lower value. If we
730 		 * generate a bit 7 that was not there, it means the byte was
731 		 * within 0x00..0x1F.
732 		 */
733 		l2  = u->v;
734 		l1  = ~l2 & ((~0UL / 255) * 0x80); /* 0x808080...80 */
735 		l2 -= (~0UL / 255) * 0x20;         /* 0x202020...20 */
736 	} while ((l1 & l2) == 0);
737 
738 	last += sizeof(long);
739 	if (__builtin_expect(curr < last, 0)) {
740 		do {
741 			if ((unsigned char)*curr < 0x20)
742 				return curr;
743 			curr++;
744 		} while (curr < last);
745 	}
746 	return NULL;
747 }
748 
749 /* looks for first occurrence of character <chr> in string <ist> and returns
750  * the tail of the string starting with this character, or (ist.end,0) if not
751  * found.
752  */
istfind(const struct ist ist,char chr)753 static inline struct ist istfind(const struct ist ist, char chr)
754 {
755 	struct ist ret = ist;
756 
757 	while (ret.len--) {
758 		if (*ret.ptr++ == chr)
759 			return ist2(ret.ptr - 1, ret.len + 1);
760 	}
761 	return ist2(ret.ptr, 0);
762 }
763 
764 /* looks for first occurrence of character different from <chr> in string <ist>
765  * and returns the tail of the string starting at this character, or (ist_end,0)
766  * if not found.
767  */
istskip(const struct ist ist,char chr)768 static inline struct ist istskip(const struct ist ist, char chr)
769 {
770 	struct ist ret = ist;
771 
772 	while (ret.len--) {
773 		if (*ret.ptr++ != chr)
774 			return ist2(ret.ptr - 1, ret.len + 1);
775 	}
776 	return ist2(ret.ptr, 0);
777 }
778 
779 /* looks for first occurrence of string <pat> in string <ist> and returns the
780  * tail of the string starting at this position, or (NULL,0) if not found. The
781  * empty pattern is found everywhere.
782  */
istist(const struct ist ist,const struct ist pat)783 static inline struct ist istist(const struct ist ist, const struct ist pat)
784 {
785 	struct ist ret = ist;
786 	size_t pos;
787 
788 	if (!pat.len)
789 		return ret;
790 
791 	while (1) {
792 	loop:
793 		ret = istfind(ret, *pat.ptr);
794 		if (ret.len < pat.len)
795 			break;
796 
797 		/* ret.len >= 1, pat.len >= 1 and *ret.ptr == *pat.ptr */
798 
799 		ret = istnext(ret);
800 		for (pos = 0; pos < pat.len - 1; ) {
801 			++pos;
802 			if (ret.ptr[pos - 1] != pat.ptr[pos])
803 				goto loop;
804 		}
805 		return ist2(ret.ptr - 1, ret.len + 1);
806 	}
807 	return IST_NULL;
808 }
809 
810 /*
811  * looks for the first occurrence of <chr> in string <ist> and returns a shorter
812  * ist if char is found.
813  */
iststop(const struct ist ist,char chr)814 static inline struct ist iststop(const struct ist ist, char chr)
815 {
816 	size_t len = 0;
817 
818 	while (len++ < ist.len && ist.ptr[len - 1] != chr)
819 		;
820 	return ist2(ist.ptr, len - 1);
821 }
822 
823 /*
824  * advance <.ptr> by <nb> characters.
825  * If <ist> is too short, (ist.end,0) is returned.
826  */
istadv(const struct ist ist,const size_t nb)827 static inline struct ist istadv(const struct ist ist, const size_t nb)
828 {
829 	if (ist.len < nb)
830 		return ist2(ist.ptr + ist.len, 0);
831 	return ist2(ist.ptr + nb, ist.len - nb);
832 }
833 
834 /* Splits the given <ist> at the given character. The returned ist is
835  * equivalent to iststop(ist, delim). The passed <ist> will contain the
836  * remainder of the string, not including the delimiter. In other words
837  * it will be advanced by the length of the returned string plus 1.
838  */
istsplit(struct ist * ist,char delim)839 static inline struct ist istsplit(struct ist *ist, char delim)
840 {
841 	const struct ist result = iststop(*ist, delim);
842 
843 	*ist = istadv(*ist, result.len + 1);
844 
845 	return result;
846 }
847 
848 /*
849  * compare 2 ists and return non-zero if they are the same
850  */
istissame(const struct ist ist1,const struct ist ist2)851 static inline int istissame(const struct ist ist1, const struct ist ist2)
852 {
853 	return ((ist1.ptr == ist2.ptr) && (ist1.len == ist2.len));
854 }
855 
856 #ifndef IST_FREESTANDING
857 /* This function allocates <size> bytes and returns an `ist` pointing to
858  * the allocated area with size `0`.
859  *
860  * If this function fails to allocate memory the return value is equivalent
861  * to IST_NULL.
862  */
istalloc(const size_t size)863 static inline struct ist istalloc(const size_t size)
864 {
865 	/* Note: do not use ist2 here, as it triggers a gcc11 warning.
866 	 * ‘<unknown>’ may be used uninitialized [-Werror=maybe-uninitialized]
867 	 *
868 	 * This warning is reported because the uninitialized memory block
869 	 * allocated by malloc should not be passed to a const argument as in
870 	 * ist2.
871 	 * See https://gcc.gnu.org/onlinedocs/gcc-11.1.0/gcc/Warning-Options.html#index-Wmaybe-uninitialized
872 	 */
873 	return (struct ist){ .ptr = malloc(size), .len = 0 };
874 }
875 
876 /* This function performs the equivalent of free() on the given <ist>.
877  *
878  * After this function returns the value of the given <ist> will be
879  * modified to be equivalent to IST_NULL.
880  */
istfree(struct ist * ist)881 static inline void istfree(struct ist *ist)
882 {
883 	free(ist->ptr);
884 	*ist = IST_NULL;
885 }
886 
887 /* This function performs the equivalent of strdup() on the given <src>.
888  *
889  * If this function fails to allocate memory the return value is equivalent
890  * to IST_NULL.
891  */
istdup(const struct ist src)892 static inline struct ist istdup(const struct ist src)
893 {
894 	const size_t src_size = src.len;
895 
896 	/* Allocate at least 1 byte to allow duplicating an empty string with
897 	 * malloc implementations that return NULL for a 0-size allocation.
898 	 */
899 	struct ist dst = istalloc(src_size ? src_size : 1);
900 
901 	if (isttest(dst)) {
902 		istcpy(&dst, src, src_size);
903 	}
904 
905 	return dst;
906 }
907 #endif
908 
909 #endif
910