Skip to content

Commit ec771cc

Browse files
svranesevicalamb
andauthored
Expose option to set line terminator for CSV writer (#9617)
# Which issue does this PR close? <!-- We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. --> - Closes #9571. # Rationale for this change <!-- Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed. Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes. --> Enable configuring line terminator for CSV writer. # What changes are included in this PR? <!-- There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR. --> See above. # Are these changes tested? <!-- We typically require tests for all PRs in order to: 1. Prevent the code from being accidentally broken by subsequent changes 2. Serve as another way to document the expected behavior of the code If tests are not included in your PR, please explain why (for example, are they covered by existing tests)? --> Yes, added tests. # Are there any user-facing changes? <!-- If there are user-facing changes then we may require documentation to be updated before approving the PR. If there are any breaking changes to public APIs, please call them out. --> Yes, expose option to set line terminator for CSV writer. --------- Co-authored-by: svranesevic <svranesevic@users.noreply.github.com> Co-authored-by: Andrew Lamb <andrew@nerdnetworks.org>
1 parent ec32ac3 commit ec771cc

File tree

1 file changed

+72
-4
lines changed

1 file changed

+72
-4
lines changed

arrow-csv/src/writer.rs

Lines changed: 72 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,8 @@ pub struct WriterBuilder {
358358
quote: u8,
359359
/// Optional escape character. Defaults to `b'\\'`
360360
escape: u8,
361+
/// Optional line terminator. Defaults to `LF` (`\n`)
362+
terminator: Terminator,
361363
/// Enable double quote escapes. Defaults to `true`
362364
double_quote: bool,
363365
/// Optional date format for date arrays
@@ -380,13 +382,23 @@ pub struct WriterBuilder {
380382
quote_style: QuoteStyle,
381383
}
382384

385+
/// The line terminator to use when writing CSV files.
386+
#[derive(Clone, Debug)]
387+
pub enum Terminator {
388+
/// Use CRLF (`\r\n`) as the line terminator
389+
CRLF,
390+
/// Use the specified byte character as the line terminator
391+
Any(u8),
392+
}
393+
383394
impl Default for WriterBuilder {
384395
fn default() -> Self {
385396
WriterBuilder {
386397
delimiter: b',',
387398
has_header: true,
388399
quote: b'"',
389400
escape: b'\\',
401+
terminator: Terminator::Any(b'\n'),
390402
double_quote: true,
391403
date_format: None,
392404
datetime_format: None,
@@ -609,15 +621,33 @@ impl WriterBuilder {
609621
self.quote_style
610622
}
611623

624+
/// Set the CSV file's line terminator
625+
pub fn with_line_terminator(mut self, terminator: Terminator) -> Self {
626+
self.terminator = terminator;
627+
self
628+
}
629+
630+
/// Get the CSV file's line terminator, defaults to `LF` (`\n`)
631+
pub fn line_terminator(&self) -> &Terminator {
632+
&self.terminator
633+
}
634+
612635
/// Create a new `Writer`
613636
pub fn build<W: Write>(self, writer: W) -> Writer<W> {
614637
let mut builder = csv::WriterBuilder::new();
638+
639+
let terminator = match self.terminator {
640+
Terminator::CRLF => csv::Terminator::CRLF,
641+
Terminator::Any(byte) => csv::Terminator::Any(byte),
642+
};
643+
615644
let writer = builder
616645
.delimiter(self.delimiter)
617646
.quote(self.quote)
618647
.quote_style(self.quote_style)
619648
.double_quote(self.double_quote)
620649
.escape(self.escape)
650+
.terminator(terminator)
621651
.from_writer(writer);
622652
Writer {
623653
writer,
@@ -1027,10 +1057,48 @@ sed do eiusmod tempor,-556132.25,1,,2019-04-18T02:45:55.555,23:46:03,foo
10271057
let mut buffer: Vec<u8> = vec![];
10281058
file.read_to_end(&mut buffer).unwrap();
10291059

1030-
assert_eq!(
1031-
"c1,c2\n00:02,46:17\n00:02,\n",
1032-
String::from_utf8(buffer).unwrap()
1033-
);
1060+
let output = String::from_utf8(buffer).unwrap();
1061+
assert_eq!(output, "c1,c2\n00:02,46:17\n00:02,\n");
1062+
}
1063+
1064+
#[test]
1065+
fn test_write_csv_with_lf_terminator() {
1066+
let output = write_batch_with_terminator(Terminator::Any(b'\n'));
1067+
assert_eq!(output, "c1,c2\nhello,1\nworld,2\n");
1068+
}
1069+
1070+
#[test]
1071+
fn test_write_csv_with_crlf_terminator() {
1072+
let output = write_batch_with_terminator(Terminator::CRLF);
1073+
assert_eq!(output, "c1,c2\r\nhello,1\r\nworld,2\r\n");
1074+
}
1075+
1076+
#[test]
1077+
fn test_write_csv_with_any_terminator() {
1078+
let output = write_batch_with_terminator(Terminator::Any(b'|'));
1079+
assert_eq!(output, "c1,c2|hello,1|world,2|");
1080+
}
1081+
1082+
fn write_batch_with_terminator(terminator: Terminator) -> String {
1083+
let schema = Schema::new(vec![
1084+
Field::new("c1", DataType::Utf8, false),
1085+
Field::new("c2", DataType::UInt32, false),
1086+
]);
1087+
1088+
let c1 = StringArray::from(vec!["hello", "world"]);
1089+
let c2 = PrimitiveArray::<UInt32Type>::from(vec![1, 2]);
1090+
1091+
let batch =
1092+
RecordBatch::try_new(Arc::new(schema), vec![Arc::new(c1), Arc::new(c2)]).unwrap();
1093+
1094+
let mut buf = Vec::new();
1095+
let mut writer = WriterBuilder::new()
1096+
.with_line_terminator(terminator)
1097+
.build(&mut buf);
1098+
writer.write(&batch).unwrap();
1099+
drop(writer);
1100+
1101+
String::from_utf8(buf).unwrap()
10341102
}
10351103

10361104
#[test]

0 commit comments

Comments
 (0)