Skip to content

Commit 70ebe18

Browse files
committed
Validate csv dialect conflicts with line terminators
- Reject dialect characters that overlap any lineterminator character - Validate Dialect construction consistently and allow non-ASCII terminators - Unskip csv invalid character coverage now that validation matches behavior
1 parent 5e2da0c commit 70ebe18

2 files changed

Lines changed: 60 additions & 120 deletions

File tree

‎Lib/test/test_csv.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1286,7 +1286,6 @@ class mydialect(csv.Dialect):
12861286
self.assertEqual(str(cm.exception),
12871287
'"lineterminator" must be a string, not NoneType')
12881288

1289-
@unittest.expectedFailure # TODO: RUSTPYTHON
12901289
def test_invalid_chars(self):
12911290
def create_invalid(field_name, value, **kwargs):
12921291
class mydialect(csv.Dialect):

‎crates/stdlib/src/csv.rs‎

Lines changed: 60 additions & 119 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,10 @@ mod _csv {
100100
impl Constructor for PyDialect {
101101
type Args = PyObjectRef;
102102

103-
fn py_new(_cls: &Py<PyType>, ctx: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
104-
Self::try_from_object(vm, ctx)
103+
fn py_new(_cls: &Py<PyType>, obj: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
104+
let dialect = Self::try_from_object(vm, obj)?;
105+
validate_dialect(vm, &dialect)?;
106+
Ok(dialect)
105107
}
106108
}
107109

@@ -240,26 +242,7 @@ mod _csv {
240242
})
241243
}
242244

