aboutsummaryrefslogtreecommitdiff
path: root/lib/io/test/istream_read.c
blob: 7029c38ec61c91f94324ac1ee74facdf527e83a5 (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
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
 * istream_read.c
 *
 * Copyright (C) 2023 David Oberhollenzer <goliath@infraroot.at>
 */
#include "config.h"

#include "io/istream.h"
#include "util/test.h"
#include "io/mem.h"

static const sqfs_u64 end0 = 449;	/* region 1: filled with 'A' */
static const sqfs_u64 end1 = 521;	/* region 2: filled with 'B' */
static const sqfs_u64 end2 = 941;	/* region 3: filled with 'C' */

static sqfs_u8 rd_buffer[941];

static sqfs_u8 byte_at_offset(sqfs_u64 off)
{
	if (off < end0)
		return 'A';
	if (off < end1)
		return 'B';
	return 'C';
}

static void init_rd_buffer(void)
{
	for (size_t i = 0; i < end2; ++i)
		rd_buffer[i] = byte_at_offset(i);
}

int main(int argc, char **argv)
{
	sqfs_u8 read_buffer[61];
	sqfs_u64 read_off = 0;
	istream_t *dummy;
	(void)argc; (void)argv;

	init_rd_buffer();
	dummy = istream_memory_create("dummy file", 103,
				      rd_buffer, sizeof(rd_buffer));
	TEST_NOT_NULL(dummy);

	/* region 1 */
	while (read_off < end0) {
		size_t read_diff = end0 - read_off;

		if (read_diff > sizeof(read_buffer))
			read_diff = sizeof(read_buffer);

		int ret = istream_read(dummy, read_buffer, read_diff);
		TEST_ASSERT(ret > 0);
		TEST_ASSERT((size_t)ret <= read_diff);

		for (int i = 0; i < ret; ++i) {
			TEST_EQUAL_UI(read_buffer[i], 'A');
		}

		read_off += ret;
	}

	/* region 2 */
	while (read_off < end1) {
		size_t read_diff = end1 - read_off;

		if (read_diff > sizeof(read_buffer))
			read_diff = sizeof(read_buffer);

		int ret = istream_read(dummy, read_buffer, read_diff);
		TEST_ASSERT(ret > 0);
		TEST_ASSERT((size_t)ret <= read_diff);

		for (int i = 0; i < ret; ++i) {
			TEST_EQUAL_UI(read_buffer[i], 'B');
		}

		read_off += ret;
	}

	/* region 3 */
	for (;;) {
		size_t read_diff = sizeof(read_buffer);

		int ret = istream_read(dummy, read_buffer, read_diff);
		TEST_ASSERT(ret >= 0);
		TEST_ASSERT((size_t)ret <= read_diff);

		if (ret == 0) {
			TEST_EQUAL_UI(read_off, end2);
			break;
		}

		for (int i = 0; i < ret; ++i) {
			TEST_EQUAL_UI(read_buffer[i], 'C');
		}

		read_off += ret;
		TEST_ASSERT(read_off <= end2);
	}

	TEST_ASSERT(dummy->eof);
	TEST_ASSERT(dummy->buffer_used == 0);
	sqfs_drop(dummy);
	return EXIT_SUCCESS;
}