Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Strictness of panicking #32

Open
chrysn opened this issue Mar 21, 2020 · 0 comments
Open

Strictness of panicking #32

chrysn opened this issue Mar 21, 2020 · 0 comments

Comments

@chrysn
Copy link

chrysn commented Mar 21, 2020

The way panics are discouraged ("Crates providing libraries should never use functions or instructions that can fail and cause the code to panic [including] assert, an unchecked access to an array") does not align with what I perceive to be the current best practice of general Rust development.

Oftentimes, panics resulting from array index access, expect calls or assertions are ruled out by the construction of a particular crate, and the invariants it upholds about its data structures. In a sense, for the "unchecked access to an array" item, the access is checked, but not at the very line before the access but somewhere further away (say, in the constructors). The compiler may or may not be able to follow that reasoning (and thus not even generate code for the panics) depending on the complexity of the invariant and the level of optimization. (Some invariants can even be made explicit in the type system, like for dividing by a NonZeroU32; others like "this index is suitable for that slice" can't yet).

The guidance as written brings the danger of functions that are conceptually infallible returning a Result for fear of violating LANG-NOPANIC. This imposes the onus of handling the error properly on the library users, who won't be able to make a good judgement on how to handle it because they know that it can't occur, and let them wind up with untestable code parts.

Suggested phrasing to avoid this:

Crates providing libraries should never use functions or instructions that can fail and cause the code to panic, unless they can ensure by invariants they uphold that the panic does not trigger. These invariants must be documented in the data structures, and referred to at the possibly panicking code.

Quite possibly it would be beneficial to even explicitly recommend against returning Results when an operation is actually infallible (not because it makes the own crate insecure, but makes securely using it harder), but that's another issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant