aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/iobuf.c133
1 files changed, 133 insertions, 0 deletions
diff --git a/src/iobuf.c b/src/iobuf.c
new file mode 100644
index 0000000..083978b
--- /dev/null
+++ b/src/iobuf.c
@@ -0,0 +1,133 @@
1// iobuf.c --- Input/Output buffer -*- C -*-
2//
3// Copyright (c) 2026 Martin Michalec <martin@michalec.dev>
4//
5// SPDX-License-Identifier: MIT
6//
7// This file is part of COSMOS Codebase.
8//
9// Commentary:
10//
11// Code:
12
13#include "iobuf.h"
14#include "dbg.h"
15
16#define DBG_ASSERT_IOBUF(iobuf) /* TODO(cmmm): check the invariant */
17
18struct iobuf
19iobuf_from (struct ms ms)
20{
21 struct iobuf iobuf = {
22 .beg = ms.beg,
23 .rhead = ms.beg,
24 .whead = ms.beg,
25 .end = ms.end,
26 };
27 DBG_ASSERT_IOBUF (iobuf);
28 return iobuf;
29}
30
31struct mv *
32iobuf_rmv (struct iobuf *buf)
33{
34 DBG_ASSERT_NN ( buf);
35 DBG_ASSERT_IOBUF (*buf);
36 return (struct mv *) &buf->rhead;
37}
38
39struct ms *
40iobuf_wms (struct iobuf *buf)
41{
42 DBG_ASSERT_NN ( buf);
43 DBG_ASSERT_IOBUF (*buf);
44 return (struct ms *) &buf->whead;
45}
46
47usz
48iobuf_sz (struct iobuf iobuf)
49{
50 DBG_ASSERT_IOBUF (iobuf);
51 return iobuf.end - iobuf.beg;
52}
53
54usz
55iobuf_isz (struct iobuf iobuf)
56{
57 DBG_ASSERT_IOBUF (iobuf);
58 return iobuf.whead - iobuf.rhead;
59}
60
61usz
62iobuf_osz (struct iobuf iobuf)
63{
64 DBG_ASSERT_IOBUF (iobuf);
65 return iobuf.end - iobuf.whead;
66}
67
68usz
69iobuf_rsz (struct iobuf iobuf)
70{
71 DBG_ASSERT_IOBUF (iobuf);
72 return iobuf.rhead - iobuf.beg;
73}
74
75usz
76iobuf_wsz (struct iobuf iobuf)
77{
78 DBG_ASSERT_IOBUF (iobuf);
79 return iobuf.rhead - iobuf.beg;
80}
81
82usz
83iobuf_ospc (struct iobuf iobuf)
84{
85 DBG_ASSERT_IOBUF (iobuf);
86 return iobuf.end - iobuf.whead;
87}
88
89#include <string.h> // TODO(cmmm): remove libc dep
90void
91iobuf_compact (struct iobuf *iobuf)
92{
93 DBG_ASSERT_NN ( iobuf);
94 DBG_ASSERT_IOBUF (*iobuf);
95
96 if (iobuf->rhead == iobuf->beg)
97 return;
98
99 usz unread = iobuf->whead - iobuf->rhead;
100 if (unread)
101 memmove (iobuf->beg, iobuf->rhead, unread);
102
103 iobuf->rhead = (u8 *) iobuf->beg;
104 iobuf->whead = (u8 *) iobuf->beg + unread;
105}
106
107
108#ifndef IOBUF_NO_FEAT_UNISTD
109
110#include <unistd.h>
111int iobuf_read (struct iobuf *iobuf, int fd)
112{
113 DBG_ASSERT_NN ( iobuf);
114 DBG_ASSERT_IOBUF (*iobuf);
115
116 iobuf_compact (iobuf);
117
118 usz avail = iobuf->end - iobuf->whead;
119 if (avail == 0)
120 return 0;
121
122 isz bytes_read = read (fd, iobuf->whead, avail);
123 if (bytes_read == -1)
124 return -1;
125
126 iobuf->whead = (u8 *) iobuf->whead + bytes_read;
127
128 return bytes_read;
129}
130
131#endif // IOBUF_NO_FEAT_UNISTD
132
133// iobuf.c ends here