From 258ff73efd1d4e5fe2264f68d56c4d6602ae31f2 Mon Sep 17 00:00:00 2001 From: ChAoS_UnItY Date: Sun, 28 Aug 2022 16:13:43 +0800 Subject: [PATCH] encoding.csv: re-encapsulate fields in Writer/Reader (fix #15558) (#15570) --- vlib/encoding/csv/reader.v | 10 +++++----- vlib/encoding/csv/writer.v | 16 +++++++++++----- vlib/encoding/csv/writer_test.v | 10 ++++++++++ 3 files changed, 26 insertions(+), 10 deletions(-) diff --git a/vlib/encoding/csv/reader.v b/vlib/encoding/csv/reader.v index 83da7a689..88fe33c90 100644 --- a/vlib/encoding/csv/reader.v +++ b/vlib/encoding/csv/reader.v @@ -38,14 +38,14 @@ fn (err InvalidLineEndingError) msg() string { return 'encoding.csv: could not find any valid line endings' } -pub struct Reader { +struct Reader { // not used yet // has_header bool // headings []string - data string -pub mut: - delimiter u8 - comment u8 + data string + delimiter u8 + comment u8 +mut: is_mac_pre_osx_le bool row_pos int } diff --git a/vlib/encoding/csv/writer.v b/vlib/encoding/csv/writer.v index c2bb0ced2..b9d80e3d8 100644 --- a/vlib/encoding/csv/writer.v +++ b/vlib/encoding/csv/writer.v @@ -6,18 +6,24 @@ module csv import strings struct Writer { -mut: - sb strings.Builder -pub mut: use_crlf bool delimiter u8 +mut: + sb strings.Builder +} + +[params] +pub struct WriterConfig { + use_crlf bool = false + delimiter u8 = `,` } // new_writer returns a reference to a Writer -pub fn new_writer() &Writer { +pub fn new_writer(config WriterConfig) &Writer { return &Writer{ - delimiter: `,` sb: strings.new_builder(200) + use_crlf: config.use_crlf + delimiter: config.delimiter } } diff --git a/vlib/encoding/csv/writer_test.v b/vlib/encoding/csv/writer_test.v index 92882ddc9..ffc362653 100644 --- a/vlib/encoding/csv/writer_test.v +++ b/vlib/encoding/csv/writer_test.v @@ -9,3 +9,13 @@ fn test_encoding_csv_writer() { assert csv_writer.str() == 'name,email,phone,other\njoe,joe@blow.com,0400000000,test\nsam,sam@likesham.com,0433000000,"needs, quoting"\n' } + +fn test_encoding_csv_writer_delimiter() { + mut csv_writer := csv.new_writer(delimiter: ` `) + + csv_writer.write(['name', 'email', 'phone', 'other']) or {} + csv_writer.write(['joe', 'joe@blow.com', '0400000000', 'test']) or {} + csv_writer.write(['sam', 'sam@likesham.com', '0433000000', 'needs, quoting']) or {} + + assert csv_writer.str() == 'name email phone other\njoe joe@blow.com 0400000000 test\nsam sam@likesham.com 0433000000 "needs, quoting"\n' +} -- 2.30.2