aboutsummaryrefslogtreecommitdiff
path: root/src/chunk.h
blob: f37a2f31d673f44163874241b2d2d4b6cd94c8e6 (plain)
  1. #ifndef _CHUNK_H_
  2. #define _CHUNK_H_
  3. #include <string.h>
  4. #include <ctype.h>
  5. #include <stdlib.h>
  6. #include <assert.h>
  7. #include "buffer.h"
  8. typedef struct {
  9. const unsigned char *data;
  10. int len;
  11. int alloc;
  12. } chunk;
  13. static inline void chunk_free(chunk *c)
  14. {
  15. if (c->alloc)
  16. free((char *)c->data);
  17. c->data = NULL;
  18. c->alloc = 0;
  19. c->len = 0;
  20. }
  21. static inline void chunk_ltrim(chunk *c)
  22. {
  23. assert(!c->alloc);
  24. while (c->len && isspace(c->data[0])) {
  25. c->data++;
  26. c->len--;
  27. }
  28. }
  29. static inline void chunk_rtrim(chunk *c)
  30. {
  31. while (c->len > 0) {
  32. if (!isspace(c->data[c->len - 1]))
  33. break;
  34. c->len--;
  35. }
  36. }
  37. static inline void chunk_trim(chunk *c)
  38. {
  39. chunk_ltrim(c);
  40. chunk_rtrim(c);
  41. }
  42. static inline int chunk_strchr(chunk *ch, int c, int offset)
  43. {
  44. const unsigned char *p = memchr(ch->data + offset, c, ch->len - offset);
  45. return p ? (int)(p - ch->data) : ch->len;
  46. }
  47. static inline unsigned char *chunk_to_cstr(chunk *c)
  48. {
  49. unsigned char *str;
  50. str = malloc(c->len + 1);
  51. memcpy(str, c->data, c->len);
  52. str[c->len] = 0;
  53. return str;
  54. }
  55. static inline chunk chunk_literal(const char *data)
  56. {
  57. chunk c = {(const unsigned char *)data, data ? strlen(data) : 0, 0};
  58. return c;
  59. }
  60. static inline chunk chunk_dup(const chunk *ch, int pos, int len)
  61. {
  62. chunk c = {ch->data + pos, len, 0};
  63. return c;
  64. }
  65. static inline chunk chunk_buf_detach(strbuf *buf)
  66. {
  67. chunk c;
  68. c.len = buf->size;
  69. c.data = strbuf_detach(buf);
  70. c.alloc = 1;
  71. return c;
  72. }
  73. #endif