libbsock/ringbuf.h

96 lines
2.1 KiB
C

#pragma once
#include <sys/uio.h>
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/* Both functions should return -1 on error otherwise the # of bytes written. errno should be used
* to set the error code */
typedef ssize_t (*bsock_ringbuf_io_fn)(void *ctx, void *buf, size_t nbytes);
typedef ssize_t (*bsock_ringbuf_iov_fn)(void *ctx, const struct iovec *iov, int iovcnt);
struct bsock_ringbuf_io {
bsock_ringbuf_io_fn read;
bsock_ringbuf_io_fn write;
bsock_ringbuf_iov_fn readv;
bsock_ringbuf_iov_fn writev;
};
struct bsock_ringbuf {
char *buf;
char *start;
char *end;
size_t sz;
size_t max_sz;
};
static inline size_t
bsock_ringbuf_size(struct bsock_ringbuf *rb)
{
return rb->sz;
}
static inline size_t
bsock_ringbuf_max_size(struct bsock_ringbuf *rb)
{
return rb->max_sz;
}
static inline size_t
bsock_ringbuf_free_size(struct bsock_ringbuf *rb)
{
return bsock_ringbuf_max_size(rb) - bsock_ringbuf_size(rb);
}
static inline void
bsock_ringbuf_init(struct bsock_ringbuf *rb, char *buf, size_t sz)
{
rb->buf = buf;
rb->sz = 0;
rb->end = buf;
rb->max_sz = sz;
rb->start = buf;
}
/**
* returns:
* success: # of bytes read
* failure: -1 + errno (ERANGE if not enough data present)
*/
int bsock_ringbuf_peek(struct bsock_ringbuf *rb, char *buf, size_t len);
/**
* returns:
* success: # of bytes read
* failure: -1 + errno (ERANGE if not enough data present)
*/
int bsock_ringbuf_read(struct bsock_ringbuf *rb, char *buf, size_t len);
/**
* returns:
* success: # of bytes written
* failure: -1 + errno
*/
int bsock_ringbuf_write(struct bsock_ringbuf *rb, void *ctx, struct bsock_ringbuf_io *io, char *buf,
size_t len);
/**
* returns:
* success: # of bytes read
* failure: -1 + errno (ERANGE if not enough data present)
*/
int bsock_ringbuf_poll(struct bsock_ringbuf *rb, void *ctx, struct bsock_ringbuf_io *io,
size_t len);
/**
* returns:
* success: # of bytes written
* failure: -1 + errno (ERANGE if not enough data present)
*/
int bsock_ringbuf_flush(struct bsock_ringbuf *rb, void *ctx, struct bsock_ringbuf_io *io,
size_t len);