summaryrefslogtreecommitdiff
path: root/src/cbuffer.c
blob: b0b8237bf8cd7b892d28c602f4adafab1315061e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*
 * 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 %m");
			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 %m");
			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 %m");
			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 %m");
			return len;
		}
	}
	buf->write_index = i + len;
	total += len;

	return total;
}