buf.h 1.7 KB

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