chronotope / chrono

Date and time library for Rust
Other
3.28k stars 516 forks source link

Why do some functions panic instead of returning a Result<T, E>? #556

Closed BlueSialia closed 7 months ago

BlueSialia commented 3 years ago

Right now I'm parsing some information I receive in UDP messages. Some of that information is timestamped but if something goes wrong on the sender I can receive random bytes so if I try to parse those bytes as dates I get a panic with 'No such local time'.

And I wonder. If the function Local.ymd(y, month, d).and_hms(h, min, s) can fail why not return a Result instead?

dzfranklin commented 3 years ago

I think those functions are intended for building timestamps from known good values. You might be looking for DateTime::parse_from_str which lets you specify the format you're trying to parse in the standard unix-y way and returns a result. Don't take me too seriously, I'm a random person who saw this while filing their own question.

BlueSialia commented 3 years ago

I see where you are coming from. But I do not have a String, though. I could create it to then parse it, but that feels like an ugly hack.

Regardless, I was under the assumption that Rust code practices were about working with Result and Option whenever some function could fail. That Rust is reliable because runtime errors should only happen if the programmer uses unwrap() (an similar functions) or unsafe code.

deviant commented 3 years ago

The time crate (which this depends on) placed panicking functions behind a feature gate and switched to providing try_ functions instead. This should too.

c-git commented 1 year ago

Is there something I can do to move this forward? I prefer not need to check each function to see if it might panic. Maybe offer parallel functions that do not panic so it's not a breaking change?

djc commented 1 year ago

Feel free to submit PRs to create non-panicking alternative APIs en add deprecations for the panicking calls.

c-git commented 1 year ago

Ok thank you, I will try to do it. Just to get a feel for naming preference, should I just add try_ to the front of the functions I change?

djc commented 1 year ago

That seems like a reasonable first approximation. Our constructors mostly have _opt() suffixes at this point, let's see what works in context.

c-git commented 1 year ago

Got it, will try to see if I can find a pattern. The name can always be refactored, I don't get attached to them

c-git commented 1 year ago

Haven't forgotten about this but my schedule has been kind of full so if someone else gets to it first that's fine otherwise I will give it a go once I can put some time aside.

pitdicker commented 7 months ago

Closing in favor of https://github.com/chronotope/chrono/issues/1049. We have non-panicking alternatives to almost all methods now, and making them default for 0.5 is definitely on the roadmap.