]> git.sesse.net Git - bcachefs-tools-debian/blob - linux/string.c
remove library from bcachefs-tools Rust package
[bcachefs-tools-debian] / linux / string.c
1 /*
2  *  linux/lib/string.c
3  *
4  *  Copyright (C) 1991, 1992  Linus Torvalds
5  */
6
7 /*
8  * stupid library routines.. The optimized versions should generally be found
9  * as inline code in <asm-xx/string.h>
10  *
11  * These are buggy as well..
12  *
13  * * Fri Jun 25 1999, Ingo Oeser <ioe@informatik.tu-chemnitz.de>
14  * -  Added strsep() which will replace strtok() soon (because strsep() is
15  *    reentrant and should be faster). Use only strsep() in new code, please.
16  *
17  * * Sat Feb 09 2002, Jason Thomas <jason@topic.com.au>,
18  *                    Matthew Hawkins <matt@mh.dropbear.id.au>
19  * -  Kissed strtok() goodbye
20  */
21
22 #include <ctype.h>
23 #include <errno.h>
24 #include <limits.h>
25 #include <string.h>
26
27 #include <linux/bug.h>
28 #include <linux/compiler.h>
29 #include <linux/string.h>
30
31 static char *skip_spaces(const char *str)
32 {
33         while (isspace(*str))
34                 ++str;
35         return (char *)str;
36 }
37
38 char *strim(char *s)
39 {
40         size_t size;
41         char *end;
42
43         size = strlen(s);
44         if (!size)
45                 return s;
46
47         end = s + size - 1;
48         while (end >= s && isspace(*end))
49                 end--;
50         *(end + 1) = '\0';
51
52         return skip_spaces(s);
53 }
54
55 size_t strlcpy(char *dest, const char *src, size_t size)
56 {
57         size_t ret = strlen(src);
58
59         if (size) {
60                 size_t len = (ret >= size) ? size - 1 : ret;
61                 memcpy(dest, src, len);
62                 dest[len] = '\0';
63         }
64         return ret;
65 }
66
67 ssize_t strscpy(char *dest, const char *src, size_t count)
68 {
69         long res = 0;
70
71         if (count == 0 || WARN_ON_ONCE(count > INT_MAX))
72                 return -E2BIG;
73
74         while (count) {
75                 char c;
76
77                 c = src[res];
78                 dest[res] = c;
79                 if (!c)
80                         return res;
81                 res++;
82                 count--;
83         }
84
85         /* Hit buffer length without finding a NUL; force NUL-termination. */
86         if (res)
87                 dest[res-1] = '\0';
88
89         return -E2BIG;
90 }
91
92 void memzero_explicit(void *s, size_t count)
93 {
94         memset(s, 0, count);
95         barrier_data(s);
96 }
97
98 int match_string(const char * const *array, size_t n, const char *string)
99 {
100         int index;
101         const char *item;
102
103         for (index = 0; index < n; index++) {
104                 item = array[index];
105                 if (!item)
106                         break;
107                 if (!strcmp(item, string))
108                         return index;
109         }
110
111         return -EINVAL;
112 }