summaryrefslogtreecommitdiff
path: root/src/cbuffer.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/cbuffer.c')
-rw-r--r--src/cbuffer.c107
1 files changed, 107 insertions, 0 deletions
diff --git a/src/cbuffer.c b/src/cbuffer.c
new file mode 100644
index 0000000..1242496
--- /dev/null
+++ b/src/cbuffer.c
@@ -0,0 +1,107 @@
+/*
+ * Venus GPS Server
+ *
+ * Copyright (C) 2010 by Multi-Tech Systems
+ *
+ * Author: James Maki <jmaki@multitech.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+#include "log.h"
+#include "cbuffer.h"
+#include "utils.h"
+#include <errno.h>
+
+int buffered_write(int fd, struct cbuffer *buf) {
+ int i;
+ int len;
+ int count = buffer_used(buf);
+ int total = 0;
+
+ i = buf->read_index;
+ if(i + count > buffer_size(buf)) {
+ len = full_write(fd, buf->buffer + i, buffer_size(buf) - i);
+ if(len <= 0) {
+ log_error("full_write failed errno: %d", errno);
+ return len;
+ }
+
+ total += len;
+ count -= len;
+
+ if(len < buffer_size(buf) - i) {
+ buf->read_index = i + len;
+ return total;
+ }
+
+ i = 0;
+ }
+
+ len = full_write(fd, buf->buffer + i, count);
+ if(len <= 0) {
+ if(total) {
+ return total;
+ } else {
+ log_error("full_write failed errno: %d", errno);
+ return len;
+ }
+ }
+ buf->read_index = i + len;
+ total += len;
+
+ return total;
+}
+
+int buffered_read(int fd, struct cbuffer *buf) {
+ int i;
+ int len;
+ int count = buffer_free(buf);
+ int total = 0;
+
+ i = buf->write_index;
+ if(i + count > buffer_size(buf)) {
+ len = safe_read(fd, buf->buffer + i, buffer_size(buf) - i);
+ if(len <= 0) {
+ log_warning("safe_read failed errno: %d", errno);
+ return len;
+ }
+
+ total += len;
+ count -= len;
+
+ if(len < buffer_size(buf) - i) {
+ buf->write_index = i + len;
+ return total;
+ }
+
+ i = 0;
+ }
+
+ len = safe_read(fd, buf->buffer + i, count);
+ if(len <= 0) {
+ if(total) {
+ return total;
+ } else {
+ log_warning("safe_read failed errno: %d", errno);
+ return len;
+ }
+ }
+ buf->write_index = i + len;
+ total += len;
+
+ return total;
+}
+