summaryrefslogtreecommitdiffstatshomepage
path: root/src/tools/imgtool/filteoln.cpp
blob: bb589e8fafecce0bab94454c50374a7b466bc844 (plain) (blame)
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
// license:BSD-3-Clause
// copyright-holders:Nathan Woods
/****************************************************************************

    filteoln.c

    Native end-of-line filter

*****************************************************************************/

#include <string.h>

#include "imgtool.h"

#define EOLN (CRLF == 1 ? "\r" : (CRLF == 2 ? "\n" : (CRLF == 3 ? "\r\n" : NULL)))



static imgtoolerr_t convert_stream_eolns(imgtool::stream &source, imgtool::stream &dest, const char *eoln)
{
	size_t len, i, pos;
	char buffer[2000];
	int hit_cr = false;

	while((len = source.read(buffer, sizeof(buffer))) > 0)
	{
		pos = 0;

		for (i = 0; i < len; i++)
		{
			switch(buffer[i])
			{
				case '\r':
				case '\n':
					if (!hit_cr || (buffer[i] != '\n'))
					{
						if (i > pos)
							dest.write(buffer + pos, i - pos);
						dest.write(eoln, strlen(eoln));
					}
					pos = i + 1;
					break;
			}
			hit_cr = (buffer[i] == '\r');
		}

		if (i > pos)
			dest.write(buffer + pos, i - pos);
	}

	return IMGTOOLERR_SUCCESS;
}



static imgtoolerr_t ascii_readfile(imgtool::partition &partition, const char *filename, const char *fork, imgtool::stream &destf)
{
	imgtoolerr_t err;
	imgtool::stream::ptr mem_stream;

	mem_stream = imgtool::stream::open_mem(nullptr, 0);
	if (!mem_stream)
		return IMGTOOLERR_OUTOFMEMORY;

	err = partition.read_file(filename, fork, *mem_stream, nullptr);
	if (err)
		return err;

	mem_stream->seek(SEEK_SET, 0);
	return convert_stream_eolns(*mem_stream, destf, EOLN);
}



static imgtoolerr_t ascii_writefile(imgtool::partition &partition, const char *filename, const char *fork, imgtool::stream &sourcef, util::option_resolution *opts)
{
	imgtoolerr_t err;
	imgtool::stream::ptr mem_stream;
	const char *eoln;

	/* create a stream */
	mem_stream = imgtool::stream::open_mem(nullptr, 0);
	if (!mem_stream)
		return IMGTOOLERR_OUTOFMEMORY;

	eoln = partition.get_info_string(IMGTOOLINFO_STR_EOLN);

	err = convert_stream_eolns(sourcef, *mem_stream, eoln);
	if (err)
		return err;
	mem_stream->seek(SEEK_SET, 0);

	return partition.write_file(filename, fork, *mem_stream, opts, nullptr);
}



void filter_eoln_getinfo(uint32_t state, union filterinfo *info)
{
	switch(state)
	{
		case FILTINFO_STR_NAME:         info->s = "ascii"; break;
		case FILTINFO_STR_HUMANNAME:    info->s = "Ascii"; break;
		case FILTINFO_PTR_READFILE:     info->read_file = ascii_readfile; break;
		case FILTINFO_PTR_WRITEFILE:    info->write_file = ascii_writefile; break;
	}
}