piece-chain

Research & implementation of a Piece Chain
git clone git://src.gearsix.net/piece-chain.gitpiece-chain.zip
Log | Files | Refs | Atom | README

buf.h (raw) (1720B)


   1 /* A piece chain implementation.
   2 	gearsix, 2022 */
   3 #ifndef PIECETABLE
   4 #define PIECETABLE
   5 
   6 #ifdef __cplusplus
   7 extern "C" {
   8 #endif
   9 
  10 
  11 #include <stdio.h>
  12 
  13 /* Points to a file (`f`), which contains a string that starts at
  14 	`off`, with length of `len`. `prev` and `next` point to	the
  15 	previous and next items in the table. */
  16 typedef struct Piece {
  17 	FILE *f;
  18 	size_t off, len;
  19 	struct Piece *prev, *next;
  20 } Piece;
  21 
  22 /* Holds a doubly-linked `Piece` list, starting at `tail`, ending at
  23 	`head`. `pos` points to the last addressed `Piece`. `size` is the
  24 	sum length of all `len` values of all `Piece` items in the list.
  25 	`idx` is the last addressed	index in the chain. `read` and `append`
  26 	point to the original file and any data to be added. */
  27 typedef struct Buf {
  28 	FILE *read, *append;
  29 	size_t size, idx;
  30 	struct Piece *tail, *pos, *head;
  31 } Buf;
  32 
  33 /* Allocates & initialises a `Buf`. If `append` is NULL, nothing is
  34 	allocated or initialised and NULL is returned. */
  35 Buf *
  36 bufinit(FILE *read, FILE *append);
  37 
  38 /* Frees `b` and all `Piece` items associated with it. */
  39 void
  40 buffree(Buf *b);
  41 
  42 /* Set `b->idx` to `pos` and `b->pos` to the `Piece` in the chain,
  43 	where the start of `b->pos->next` is `pos`. */
  44 Piece *
  45 bufidx(Buf *b, size_t pos);
  46 
  47 /* Adds a new `Piece` to the chain, at `pos` (found using `bufidx`).
  48 	`s` will be appended to `b->append` and the new `Piece` will
  49 	reflect the appended data. */
  50 size_t
  51 bufins(Buf *b, size_t pos, const char *s);
  52 
  53 /* Removed all pieces from index `pos` to `pos+num`. `pos` and
  54 	`pos+num` are found using `bufidx`. */
  55 size_t
  56 bufdel(Buf *b, size_t pos, int num);
  57 
  58 /* writes all data in `b` to `f`. */
  59 size_t
  60 bufout(Buf *b, FILE *f);
  61 
  62 
  63 #ifdef __cplusplus
  64 }
  65 #endif
  66 
  67 #endif /* PIECETABLE */