~blainsmith/hare-csv

02c26cda919b6d462abc374bc7f7097c722b961c — Byron Torres 1 year, 1 month ago 4e84682
add delim parameter to newreader, newwriter
3 files changed, 13 insertions(+), 17 deletions(-)

M format/csv/README
M format/csv/reader.ha
M format/csv/writer.ha
M format/csv/README => format/csv/README +3 -5
@@ 1,9 1,7 @@
The format::csv module provides basic reading and writing of comma-separated
text. By default, the comma is used as the default delimiter when creating a
[[reader]] or [[writer]]. You may change this by setting the `delim` field.
The format::csv module handles the reading and writing of comma-separated text,
or newline-delimited records of text with generic field delimiters.

    let w = csv::newwriter(os::stdout);
    w.delim = '|';
    let w = csv::newwriter(os::stdout, '|');

    csv::write(&w, ["field1", "field2", "field3"])!;
    // "field1|field2|field3\n"

M format/csv/reader.ha => format/csv/reader.ha +5 -6
@@ 12,10 12,10 @@ export type reader = struct {
	delim: rune,
};

// Creates a new [[reader]] with a comma (',') as the delimiter.
export fn newreader(in: io::handle) reader = reader {
// Creates a new [[reader]] with a specified delimiter.
export fn newreader(in: io::handle, delim: rune) reader = reader {
	in = in,
	delim = ',',
	delim = delim,
};

// Reads one record (a slice of strings) from a [[reader]].


@@ 83,7 83,7 @@ export fn read(r: *reader) ([]str | io::EOF | encoding::utf8::invalid | io::erro
`);
	let buf = bufio::fixed(csv, io::mode::READ);

	let r = newreader(&buf);
	let r = newreader(&buf, ',');

	let record = read(&r)! as []str;
	assert(record[0] == "col1");


@@ 114,8 114,7 @@ export fn read(r: *reader) ([]str | io::EOF | encoding::utf8::invalid | io::erro
`);
	let buf = bufio::fixed(csv, io::mode::READ);

	let r = newreader(&buf);
	r.delim = '|';
	let r = newreader(&buf, '|');

	let record = read(&r)! as []str;
	assert(record[0] == "col1");

M format/csv/writer.ha => format/csv/writer.ha +5 -6
@@ 12,10 12,10 @@ export type writer = struct {
	delim: rune,
};

// Creates a new [[writer]] with a comma (',') as the delimiter.
export fn newwriter(out: io::handle) writer = writer {
// Creates a new [[writer]] with a specified delimiter.
export fn newwriter(out: io::handle, delim: rune) writer = writer {
	out = out,
	delim = ',',
	delim = delim,
};

// Writes one record (a slice of strings) to a [[writer]], escaping


@@ 52,7 52,7 @@ export fn write(w: *writer, record: []str) (void | io::error) = {
@test fn write() void = {
	let buf = strio::dynamic();

	let w = newwriter(&buf);
	let w = newwriter(&buf, ',');

	write(&w, ["col1", "col2", "col3"])!;
	write(&w, [`1,1`, "12", "13"])!;


@@ 71,8 71,7 @@ export fn write(w: *writer, record: []str) (void | io::error) = {
@test fn write_delim() void = {
	let buf = strio::dynamic();

	let w = newwriter(&buf);
	w.delim = '|';
	let w = newwriter(&buf, '|');

	write(&w, ["col1", "col2", "col3"])!;
	write(&w, [`1,1`, "12", "13"])!;