chiark / gitweb /
ab43ca5b51646ca8765c37e3f7dc59b08d7b97f5
[elogind.git] / src / basic / io-util.h
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 #pragma once
3
4 /***
5   Copyright 2010 Lennart Poettering
6 ***/
7
8 #include <stdbool.h>
9 #include <stddef.h>
10 #include <stdint.h>
11 #include <sys/types.h>
12 #include <sys/uio.h>
13
14 #include "macro.h"
15 #include "time-util.h"
16
17 int flush_fd(int fd);
18
19 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll);
20 int loop_read_exact(int fd, void *buf, size_t nbytes, bool do_poll);
21 int loop_write(int fd, const void *buf, size_t nbytes, bool do_poll);
22
23 int pipe_eof(int fd);
24
25 int fd_wait_for_event(int fd, int event, usec_t timeout);
26
27 ssize_t sparse_write(int fd, const void *p, size_t sz, size_t run_length);
28
29 static inline size_t IOVEC_TOTAL_SIZE(const struct iovec *i, size_t n) {
30         size_t j, r = 0;
31
32         for (j = 0; j < n; j++)
33                 r += i[j].iov_len;
34
35         return r;
36 }
37
38 static inline size_t IOVEC_INCREMENT(struct iovec *i, size_t n, size_t k) {
39         size_t j;
40
41         for (j = 0; j < n; j++) {
42                 size_t sub;
43
44                 if (_unlikely_(k <= 0))
45                         break;
46
47                 sub = MIN(i[j].iov_len, k);
48                 i[j].iov_len -= sub;
49                 i[j].iov_base = (uint8_t*) i[j].iov_base + sub;
50                 k -= sub;
51         }
52
53         return k;
54 }
55
56 static inline bool FILE_SIZE_VALID(uint64_t l) {
57         /* ftruncate() and friends take an unsigned file size, but actually cannot deal with file sizes larger than
58          * 2^63 since the kernel internally handles it as signed value. This call allows checking for this early. */
59
60         return (l >> 63) == 0;
61 }
62
63 static inline bool FILE_SIZE_VALID_OR_INFINITY(uint64_t l) {
64
65         /* Same as above, but allows one extra value: -1 as indication for infinity. */
66
67         if (l == (uint64_t) -1)
68                 return true;
69
70         return FILE_SIZE_VALID(l);
71
72 }
73
74 #define IOVEC_INIT(base, len) { .iov_base = (base), .iov_len = (len) }
75 #define IOVEC_MAKE(base, len) (struct iovec) IOVEC_INIT(base, len)
76 #define IOVEC_INIT_STRING(string) IOVEC_INIT((char*) string, strlen(string))
77 #define IOVEC_MAKE_STRING(string) (struct iovec) IOVEC_INIT_STRING(string)