chunk.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <assert.h>
  4. #include "private.h"
  5. faux_chunk_t *faux_chunk_new(size_t size) {
  6. faux_chunk_t *chunk = NULL;
  7. if (0 == size) // Illegal 0 size
  8. return NULL;
  9. chunk = faux_zmalloc(sizeof(*chunk));
  10. if (!chunk)
  11. return NULL;
  12. // Init
  13. chunk->buf = faux_zmalloc(size);
  14. if (!chunk->buf) {
  15. faux_free(chunk);
  16. return NULL;
  17. }
  18. chunk->size = size;
  19. chunk->start = chunk->buf;
  20. chunk->end = chunk->buf;
  21. return chunk;
  22. }
  23. void faux_chunk_free(faux_chunk_t *chunk) {
  24. // Without assert()
  25. if (!chunk)
  26. return;
  27. faux_free(chunk->buf);
  28. faux_free(chunk);
  29. }
  30. size_t faux_chunk_len(faux_chunk_t *chunk) {
  31. assert(chunk);
  32. if (!chunk)
  33. return 0;
  34. return (chunk->end - chunk->start);
  35. }
  36. ssize_t faux_chunk_inc_len(faux_chunk_t *chunk, size_t inc_len) {
  37. assert(chunk);
  38. if (!chunk)
  39. return -1;
  40. assert((faux_chunk_len(chunk) + inc_len) <= chunk->size);
  41. if ((faux_chunk_len(chunk) + inc_len) > chunk->size)
  42. return -1;
  43. chunk->end += inc_len;
  44. return faux_chunk_len(chunk);
  45. }
  46. ssize_t faux_chunk_dec_len(faux_chunk_t *chunk, size_t dec_len) {
  47. assert(chunk);
  48. if (!chunk)
  49. return -1;
  50. assert(faux_chunk_len(chunk) >= dec_len);
  51. if (faux_chunk_len(chunk) < dec_len)
  52. return -1;
  53. chunk->start += dec_len;
  54. return faux_chunk_len(chunk);
  55. }
  56. ssize_t faux_chunk_size(faux_chunk_t *chunk) {
  57. assert(chunk);
  58. if (!chunk)
  59. return -1;
  60. return chunk->size;
  61. }
  62. void *faux_chunk_buf(faux_chunk_t *chunk) {
  63. assert(chunk);
  64. if (!chunk)
  65. return NULL;
  66. return chunk->buf;
  67. }
  68. void *faux_chunk_write_pos(faux_chunk_t *chunk) {
  69. assert(chunk);
  70. if (!chunk)
  71. return NULL;
  72. return chunk->end;
  73. }
  74. void *faux_chunk_read_pos(faux_chunk_t *chunk) {
  75. assert(chunk);
  76. if (!chunk)
  77. return NULL;
  78. return chunk->start;
  79. }
  80. ssize_t faux_chunk_left(faux_chunk_t *chunk) {
  81. assert(chunk);
  82. if (!chunk)
  83. return -1;
  84. return (chunk->buf + chunk->size - chunk->end);
  85. }