2 * This file is part of DisOrder
3 * Copyright (C) 2013 Richard Kettlewell
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 /** @file lib/socketio.c
19 * @brief Buffered socket IO
26 #include <sys/types.h>
28 # include <sys/socket.h>
34 void socketio_init(struct socketio
*sio
, SOCKET sd
) {
36 sio
->inputptr
= sio
->inputlimit
= sio
->input
;
41 int socketio_write(struct socketio
*sio
, const void *buffer
, size_t n
) {
44 chunk
= n
> sizeof sio
->output ?
sizeof sio
->output
: n
;
46 memcpy(sio
->output
+ sio
->outputused
, buffer
, chunk
);
47 sio
->outputused
+= chunk
;
48 buffer
= (char *)buffer
+ chunk
;
51 if(sio
->outputused
== sizeof sio
->output
)
52 if(socketio_flush(sio
))
58 static int socketio_fill(struct socketio
*sio
) {
59 int n
= recv(sio
->sd
, sio
->input
, sizeof sio
->input
, 0);
61 sio
->error
= n
< 0 ?
socket_error() : -1;
64 sio
->inputptr
= sio
->input
;
65 sio
->inputlimit
= sio
->input
+ n
;
69 int socketio_getc(struct socketio
*sio
) {
70 if(sio
->inputptr
>= sio
->inputlimit
) {
71 if(socketio_fill(sio
))
74 return *sio
->inputptr
++;
77 int socketio_flush(struct socketio
*sio
) {
79 while(written
< sio
->outputused
) {
80 int n
= send(sio
->sd
, sio
->output
+ written
, sio
->outputused
- written
, 0);
82 sio
->error
= socket_error();
91 void socketio_close(struct socketio
*sio
) {