aboutsummaryrefslogtreecommitdiff
path: root/src/iobuf.c
blob: 083978bb86c1912bc66e079bde161343d62a3ee8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
// iobuf.c --- Input/Output buffer                                     -*- C -*-
//
// Copyright (c) 2026 Martin Michalec <martin@michalec.dev>
//
// SPDX-License-Identifier: MIT
//
// This file is part of COSMOS Codebase.
//
// Commentary:
//
// Code:

#include "iobuf.h"
#include "dbg.h"

#define DBG_ASSERT_IOBUF(iobuf) /* TODO(cmmm): check the invariant */

struct iobuf
iobuf_from (struct ms ms)
{
  struct iobuf iobuf = {
    .beg   = ms.beg,
    .rhead = ms.beg,
    .whead = ms.beg,
    .end   = ms.end,
  };
  DBG_ASSERT_IOBUF (iobuf);
  return iobuf;
}

struct mv *
iobuf_rmv (struct iobuf *buf)
{
  DBG_ASSERT_NN    ( buf);
  DBG_ASSERT_IOBUF (*buf);
  return (struct mv *) &buf->rhead;
}

struct ms *
iobuf_wms (struct iobuf *buf)
{
  DBG_ASSERT_NN    ( buf);
  DBG_ASSERT_IOBUF (*buf);
  return (struct ms *) &buf->whead;
}

usz
iobuf_sz (struct iobuf iobuf)
{
  DBG_ASSERT_IOBUF (iobuf);
  return iobuf.end - iobuf.beg;
}

usz
iobuf_isz (struct iobuf iobuf)
{
  DBG_ASSERT_IOBUF (iobuf);
  return iobuf.whead - iobuf.rhead;
}

usz
iobuf_osz (struct iobuf iobuf)
{
  DBG_ASSERT_IOBUF (iobuf);
  return iobuf.end - iobuf.whead;
}

usz
iobuf_rsz (struct iobuf iobuf)
{
  DBG_ASSERT_IOBUF (iobuf);
  return iobuf.rhead - iobuf.beg;
}

usz
iobuf_wsz (struct iobuf iobuf)
{
  DBG_ASSERT_IOBUF (iobuf);
  return iobuf.rhead - iobuf.beg;
}

usz
iobuf_ospc (struct iobuf iobuf)
{
  DBG_ASSERT_IOBUF (iobuf);
  return iobuf.end - iobuf.whead;
}

#include <string.h>             // TODO(cmmm): remove libc dep
void
iobuf_compact (struct iobuf *iobuf)
{
  DBG_ASSERT_NN    ( iobuf);
  DBG_ASSERT_IOBUF (*iobuf);

  if (iobuf->rhead == iobuf->beg)
    return;

  usz unread = iobuf->whead - iobuf->rhead;
  if (unread)
    memmove (iobuf->beg, iobuf->rhead, unread);

  iobuf->rhead = (u8 *) iobuf->beg;
  iobuf->whead = (u8 *) iobuf->beg + unread;
}


#ifndef IOBUF_NO_FEAT_UNISTD

#include <unistd.h>
int iobuf_read (struct iobuf *iobuf, int fd)
{
  DBG_ASSERT_NN    ( iobuf);
  DBG_ASSERT_IOBUF (*iobuf);

  iobuf_compact (iobuf);

  usz avail = iobuf->end - iobuf->whead;
  if (avail == 0)
    return 0;

  isz bytes_read = read (fd, iobuf->whead, avail);
  if (bytes_read == -1)
    return -1;

  iobuf->whead = (u8 *) iobuf->whead + bytes_read;

  return bytes_read;
}

#endif // IOBUF_NO_FEAT_UNISTD

// iobuf.c ends here