2 * ustream - library for stream buffer management
4 * Copyright (C) 2012 Felix Fietkau <nbd@openwrt.org>
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
24 static void ustream_fd_set_uloop(struct ustream
*s
)
26 struct ustream_fd
*sf
= container_of(s
, struct ustream_fd
, stream
);
27 struct ustream_buf
*buf
;
28 unsigned int flags
= ULOOP_EDGE_TRIGGER
;
30 if (!s
->read_blocked
&& !s
->eof
)
34 if (buf
&& s
->w
.data_bytes
&& !s
->write_error
)
37 uloop_fd_add(&sf
->fd
, flags
);
39 if (flags
& ULOOP_READ
)
40 sf
->fd
.cb(&sf
->fd
, ULOOP_READ
);
43 static void ustream_fd_read_pending(struct ustream_fd
*sf
, bool *update
)
45 struct ustream
*s
= &sf
->stream
;
51 buf
= ustream_reserve(s
, 1, &buflen
);
55 len
= read(sf
->fd
.fd
, buf
, buflen
);
69 ustream_fill_read(s
, len
);
73 static int ustream_fd_write(struct ustream
*s
, const char *buf
, int buflen
, bool more
)
75 struct ustream_fd
*sf
= container_of(s
, struct ustream_fd
, stream
);
82 len
= write(sf
->fd
.fd
, buf
, buflen
);
90 if (errno
== EAGAIN
|| errno
== EWOULDBLOCK
)
97 static void ustream_uloop_cb(struct uloop_fd
*fd
, unsigned int events
)
99 struct ustream_fd
*sf
= container_of(fd
, struct ustream_fd
, fd
);
100 struct ustream
*s
= &sf
->stream
;
103 if (events
& ULOOP_READ
)
104 ustream_fd_read_pending(sf
, &update
);
106 if (events
& ULOOP_WRITE
) {
107 if (ustream_write_pending(s
))
108 ustream_fd_set_uloop(s
);
111 if (!s
->eof
&& fd
->eof
) {
113 ustream_fd_set_uloop(s
);
114 ustream_state_change(s
);
119 static void ustream_fd_free(struct ustream
*s
)
121 struct ustream_fd
*sf
= container_of(s
, struct ustream_fd
, stream
);
123 uloop_fd_delete(&sf
->fd
);
126 void ustream_fd_init(struct ustream_fd
*sf
, int fd
)
128 struct ustream
*s
= &sf
->stream
;
130 ustream_init_defaults(s
);
133 sf
->fd
.cb
= ustream_uloop_cb
;
134 s
->set_read_blocked
= ustream_fd_set_uloop
;
135 s
->write
= ustream_fd_write
;
136 s
->free
= ustream_fd_free
;
137 ustream_fd_set_uloop(s
);