skalibs

Mirror/fork of https://skarnet.org/software/skalibs/
git clone https://ccx.te2000.cz/git/skalibs
Log | Files | Refs | README | LICENSE

cbuffer.h (1845B)


      1 /* ISC license. */
      2 
      3 #ifndef SKALIBS_CBUFFER_H
      4 #define SKALIBS_CBUFFER_H
      5 
      6 #include <sys/uio.h>
      7 #include <string.h>
      8 
      9 #include <skalibs/gccattributes.h>
     10 
     11 typedef struct cbuffer_s cbuffer, *cbuffer_ref ;
     12 struct cbuffer_s
     13 {
     14   char *x ;
     15   size_t a ; /* total length */
     16   size_t p ; /* head */
     17   size_t n ; /* tail */
     18 } ;
     19 #define CBUFFER_ZERO { 0, 0, 0, 0 }
     20 
     21  /*
     22     Circular buffers need to be 1 char bigger than the storage space,
     23     so that the head == tail case is nonambiguous (empty).
     24  */
     25 
     26 #define CBUFFER_INIT(buf, len) { (buf), (len), 0, 0 }
     27 extern int cbuffer_init (cbuffer *, char *, size_t) ;
     28 
     29 
     30  /* Writing */
     31 
     32 extern size_t cbuffer_put (cbuffer *, char const *, size_t) ;
     33 extern size_t cbuffer_putv (cbuffer *, struct iovec const *, unsigned int) ;
     34 #define cbuffer_puts(b, s) cbuffer_put(b, (s), strlen(s))
     35 
     36 #define cbuffer_UNPUT(b, w) ((b)->n = ((b)->a + (b)->n - w) % (b)->a, w) ;
     37 extern size_t cbuffer_unput (cbuffer *, size_t) ;
     38 extern void cbuffer_wpeek (cbuffer const *, struct iovec *) ;
     39 #define cbuffer_WSEEK(b, w) ((b)->n = ((b)->n + (w)) % (b)->a, w)
     40 extern size_t cbuffer_wseek (cbuffer *, size_t) ;
     41 
     42 
     43  /* Reading */
     44 
     45 extern size_t cbuffer_get (cbuffer *, char *, size_t) ;
     46 extern size_t cbuffer_getv (cbuffer *, struct iovec const *, unsigned int) ;
     47 
     48 #define cbuffer_UNGET(b, n) ((b)->p = ((b)->a + (b)->p - n) % (b)->a, n) ;
     49 extern size_t cbuffer_unget (cbuffer *, size_t) ;
     50 extern void cbuffer_rpeek (cbuffer const *, struct iovec *) ;
     51 #define cbuffer_RSEEK(b, n) ((b)->p = ((b)->p + (n)) % (b)->a, n)
     52 extern size_t cbuffer_rseek (cbuffer *, size_t) ;
     53 
     54 
     55  /* Utility */
     56 
     57 #define cbuffer_len(b) ((size_t)(((b)->a - (b)->p + (b)->n) % (b)->a))
     58 #define cbuffer_available(b) ((size_t)(((b)->a - (b)->n + (b)->p - 1) % (b)->a))
     59 #define cbuffer_isempty(b) (!cbuffer_len(b))
     60 #define cbuffer_isfull(b) (!cbuffer_available(b))
     61 
     62 #endif