cleaned up some code, removed/improved few comments, better logging
[rxpd.git] / src / rxpd_buffer.c
blobcb584843cf2d3b61581ea2cfca363168a6bee56f
1 /*
2 rxpd_buffer.c - regex policy daemon
4 Copyright (C)
5 2007, Christian Thaeter <ct@pipapo.org>
7 This program is free software; you can redistribute it and/or
8 modify it under the terms of the GNU General Public License as
9 published by the Free Software Foundation; either version 2 of the
10 License, or (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 #include "rxpd.h"
24 struct rxpd_buffer*
25 rxpd_buffer_init (struct rxpd_buffer* self, int fd)
27 self->fd = fd;
28 self->state = RXPD_OK;
29 self->eol = self->eob = self->buffer;
30 self->buffer [4095] = '\0';
31 return self;
35 char*
36 rxpd_buffer_readline (struct rxpd_buffer* self)
38 if (self->eol < self->eob)
40 //there was a line pending, shift buffer left
41 memmove (self->buffer, self->eol+1, self->eob - self->eol - 1);
42 self->eob = (char*)(self->eob - (self->eol - self->buffer + 1));
43 self->eol = self->buffer;
44 // TODO handle \r's
47 do {
48 // find next newline, terminate string there
49 for (char* i = self->buffer; i < self->eob; ++i)
51 if (*i == '\n')
53 *i = '\0';
54 self->eol = i;
55 // have line, return it
56 return (self->eob == self->buffer) ? NULL : self->buffer;
60 // else we have to read
61 if (self->state == RXPD_OK)
63 ssize_t r = 0;
66 r = pth_read (self->fd, self->eob, 4095 - (self->eob - self->buffer));
68 while (r == -1 && errno == EINTR);
70 if (r != -1)
72 if (r == 0)
74 shutdown (self->fd, SHUT_RD);
75 self->state = RXPD_EOF;
77 self->eob += r;
79 else
80 self->state = RXPD_ERROR;
82 } while (self->state == RXPD_OK); // TODO while (!buffer overfulls)
83 return NULL;
87 int
88 rxpd_buffer_printf (struct rxpd_buffer* self, const char* fmt, ...)
90 va_list ap;
91 va_start(ap, fmt);
92 int n = vsnprintf (self->buffer, 4096, fmt, ap);
93 va_end(ap);
95 pth_write (self->fd, self->buffer, n);
97 if (n > 4095)
98 return 0;
100 return 1;