2 * Wireshark Memory Manager String Utilities
3 * Copyright 2012, Evan Huus <eapache@gmail.com>
5 * Wireshark - Network traffic analyzer
6 * By Gerald Combs <gerald@wireshark.org>
7 * Copyright 1998 Gerald Combs
9 * SPDX-License-Identifier: GPL-2.0-or-later
13 #include "wmem_strutl.h"
20 wmem_strdup(wmem_allocator_t
*allocator
, const char *src
)
24 /* If the string is NULL, just return the string "<NULL>" so that the
25 * callers don't have to bother checking it. */
30 len
= strlen(src
) + 1; /* +1 for the null-terminator */
32 return (char *)memcpy(wmem_alloc(allocator
, len
), src
, len
);
36 wmem_strndup(wmem_allocator_t
*allocator
, const char *src
, const size_t len
)
41 dst
= (char *)wmem_alloc(allocator
, len
+1);
43 for (i
=0; (i
< len
) && src
[i
]; i
++) {
53 wmem_strdup_printf(wmem_allocator_t
*allocator
, const char *fmt
, ...)
59 dst
= wmem_strdup_vprintf(allocator
, fmt
, ap
);
67 _strdup_vasprintf(const char *fmt
, va_list ap
)
72 ret
= vasprintf(&str
, fmt
, ap
);
73 if (ret
== -1 && errno
== ENOMEM
) {
74 /* Out of memory. We have to mimic GLib here and abort. */
75 g_error("%s: failed to allocate memory", G_STRLOC
);
79 #endif /* HAVE_VASPRINTF */
81 #define WMEM_STRDUP_VPRINTF_DEFAULT_BUFFER 256
83 wmem_strdup_vprintf(wmem_allocator_t
*allocator
, const char *fmt
, va_list ap
)
86 char buf
[WMEM_STRDUP_VPRINTF_DEFAULT_BUFFER
];
92 if (allocator
== NULL
) {
93 return _strdup_vasprintf(fmt
, ap
);
98 needed_len
= vsnprintf(buf
, sizeof(buf
), fmt
, ap2
);
101 new_buf_size
= needed_len
+ 1;
102 new_buf
= wmem_alloc(allocator
, new_buf_size
);
104 if (new_buf_size
<= WMEM_STRDUP_VPRINTF_DEFAULT_BUFFER
) {
105 memcpy(new_buf
, buf
, new_buf_size
);
108 vsnprintf(new_buf
, new_buf_size
, fmt
, ap
);
112 /* Return the first occurrence of needle in haystack.
113 * If not found, return NULL.
114 * If either haystack has 0 length, return NULL.
115 * If needle has 0 length, return pointer to haystack. */
117 ws_memmem(const void *_haystack
, size_t haystack_len
,
118 const void *_needle
, size_t needle_len
)
121 return memmem(_haystack
, haystack_len
, _needle
, needle_len
);
123 /* Algorithm copied from GNU's glibc 2.3.2 memmem() under LGPL 2.1+ */
124 const uint8_t *haystack
= _haystack
;
125 const uint8_t *needle
= _needle
;
126 const uint8_t *begin
;
127 const uint8_t *const last_possible
= haystack
+ haystack_len
- needle_len
;
129 if (needle_len
== 0) {
133 if (needle_len
== 1) {
134 return memchr(haystack
, needle
[0], haystack_len
);
137 if (needle_len
> haystack_len
) {
141 for (begin
= haystack
; begin
<= last_possible
; ++begin
) {
142 begin
= memchr(begin
, needle
[0], last_possible
- begin
+ 1);
143 if (begin
== NULL
) break;
144 if (!memcmp(&begin
[1], needle
+ 1, needle_len
- 1)) {
150 #endif /* HAVE_MEMMEM */
154 * Editor modelines - https://www.wireshark.org/tools/modelines.html
159 * indent-tabs-mode: nil
162 * vi: set shiftwidth=4 tabstop=8 expandtab:
163 * :indentSize=4:tabSize=8:noTabs=true: