aboutsummaryrefslogtreecommitdiff
path: root/csv/csv.ha
blob: 40e1e3b26b3e23d85555b6b313fad7be17aeba85 (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
use io;
use strings;
use fmt;

export type error = !(str | io::error);

export fn writerecord(w: io::handle, record: []str, separator: const str = ",", quote: const rune =
	'"') (void | error) = {
	let sep = "";
	for (const field .. record) {
		if (strings::contains(field, separator)) {
			if (strings::contains(field, quote)) {
				return "ERROR: Field contains quote character
					(not supported)";
			};
			fmt::fprintf(w, "{}{}{}{}", sep, quote, field, quote)!;
		} else {
			fmt::fprintf(w, "{}{}", sep, field)!;
		};
		sep = separator;
	};
	fmt::fprintln(w)!;
};

export fn writerecords(w: io::handle, records: [][]str, separator: const str = ",", quote: const
		rune = '"') (void | error) = {
	for (const record .. records) {
		writerecord(w, record, separator, quote)?;
	};
};