// iobuf.c --- Input/Output buffer -*- C -*- // // Copyright (c) 2026 Martin Michalec // // 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 // 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 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