Debian Codegraph @

src/fundamental/iovec-util.h

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 #pragma once
3
4 #if !SD_BOOT
5 #include <sys/uio.h>
6 #endif
7
8 #include "assert-util.h" /* IWYU pragma: keep */
9 #include "macro.h"
10
11 #if SD_BOOT
12 /* struct iovec is a POSIX userspace construct. Let's introduce it also in EFI mode, it's just so useful */
13 struct iovec {
14 void *iov_base;
15 size_t iov_len;
16 };
17 #endif
18
19 /* This accepts both const and non-const pointers */
20 #define IOVEC_MAKE(base, len) \
21 (struct iovec) { \
22 .iov_base = (void*) (base), \
23 .iov_len = (len), \
24 }
25
26 static inline struct iovec* iovec_shift(const struct iovec *iovec, size_t shift, struct iovec *ret) {
27 assert(iovec);
28 assert(ret);
29
30 /* This returns an empty iovec when 'shift' is larger or equals to the input iovec length.
31 * The 'iovec' and 'ret' can point to the same object. */
32
33 *ret = IOVEC_MAKE(iovec->iov_len > shift ? (uint8_t*) iovec->iov_base + shift : NULL,
34 LESS_BY(iovec->iov_len, shift));
35 return ret;
36 }
37
38 #define IOVEC_SHIFT(iov, shift) \
39 *iovec_shift(iov, shift, &(struct iovec){})
40
41 static inline struct iovec* iovec_inc(struct iovec *iovec, size_t shift) {
42 return iovec_shift(iovec, shift, iovec);
43 }
44
45 static inline void iovec_done(struct iovec *iovec) {
46 /* A _cleanup_() helper that frees the iov_base in the iovec */
47 assert(iovec);
48
49 iovec->iov_base = mfree(iovec->iov_base);
50 iovec->iov_len = 0;
51 }
52
53 static inline void iovec_done_many_and_free(struct iovec *iovec, size_t n) {
54 if (n > 0) {
55 assert(iovec);
56 FOREACH_ARRAY(j, iovec, n)
57 iovec_done(j);
58 }
59 free(iovec);
60 }
61
62 static inline bool iovec_is_set(const struct iovec *iovec) {
63 /* Checks if the iovec points to a non-empty chunk of memory */
64 return iovec && iovec->iov_len > 0 && iovec->iov_base;
65 }
66
67 static inline bool iovec_is_valid(const struct iovec *iovec) {
68 /* Checks if the iovec is either NULL, empty or points to a valid bit of memory */
69 return !iovec || iovec->iov_base || iovec->iov_len == 0;
70 }