aboutsummaryrefslogtreecommitdiff
path: root/lib/io/src/get_line.c
blob: 317859270a887cc989f8e1117a9fc3f72d9fc846 (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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
 * get_line.c
 *
 * Copyright (C) 2019 David Oberhollenzer <goliath@infraroot.at>
 */
#include "internal.h"
#include "sqfs/io.h"
#include "sqfs/error.h"

static void ltrim(char *buffer)
{
	size_t i = 0;

	while (isspace(buffer[i]))
		++i;

	if (i > 0)
		memmove(buffer, buffer + i, strlen(buffer + i) + 1);
}

static void rtrim(char *buffer)
{
	size_t i = strlen(buffer);

	while (i > 0 && isspace(buffer[i - 1]))
		--i;

	buffer[i] = '\0';
}

static size_t trim(char *buffer, int flags)
{
	if (flags & ISTREAM_LINE_LTRIM)
		ltrim(buffer);

	if (flags & ISTREAM_LINE_RTRIM)
		rtrim(buffer);

	return strlen(buffer);
}

int istream_get_line(sqfs_istream_t *strm, char **out,
		     size_t *line_num, int flags)
{
	char *line = NULL, *new;
	size_t line_len = 0;
	int err;

	for (;;) {
		bool have_line = false;
		size_t i, count, avail;
		const sqfs_u8 *ptr;

		err = strm->get_buffered_data(strm, &ptr, &avail, 0);
		if (err < 0)
			goto fail;
		if (err > 0) {
			if (line_len == 0)
				goto out_eof;

			line_len = trim(line, flags);
			if (line_len > 0 ||!(flags & ISTREAM_LINE_SKIP_EMPTY))
				break;

			goto out_eof;
		}

		for (i = 0; i < avail; ++i) {
			if (ptr[i] == '\n')
				break;
		}

		if (i < avail) {
			count = i++;
			have_line = true;
		} else {
			count = i;
		}

		new = realloc(line, line_len + count + 1);
		if (new == NULL) {
			err = SQFS_ERROR_ALLOC;
			goto fail;
		}

		line = new;
		memcpy(line + line_len, ptr, count);
		line_len += count;
		line[line_len] = '\0';

		strm->advance_buffer(strm, i);

		if (have_line) {
			if (line_len > 0 && line[line_len - 1] == '\r')
				line[--line_len] = '\0';

			line_len = trim(line, flags);
			if (line_len > 0 || !(flags & ISTREAM_LINE_SKIP_EMPTY))
				break;

			free(line);
			line = NULL;
			*line_num += 1;
		}
	}

	new = realloc(line, line_len + 1);
	if (new != NULL)
		line = new;

	*out = line;
	return 0;
fail: {
	int temp = errno;
	free(line);
	*out = NULL;
	errno = temp;
	return err;
}
out_eof:
	free(line);
	*out = NULL;
	return 1;
}