version 0.1.6
[fms.git] / libs / shttpd / io.h
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
11 #ifndef IO_HEADER_INCLUDED
12 #define IO_HEADER_INCLUDED
13
14 #include <assert.h>
15 #include <stddef.h>
16
17 /*
18  * I/O buffer descriptor
19  */
20 struct io {
21         char            *buf;           /* IO Buffer                    */
22         size_t          size;           /* IO buffer size               */
23         size_t          head;           /* Bytes read                   */
24         size_t          tail;           /* Bytes written                */
25         size_t          total;          /* Total bytes read             */
26 };
27
28 static __inline void
29 io_clear(struct io *io)
30 {
31         assert(io->buf != NULL);
32         assert(io->size > 0);
33         io->total = io->tail = io->head = 0;
34 }
35
36 static __inline char *
37 io_space(struct io *io)
38 {
39         assert(io->buf != NULL);
40         assert(io->size > 0);
41         assert(io->head <= io->size);
42         return (io->buf + io->head);
43 }
44
45 static __inline char *
46 io_data(struct io *io)
47 {
48         assert(io->buf != NULL);
49         assert(io->size > 0);
50         assert(io->tail <= io->size);
51         return (io->buf + io->tail);
52 }
53
54 static __inline size_t
55 io_space_len(const struct io *io)
56 {
57         assert(io->buf != NULL);
58         assert(io->size > 0);
59         assert(io->head <= io->size);
60         return (io->size - io->head);
61 }
62
63 static __inline size_t
64 io_data_len(const struct io *io)
65 {
66         assert(io->buf != NULL);
67         assert(io->size > 0);
68         assert(io->head <= io->size);
69         assert(io->tail <= io->head);
70         return (io->head - io->tail);
71 }
72
73 static __inline void
74 io_inc_tail(struct io *io, size_t n)
75 {
76         assert(io->buf != NULL);
77         assert(io->size > 0);
78         assert(io->tail <= io->head);
79         assert(io->head <= io->size);
80         io->tail += n;
81         assert(io->tail <= io->head);
82         if (io->tail == io->head)
83                 io->head = io->tail = 0;
84 }
85
86 static __inline void
87 io_inc_head(struct io *io, size_t n)
88 {
89         assert(io->buf != NULL);
90         assert(io->size > 0);
91         assert(io->tail <= io->head);
92         io->head += n;
93         io->total += n;
94         assert(io->head <= io->size);
95 }
96
97 #endif /* IO_HEADER_INCLUDED */