243-
/// Validate that a line terminator is ASCII and return it as a `str`.
244-
///
245-
/// The writer's quoting and escaping predicates compare raw bytes, so a
246-
/// non-ASCII terminator would either quote a field that merely shares a
247-
/// UTF-8 lead byte or splice an escape character into the middle of a
248-
/// multi-byte sequence. Reject those here.
249-
///
250-
/// The ASCII check must come before any UTF-8 conversion so that lone
251-
/// surrogates are reported as this `csv.Error` too.
252-
///
253-
/// TODO: RUSTPYTHON; handle non-ASCII terminators code-point-wise as part
254-
/// of full Unicode dialect support.
255-
fn ascii_lineterminator<'a>(vm: &VirtualMachine, s: &'a PyStr) -> PyResult<&'a str> {
256-
if !s.as_wtf8().is_ascii() {
257-
return Err(new_csv_error(
258-
vm,
259-
r#""lineterminator" must be an ASCII string"#,
260-
));
261-
}
262-
// An ASCII string is always valid UTF-8.
245+
fn parse_lineterminator<'a>(vm: &VirtualMachine, s: &'a PyStr) -> PyResult<&'a str> {
263246
s.to_str()
264247
.ok_or_else(|| new_csv_error(vm, r#""lineterminator" must be a string"#))
265248
}
@@ -271,7 +254,7 @@ mod _csv {
271254
// arbitrary-length terminator; the manual writer paths emit it
272255
// verbatim and the csv-core writer path appends it after a
273256
// sentinel terminator (see `writerow`).
274-
let value = ascii_lineterminator(vm, &s)?;
257+
let value = parse_lineterminator(vm, &s)?;
275258
Ok(value.to_owned())
276259
}
277260
attr => {
@@ -492,7 +475,7 @@ mod _csv {
492475
write,
493476
state: PyMutex::new(WriteState {
494477
buffer: vec![0; 1024],
495-
writer: options.to_writer(),
478+
writer: FormatOptions::to_writer(&dialect),
496479
}),
497480
dialect,
498481
})
@@ -578,7 +561,7 @@ mod _csv {
578561
dialect: DialectItem,
579562
delimiter: Option<u8>,
580563
quotechar: Option<Option<u8>>,
581-
escapechar: Option<u8>,
564+
escapechar: Option<Option<u8>>,
582565
doublequote: Option<bool>,
583566
skipinitialspace: Option<bool>,
584567
lineterminator: Option<String>,
@@ -661,9 +644,10 @@ mod _csv {
661644

662645
if let Some(escapechar) = args.kwargs.swap_remove("escapechar") {
663646
res.escapechar = match_class!(match escapechar {
664-
s @ PyStr => Some(parse_single_char(&s, |_| {
647+
s @ PyStr => Some(Some(parse_single_char(&s, |_| {
665648
vm.new_type_error(r#""escapechar" must be a 1-character string"#)
666-
})?),
649+
})?)),
650+
PyNone => Some(None),
667651
_ => {
668652
return Err(ArgumentError::Exception(
669653
vm.new_type_error(r#""escapechar" must be a 1-character string"#),
@@ -679,7 +663,7 @@ mod _csv {
679663
lineterminator.class().name()
680664
))
681665
})?;
682-
let value = ascii_lineterminator(vm, s)?;
666+
let value = parse_lineterminator(vm, s)?;
683667
res.lineterminator = Some(value.to_owned());
684668
};
685669

@@ -786,27 +770,29 @@ mod _csv {
786770
));
787771
}
788772

789-
let values = [
790-
("delimiter", Some(core::slice::from_ref(&dialect.delimiter))),
791-
(
792-
"quotechar",
793-
dialect.quotechar.as_ref().map(core::slice::from_ref),
794-
),
795-
(
796-
"escapechar",
797-
dialect.escapechar.as_ref().map(core::slice::from_ref),
798-
),
799-
("lineterminator", Some(dialect.lineterminator.as_bytes())),
773+
let values: [(&str, Option<u8>); 3] = [
774+
("delimiter", Some(dialect.delimiter)),
775+
("quotechar", dialect.quotechar),
776+
("escapechar", dialect.escapechar),
800777
];
801778
for (index, (left_name, left)) in values.iter().enumerate() {
802-
let Some(left) = left else { continue };
803779
for (right_name, right) in values.iter().skip(index + 1) {
804-
if right.as_ref() == Some(left) {
780+
if left.is_some() && left == right {
805781
return Err(vm.new_value_error(format!(
806782
"{left_name} and {right_name} cannot be the same"
807783
)));
808784
}
809785
}
786+
if left.is_some_and(|value| {
787+
dialect
788+
.lineterminator
789+
.chars()
790+
.any(|character| character == value as char)
791+
}) {
792+
return Err(vm.new_value_error(format!(
793+
"{left_name} and lineterminator cannot be the same"
794+
)));
795+
}
810796
}
811797
Ok(())
812798
}
@@ -828,7 +814,7 @@ mod _csv {
828814
check_and_fill!(res, skipinitialspace);
829815

830816
if let Some(t) = self.escapechar {
831-
res.escapechar = Some(t);
817+
res.escapechar = t;
832818
};
833819

834820
if let Some(t) = self.quotechar {
@@ -865,81 +851,23 @@ mod _csv {
865851
Ok(dialect)
866852
}
867853

868-
fn get_quoting(&self) -> QuoteStyle {
869-
let mut quoting = match &self.dialect {
870-
DialectItem::Str(name) => {
871-
let g = GLOBAL_HASHMAP.lock();
872-
if let Some(dialect) = g.get(name) {
873-
dialect.quoting
874-
} else {
875-
QuoteStyle::Minimal
876-
}
877-
}
878-
DialectItem::Obj(obj) => obj.quoting,
879-
_ => QuoteStyle::Minimal,
880-
};
881-
882-
if let Some(attr) = self.quoting {
883-
quoting = attr
884-
}
885-
886-
quoting
887-
}
888-
889-
fn to_writer(&self) -> csv_core::Writer {
854+
fn to_writer(dialect: &PyDialect) -> csv_core::Writer {
890855
let mut builder = csv_core::WriterBuilder::new();
891-
let mut writer = match &self.dialect {
892-
DialectItem::Str(name) => {
893-
let g = GLOBAL_HASHMAP.lock();
894-
if let Some(dialect) = g.get(name) {
895-
let mut builder = builder
896-
.delimiter(dialect.delimiter)
897-
.double_quote(dialect.doublequote);
898-
899-
if let Some(t) = dialect.quotechar {
900-
builder = builder.quote(t);
901-
}
902-
903-
builder
904-
905-
// TODO: RUSTPYTHON; Perfecting the remaining attributes.
906-
} else {
907-
&mut builder
908-
}
909-
}
910-
DialectItem::Obj(obj) => {
911-
let mut builder = builder
912-
.delimiter(obj.delimiter)
913-
.double_quote(obj.doublequote);
914-
915-
if let Some(t) = obj.quotechar {
916-
builder = builder.quote(t);
917-
}
918-
919-
builder
920-
}
921-
_ => &mut builder,
922-
};
923-
924-
if let Some(t) = self.delimiter {
925-
writer = writer.delimiter(t);
926-
}
856+
let mut writer = builder
857+
.delimiter(dialect.delimiter)
858+
.double_quote(dialect.doublequote);
927859

928-
if let Some(Some(t)) = self.quotechar {
860+
if let Some(t) = dialect.quotechar {
929861
writer = writer.quote(t);
930862
}
931863

932-
if let Some(t) = self.doublequote {
933-
writer = writer.double_quote(t);
934-
}
935-
936864
writer = writer.terminator(Terminator::Any(CSV_CORE_TERMINATOR_SENTINEL));
937865

938-
if let Some(e) = self.escapechar {
866+
if let Some(e) = dialect.escapechar {
939867
writer = writer.escape(e);
940868
}
941869

942-
writer = writer.quote_style(self.get_quoting().into());
870+
writer = writer.quote_style(dialect.quoting.into());
943871

944872
writer.build()
945873
}
@@ -1355,39 +1283,52 @@ mod _csv {
13551283
dialect: &PyDialect,
13561284
vm: &VirtualMachine,
13571285
) -> PyResult<()> {
1358-
for &byte in data {
1359-
if field_needs_escape(byte, dialect) {
1286+
let mut data = data;
1287+
while let Some((&byte, rest)) = data.split_first() {
1288+
if field_needs_escape(data, dialect) {
13601289
let escapechar = dialect
13611290
.escapechar
13621291
.ok_or_else(|| new_csv_error(vm, "need to escape, but no escapechar set"))?;
13631292
output.push(escapechar);
13641293
}
13651294
output.push(byte);
1295+
data = rest;
13661296
}
13671297
Ok(())
13681298
}
13691299

1300+
fn data_contains_lineterminator_char(data: &[u8], dialect: &PyDialect) -> bool {
1301+
dialect.lineterminator.chars().any(|character| {
1302+
let mut encoded = [0; 4];
1303+
let character = character.encode_utf8(&mut encoded).as_bytes();
1304+
data.windows(character.len())
1305+
.any(|window| window == character)
1306+
})
1307+
}
1308+
1309+
fn data_starts_with_lineterminator_char(data: &[u8], dialect: &PyDialect) -> bool {
1310+
dialect.lineterminator.chars().any(|character| {
1311+
let mut encoded = [0; 4];
1312+
let character = character.encode_utf8(&mut encoded).as_bytes();
1313+
data.starts_with(character)
1314+
})
1315+
}
1316+
13701317
fn field_needs_quotes(data: &[u8], dialect: &PyDialect) -> bool {
13711318
data.iter().any(|&byte| {
13721319
byte == dialect.delimiter
13731320
|| dialect.quotechar == Some(byte)
13741321
|| matches!(byte, b'\r' | b'\n')
1375-
// CPython quotes a field containing any character of the line
1376-
// terminator. The terminator is ASCII-validated at parse time, so
1377-
// comparing raw bytes cannot match part of a multi-byte character.
1378-
// TODO: RUSTPYTHON; supporting non-ASCII terminators needs
1379-
// code-point-wise quoting and escaping as part of full
1380-
// Unicode dialect support.
1381-
|| dialect.lineterminator.as_bytes().contains(&byte)
1382-
})
1322+
}) || data_contains_lineterminator_char(data, dialect)
13831323
}
13841324

1385-
fn field_needs_escape(byte: u8, dialect: &PyDialect) -> bool {
1325+
fn field_needs_escape(data: &[u8], dialect: &PyDialect) -> bool {
1326+
let byte = data[0];
13861327
byte == dialect.delimiter
13871328
|| dialect.quotechar == Some(byte)
13881329
|| dialect.escapechar == Some(byte)
13891330
|| matches!(byte, b'\r' | b'\n')
1390-
|| dialect.lineterminator.as_bytes().contains(&byte)
1331+
|| data_starts_with_lineterminator_char(data, dialect)
13911332
}
13921333

13931334
fn write_lineterminator(output: &mut Vec<u8>, terminator: &str) {

0 commit comments

Comments
 (0)