]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/memory-util.h
cryptsetup: small refactoring
[thirdparty/systemd.git] / src / basic / memory-util.h
CommitLineData
0a970718
LP
1/* SPDX-License-Identifier: LGPL-2.1+ */
2#pragma once
3
4#include <inttypes.h>
5#include <stdbool.h>
6#include <string.h>
7#include <sys/types.h>
8
9#include "macro.h"
10
11size_t page_size(void) _pure_;
12#define PAGE_ALIGN(l) ALIGN_TO((l), page_size())
13
14/* Normal memcpy requires src to be nonnull. We do nothing if n is 0. */
15static inline void memcpy_safe(void *dst, const void *src, size_t n) {
16 if (n == 0)
17 return;
18 assert(src);
19 memcpy(dst, src, n);
20}
21
22/* Normal memcmp requires s1 and s2 to be nonnull. We do nothing if n is 0. */
23static inline int memcmp_safe(const void *s1, const void *s2, size_t n) {
24 if (n == 0)
25 return 0;
26 assert(s1);
27 assert(s2);
28 return memcmp(s1, s2, n);
29}
30
31/* Compare s1 (length n1) with s2 (length n2) in lexicographic order. */
32static inline int memcmp_nn(const void *s1, size_t n1, const void *s2, size_t n2) {
33 return memcmp_safe(s1, s2, MIN(n1, n2))
34 ?: CMP(n1, n2);
35}
36
37#define memzero(x,l) \
38 ({ \
39 size_t _l_ = (l); \
40 void *_x_ = (x); \
41 _l_ == 0 ? _x_ : memset(_x_, 0, _l_); \
42 })
43
44#define zero(x) (memzero(&(x), sizeof(x)))
45
46bool memeqzero(const void *data, size_t length);
47
48#define eqzero(x) memeqzero(x, sizeof(x))
49
50static inline void *mempset(void *s, int c, size_t n) {
51 memset(s, c, n);
52 return (uint8_t*)s + n;
53}
090a9c1e
LP
54
55/* Normal memmem() requires haystack to be nonnull, which is annoying for zero-length buffers */
56static inline void *memmem_safe(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen) {
57
58 if (needlelen <= 0)
59 return (void*) haystack;
60
61 if (haystacklen < needlelen)
62 return NULL;
63
64 assert(haystack);
65 assert(needle);
66
67 return memmem(haystack, haystacklen, needle, needlelen);
68}
69
70#if HAVE_EXPLICIT_BZERO
71static inline void* explicit_bzero_safe(void *p, size_t l) {
72 if (l > 0)
73 explicit_bzero(p, l);
74
75 return p;
76}
77#else
78void *explicit_bzero_safe(void *p, size_t l);
79#endif