libbsock/bsock.c

140 lines
2.6 KiB
C

#include <stdlib.h>
#include "bsock.h"
#include "ringbuf.h"
static ssize_t
bsock_posix_io_read(void *ctx, void *buf, size_t nbytes)
{
return read((int)(uintptr_t)ctx, buf, nbytes);
}
static ssize_t
bsock_posix_io_write(void *ctx, void *buf, size_t nbytes)
{
return write((int)(uintptr_t)ctx, buf, nbytes);
}
static ssize_t
bsock_posix_io_readv(void *ctx, const struct iovec *iovec, int nvec)
{
return readv((int)(uintptr_t)ctx, iovec, nvec);
}
static ssize_t
bsock_posix_io_writev(void *ctx, const struct iovec *iovec, int nvec)
{
return writev((int)(uintptr_t)ctx, iovec, nvec);
}
struct bsock_ringbuf_io
bsock_io_posix()
{
struct bsock_ringbuf_io ret;
ret.read = &bsock_posix_io_read;
ret.write = &bsock_posix_io_write;
ret.readv = &bsock_posix_io_readv;
ret.writev = &bsock_posix_io_writev;
return ret;
}
struct bsock *
bsock_create(void *io_ctx, struct bsock_ringbuf_io *io, size_t rbuf_sz, size_t wbuf_sz)
{
if (rbuf_sz == 0) {
errno = EINVAL;
return NULL;
}
struct bsock *bsock = malloc(sizeof(struct bsock));
if (bsock == NULL) {
errno = ENOMEM;
return NULL;
}
struct bsock_ringbuf rbuf = { 0 }, wbuf = { 0 };
char *buf = malloc(rbuf_sz);
if (buf == NULL) {
errno = ENOMEM;
goto fail;
}
bsock_ringbuf_init(&rbuf, buf, rbuf_sz);
if (wbuf_sz > 0) {
buf = malloc(wbuf_sz);
if (buf == NULL) {
errno = ENOMEM;
goto fail;
}
} else {
buf = NULL;
}
bsock_ringbuf_init(&wbuf, buf, wbuf_sz);
bsock_init(bsock, io_ctx, io, &rbuf, &wbuf);
return bsock;
fail:
if (bsock != NULL) {
free(bsock);
}
if (rbuf.buf != NULL) {
free(rbuf.buf);
}
if (wbuf.buf != NULL) {
free(wbuf.buf);
}
return NULL;
}
void
bsock_free(struct bsock *bsock)
{
free(bsock->rbuf.buf);
free(bsock->wbuf.buf);
free(bsock);
}
int
bsock_write(struct bsock *bsock, char *buf, size_t len)
{
return bsock_ringbuf_write(&bsock->wbuf, bsock->io_ctx, &bsock->io, buf, len);
}
int
bsock_read(struct bsock *bsock, char *buf, size_t len)
{
return bsock_ringbuf_read(&bsock->rbuf, buf, len);
}
int
bsock_peek(struct bsock *bsock, char *buf, size_t len)
{
return bsock_ringbuf_peek(&bsock->rbuf, buf, len);
}
int
bsock_flush(struct bsock *bsock)
{
return bsock_ringbuf_flush(&bsock->wbuf, bsock->io_ctx, &bsock->io,
bsock_ringbuf_size(&bsock->wbuf));
}
int
bsock_poll(struct bsock *bsock)
{
return bsock_ringbuf_poll(&bsock->rbuf, bsock->io_ctx, &bsock->io,
bsock_ringbuf_free_size(&bsock->rbuf));
}
int
bsock_read_avail_size(struct bsock *sock)
{
return bsock_ringbuf_size(&sock->rbuf);
}
int
bsock_write_avail_size(struct bsock *sock)
{
return bsock_ringbuf_free_size(&sock->wbuf);
}