Skip to content

Commit

Permalink
fix: Do not panic in strptime() if format ends with '%' (#21176)
Browse files Browse the repository at this point in the history
  • Loading branch information
etiennebacher authored Feb 11, 2025
1 parent c1e493a commit 0654544
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 24 deletions.
51 changes: 27 additions & 24 deletions crates/polars-time/src/chunkedarray/string/strptime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,31 +207,34 @@ pub(super) fn fmt_len(fmt: &[u8]) -> Option<u16> {

while let Some(&val) = iter.next() {
match val {
b'%' => match iter.next().expect("invalid pattern") {
b'Y' => cnt += 4,
b'y' => cnt += 2,
b'd' => cnt += 2,
b'm' => cnt += 2,
b'b' => cnt += 3,
b'H' => cnt += 2,
b'M' => cnt += 2,
b'S' => cnt += 2,
b'9' => {
cnt += 9;
debug_assert_eq!(iter.next(), Some(&b'f'));
return Some(cnt);
},
b'6' => {
cnt += 6;
debug_assert_eq!(iter.next(), Some(&b'f'));
return Some(cnt);
},
b'3' => {
cnt += 3;
debug_assert_eq!(iter.next(), Some(&b'f'));
return Some(cnt);
b'%' => match iter.next() {
Some(&next_val) => match next_val {
b'Y' => cnt += 4,
b'y' => cnt += 2,
b'd' => cnt += 2,
b'm' => cnt += 2,
b'b' => cnt += 3,
b'H' => cnt += 2,
b'M' => cnt += 2,
b'S' => cnt += 2,
b'9' => {
cnt += 9;
debug_assert_eq!(iter.next(), Some(&b'f'));
return Some(cnt);
},
b'6' => {
cnt += 6;
debug_assert_eq!(iter.next(), Some(&b'f'));
return Some(cnt);
},
b'3' => {
cnt += 3;
debug_assert_eq!(iter.next(), Some(&b'f'));
return Some(cnt);
},
_ => return None,
},
_ => return None,
None => return None,
},
_ => {
cnt += 1;
Expand Down
5 changes: 5 additions & 0 deletions py-polars/tests/unit/operations/namespaces/test_strptime.py
Original file line number Diff line number Diff line change
Expand Up @@ -755,3 +755,8 @@ def test_out_of_ns_range_no_tu_specified_13592() -> None:
dtype=pl.Datetime("us"),
)
assert_series_equal(result, expected)


def test_wrong_format_percent() -> None:
with pytest.raises(InvalidOperationError):
pl.Series(["2019-01-01"]).str.strptime(pl.Date, format="d%")

0 comments on commit 0654544

Please sign in to comment.