b7f1e3eec9caed5015916183edbd0c12d11d09d7
[libcext.git] / strdup.h
1 /*
2 * This is free and unencumbered software released into the public domain.
3 *
4 * Anyone is free to copy, modify, publish, use, compile, sell, or
5 * distribute this software, either in source code form or as a compiled
6 * binary, for any purpose, commercial or non-commercial, and by any
7 * means.
8 *
9 * In jurisdictions that recognize copyright laws, the author or authors
10 * of this software dedicate any and all copyright interest in the
11 * software to the public domain. We make this dedication for the benefit
12 * of the public at large and to the detriment of our heirs and
13 * successors. We intend this dedication to be an overt act of
14 * relinquishment in perpetuity of all present and future rights to this
15 * software under copyright law.
16
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
21 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
22 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23 * OTHER DEALINGS IN THE SOFTWARE.
24 *
25 * For more information, please refer to <https://unlicense.org>
26 */
27
28 /* https://git.datadissipation.net */
29 #ifndef STRDUP_H_
30 #define STRDUP_H_ 1
31
32 #ifdef STRDUP_INCLUDE_LIBC
33 #include <stdlib.h>
34 #include <string.h>
35 #endif /* STRDUP_INCLUDE_LIBC */
36
37 #ifndef HAVE_STRDUP
38 #define HAVE_STRDUP 1
39 #define strdup i_strdup_
40 #define strndup i_strndup_
41 char *i_strdup_(const char *s);
42 char *i_strndup_(const char *s, size_t n);
43 #endif /* !HAVE_STRDUP */
44
45 #ifdef STRDUP_IMPLEMENTATION
46 char *
47 i_strdup_(const char *s)
48 {
49 /* avoid calling strlen twice by passing the maximum */
50 return i_strndup_(s, ~(size_t)0);
51 }
52
53 char *
54 i_strndup_(const char *s, size_t n)
55 {
56 char *d;
57 size_t t;
58
59 t = strlen(s) + 1;
60 t = t < n ? t : n;
61 d = malloc(t);
62
63 if (!d) return NULL;
64 *(d + t) = '\0';
65
66 return memcpy(d, s, t - 1);
67 }
68 #endif /* STRDUP_IMPLEMENTATION */
69 #endif /* !STRDUP_H_ */