io.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * Copyright (c) 2004-2005 Sergey Lyubka <valenok@gmail.com>
  3. * All rights reserved
  4. *
  5. * "THE BEER-WARE LICENSE" (Revision 42):
  6. * Sergey Lyubka wrote this file. As long as you retain this notice you
  7. * can do whatever you want with this stuff. If we meet some day, and you think
  8. * this stuff is worth it, you can buy me a beer in return.
  9. */
  10. #ifndef IO_HEADER_INCLUDED
  11. #define IO_HEADER_INCLUDED
  12. #include <assert.h>
  13. #include <stddef.h>
  14. /*
  15. * I/O buffer descriptor
  16. */
  17. struct io {
  18. char *buf; /* IO Buffer */
  19. size_t size; /* IO buffer size */
  20. size_t head; /* Bytes read */
  21. size_t tail; /* Bytes written */
  22. size_t total; /* Total bytes read */
  23. };
  24. static __inline void
  25. io_clear(struct io *io)
  26. {
  27. assert(io->buf != NULL);
  28. assert(io->size > 0);
  29. io->total = io->tail = io->head = 0;
  30. }
  31. static __inline char *
  32. io_space(struct io *io)
  33. {
  34. assert(io->buf != NULL);
  35. assert(io->size > 0);
  36. assert(io->head <= io->size);
  37. return (io->buf + io->head);
  38. }
  39. static __inline char *
  40. io_data(struct io *io)
  41. {
  42. assert(io->buf != NULL);
  43. assert(io->size > 0);
  44. assert(io->tail <= io->size);
  45. return (io->buf + io->tail);
  46. }
  47. static __inline size_t
  48. io_space_len(const struct io *io)
  49. {
  50. assert(io->buf != NULL);
  51. assert(io->size > 0);
  52. assert(io->head <= io->size);
  53. return (io->size - io->head);
  54. }
  55. static __inline size_t
  56. io_data_len(const struct io *io)
  57. {
  58. assert(io->buf != NULL);
  59. assert(io->size > 0);
  60. assert(io->head <= io->size);
  61. assert(io->tail <= io->head);
  62. return (io->head - io->tail);
  63. }
  64. static __inline void
  65. io_inc_tail(struct io *io, size_t n)
  66. {
  67. assert(io->buf != NULL);
  68. assert(io->size > 0);
  69. assert(io->tail <= io->head);
  70. assert(io->head <= io->size);
  71. io->tail += n;
  72. assert(io->tail <= io->head);
  73. if (io->tail == io->head)
  74. io->head = io->tail = 0;
  75. }
  76. static __inline void
  77. io_inc_head(struct io *io, size_t n)
  78. {
  79. assert(io->buf != NULL);
  80. assert(io->size > 0);
  81. assert(io->tail <= io->head);
  82. io->head += n;
  83. io->total += n;
  84. assert(io->head <= io->size);
  85. }
  86. #endif /* IO_HEADER_INCLUDED */