aboutsummaryrefslogtreecommitdiff
path: root/lib/fstream/istream.c
blob: 6318a23dfaa89a35325ad928e24e8cef53252107 (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
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
 * istream.c
 *
 * Copyright (C) 2019 David Oberhollenzer <goliath@infraroot.at>
 */
#include "internal.h"


sqfs_s32 istream_read(istream_t *strm, void *data, size_t size)
{
	sqfs_s32 total = 0;
	size_t diff;

	if (size > 0x7FFFFFFF)
		size = 0x7FFFFFFF;

	while (size > 0) {
		if (strm->buffer_offset >= strm->buffer_used) {
			if (istream_precache(strm))
				return -1;

			if (strm->buffer_used == 0)
				break;
		}

		diff = strm->buffer_used - strm->buffer_offset;
		if (diff > size)
			diff = size;

		memcpy(data, strm->buffer + strm->buffer_offset, diff);
		data = (char *)data + diff;
		strm->buffer_offset += diff;
		size -= diff;
		total += diff;
	}

	return total;
}

int istream_precache(istream_t *strm)
{
	if (strm->buffer_offset >= strm->buffer_used) {
		strm->buffer_offset = 0;
		strm->buffer_used = 0;
	} else if (strm->buffer_offset > 0) {
		memmove(strm->buffer,
			strm->buffer + strm->buffer_offset,
			strm->buffer_used - strm->buffer_offset);

		strm->buffer_used -= strm->buffer_offset;
		strm->buffer_offset = 0;
	}

	if (strm->eof)
		return 0;

	return strm->precache(strm);
}

const char *istream_get_filename(istream_t *strm)
{
	return strm->get_filename(strm);
}

int istream_skip(istream_t *strm, sqfs_u64 size)
{
	size_t diff;

	while (size > 0) {
		if (strm->buffer_offset >= strm->buffer_used) {
			if (istream_precache(strm))
				return -1;

			if (strm->buffer_used == 0) {
				fprintf(stderr, "%s: unexpected end-of-file\n",
					strm->get_filename(strm));
				return -1;
			}
		}

		diff = strm->buffer_used - strm->buffer_offset;
		if ((sqfs_u64)diff > size)
			diff = size;

		strm->buffer_offset += diff;
		size -= diff;
	}

	return 0;
}