blob: 0e071c0bb09e3c8053a44f641123c5b239cd67ca [file] [log] [blame]
Wang Nan7d85c432015-11-16 11:42:05 -03001/*
2 * linux/tools/lib/string.c
3 *
4 * Copied from linux/lib/string.c, where it is:
5 *
6 * Copyright (C) 1991, 1992 Linus Torvalds
7 *
8 * More specifically, the first copied function was strtobool, which
9 * was introduced by:
10 *
11 * d0f1fed29e6e ("Add a strtobool function matching semantics of existing in kernel equivalents")
12 * Author: Jonathan Cameron <jic23@cam.ac.uk>
13 */
14
Arnaldo Carvalho de Melo4ddd3272015-11-16 11:36:29 -030015#include <stdlib.h>
16#include <string.h>
Wang Nan7d85c432015-11-16 11:42:05 -030017#include <errno.h>
Arnaldo Carvalho de Melo4ddd3272015-11-16 11:36:29 -030018#include <linux/string.h>
Josh Poimboeufce990912015-12-15 09:39:33 -060019#include <linux/compiler.h>
Arnaldo Carvalho de Melo4ddd3272015-11-16 11:36:29 -030020
21/**
22 * memdup - duplicate region of memory
23 *
24 * @src: memory region to duplicate
25 * @len: memory region length
26 */
27void *memdup(const void *src, size_t len)
28{
29 void *p = malloc(len);
30
31 if (p)
32 memcpy(p, src, len);
33
34 return p;
35}
Wang Nan7d85c432015-11-16 11:42:05 -030036
37/**
38 * strtobool - convert common user inputs into boolean values
39 * @s: input string
40 * @res: result
41 *
42 * This routine returns 0 iff the first character is one of 'Yy1Nn0'.
43 * Otherwise it will return -EINVAL. Value pointed to by res is
44 * updated upon finding a match.
45 */
46int strtobool(const char *s, bool *res)
47{
48 switch (s[0]) {
49 case 'y':
50 case 'Y':
51 case '1':
52 *res = true;
53 break;
54 case 'n':
55 case 'N':
56 case '0':
57 *res = false;
58 break;
59 default:
60 return -EINVAL;
61 }
62 return 0;
63}
Josh Poimboeufce990912015-12-15 09:39:33 -060064
65/**
66 * strlcpy - Copy a C-string into a sized buffer
67 * @dest: Where to copy the string to
68 * @src: Where to copy the string from
69 * @size: size of destination buffer
70 *
71 * Compatible with *BSD: the result is always a valid
72 * NUL-terminated string that fits in the buffer (unless,
73 * of course, the buffer size is zero). It does not pad
74 * out the result like strncpy() does.
75 *
76 * If libc has strlcpy() then that version will override this
77 * implementation:
78 */
Vitaly Chikunov0d65b362019-12-24 20:20:29 +030079#ifdef __clang__
80#pragma clang diagnostic push
81#pragma clang diagnostic ignored "-Wignored-attributes"
82#endif
Josh Poimboeufce990912015-12-15 09:39:33 -060083size_t __weak strlcpy(char *dest, const char *src, size_t size)
84{
85 size_t ret = strlen(src);
86
87 if (size) {
88 size_t len = (ret >= size) ? size - 1 : ret;
89 memcpy(dest, src, len);
90 dest[len] = '\0';
91 }
92 return ret;
93}
Vitaly Chikunov0d65b362019-12-24 20:20:29 +030094#ifdef __clang__
95#pragma clang diagnostic pop
96#endif