diff options
author | Indrajith K L | 2022-12-03 17:00:20 +0530 |
---|---|---|
committer | Indrajith K L | 2022-12-03 17:00:20 +0530 |
commit | f5c4671bfbad96bf346bd7e9a21fc4317b4959df (patch) | |
tree | 2764fc62da58f2ba8da7ed341643fc359873142f /v_windows/v/old/vlib/encoding/csv/writer.v | |
download | cli-tools-windows-master.tar.gz cli-tools-windows-master.tar.bz2 cli-tools-windows-master.zip |
Diffstat (limited to 'v_windows/v/old/vlib/encoding/csv/writer.v')
-rw-r--r-- | v_windows/v/old/vlib/encoding/csv/writer.v | 80 |
1 files changed, 80 insertions, 0 deletions
diff --git a/v_windows/v/old/vlib/encoding/csv/writer.v b/v_windows/v/old/vlib/encoding/csv/writer.v new file mode 100644 index 0000000..735ca20 --- /dev/null +++ b/v_windows/v/old/vlib/encoding/csv/writer.v @@ -0,0 +1,80 @@ +// Copyright (c) 2019-2021 Alexander Medvednikov. All rights reserved. +// Use of this source code is governed by an MIT license +// that can be found in the LICENSE file. +module csv + +import strings + +struct Writer { +mut: + sb strings.Builder +pub mut: + use_crlf bool + delimiter byte +} + +pub fn new_writer() &Writer { + return &Writer{ + delimiter: `,` + sb: strings.new_builder(200) + } +} + +// write writes a single record +pub fn (mut w Writer) write(record []string) ?bool { + if !valid_delim(w.delimiter) { + return IError(&ErrInvalidDelimiter{}) + } + le := if w.use_crlf { '\r\n' } else { '\n' } + for n, field_ in record { + mut field := field_ + if n > 0 { + w.sb.write_string(w.delimiter.ascii_str()) + } + if !w.field_needs_quotes(field) { + w.sb.write_string(field) + continue + } + w.sb.write_string('"') + for field.len > 0 { + mut i := field.index_any('"\r\n') + if i < 0 { + i = field.len + } + w.sb.write_string(field[..i]) + field = field[i..] + if field.len > 0 { + z := field[0] + match z { + `"` { w.sb.write_string('""') } + `\r`, `\n` { w.sb.write_string(le) } + else {} + } + field = field[1..] + } + } + w.sb.write_string('"') + } + w.sb.write_string(le) + return true +} + +// Once we have multi dimensional array +// pub fn (w &Writer) write_all(records [][]string) { +// for _, record in records { +// w.write(record) +// } +// } +fn (w &Writer) field_needs_quotes(field string) bool { + if field == '' { + return false + } + if field.contains(w.delimiter.ascii_str()) || (field.index_any('"\r\n') != -1) { + return true + } + return false +} + +pub fn (mut w Writer) str() string { + return w.sb.str() +} |