Skip to content

Commit 258ff73

Browse files
authored
encoding.csv: re-encapsulate fields in Writer/Reader (fix #15558) (#15570)
1 parent 797bdd5 commit 258ff73

File tree

3 files changed

+26
-10
lines changed

3 files changed

+26
-10
lines changed

vlib/encoding/csv/reader.v

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,14 +38,14 @@ fn (err InvalidLineEndingError) msg() string {
3838
return 'encoding.csv: could not find any valid line endings'
3939
}
4040

41-
pub struct Reader {
41+
struct Reader {
4242
// not used yet
4343
// has_header bool
4444
// headings []string
45-
data string
46-
pub mut:
47-
delimiter u8
48-
comment u8
45+
data string
46+
delimiter u8
47+
comment u8
48+
mut:
4949
is_mac_pre_osx_le bool
5050
row_pos int
5151
}

vlib/encoding/csv/writer.v

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,24 @@ module csv
66
import strings
77

88
struct Writer {
9-
mut:
10-
sb strings.Builder
11-
pub mut:
129
use_crlf bool
1310
delimiter u8
11+
mut:
12+
sb strings.Builder
13+
}
14+
15+
[params]
16+
pub struct WriterConfig {
17+
use_crlf bool = false
18+
delimiter u8 = `,`
1419
}
1520

1621
// new_writer returns a reference to a Writer
17-
pub fn new_writer() &Writer {
22+
pub fn new_writer(config WriterConfig) &Writer {
1823
return &Writer{
19-
delimiter: `,`
2024
sb: strings.new_builder(200)
25+
use_crlf: config.use_crlf
26+
delimiter: config.delimiter
2127
}
2228
}
2329

vlib/encoding/csv/writer_test.v

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,13 @@ fn test_encoding_csv_writer() {
99

1010
assert csv_writer.str() == 'name,email,phone,other\njoe,joe@blow.com,0400000000,test\nsam,sam@likesham.com,0433000000,"needs, quoting"\n'
1111
}
12+
13+
fn test_encoding_csv_writer_delimiter() {
14+
mut csv_writer := csv.new_writer(delimiter: ` `)
15+
16+
csv_writer.write(['name', 'email', 'phone', 'other']) or {}
17+
csv_writer.write(['joe', 'joe@blow.com', '0400000000', 'test']) or {}
18+
csv_writer.write(['sam', 'sam@likesham.com', '0433000000', 'needs, quoting']) or {}
19+
20+
assert csv_writer.str() == 'name email phone other\njoe joe@blow.com 0400000000 test\nsam sam@likesham.com 0433000000 "needs, quoting"\n'
21+
}

0 commit comments

Comments
 (0)