aboutsummaryrefslogtreecommitdiff
path: root/format/tsv/writer.ha
blob: f1f045b7cc4919041d165b239cdc2ba54d19ea64 (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
use io;
use strings;
use fmt;
use memio;

// Writes a slice strings to a handle in TSV format. Existing tabs in the record
// are removed.
export fn writerecord(w: io::handle, record: []str) (void | io::error) = {
	let sep = "";
	for (const field .. record) {
		const pfield = strings::replace(field, "\t", "");
		defer free(pfield);
		fmt::fprintf(w, "{}{}", sep, pfield)!;
		sep = "\t";
	};
	fmt::fprintln(w)!;
};

// Writes a slice of string slices to a handle in TSV format. Existing tabs in
// the records are removed.
export fn writerecords(w: io::handle, records: [][]str) (void | io::error) = {
	for (const record .. records) {
		writerecord(w, record)?;
	};
};

@test fn writenormal() void = {
	const expected = "col1\tcol2\tcol3
1\t2\t3
4\t5\t6\n";
	const input: [][]str = [
		["col1", "col2", "col3"],
		["1", "2", "3"],
		["4", "5", "6"],
	];
	const st = memio::dynamic();
	defer io::close(&st)!;
	writerecords(&st, input)!;
	const actual = memio::string(&st)!;
	fmt::errorfln("expected: {}EOF", expected)!;
	fmt::errorln()!;
	fmt::errorfln("actual: {}EOF", actual)!;
	assert(actual == expected);
};

@test fn writetabs() void = {
	const expected = "col1\tcol2\tcol3
1\t2\t3
4\t5\t6\n";
	const input: [][]str = [
		["col1\t", "co\tl2", "col3"],
		["1", "2", "\t3"],
		["4\t", "\t\t5\t", "6"],
	];
	const st = memio::dynamic();
	defer io::close(&st)!;
	writerecords(&st, input)!;
	const actual = memio::string(&st)!;
	fmt::errorfln("expected: {}EOF", expected)!;
	fmt::errorln()!;
	fmt::errorfln("actual: {}EOF", actual)!;
	assert(actual == expected);
};