image icon indicating copy to clipboard operation
image copied to clipboard

Add `GenericImageView::try_view`

Open imlazyeye opened this issue 6 months ago • 2 comments

This adds GenericImageView::try_view as a non-panicking alternative to GenericImageView::view. It additionally updates the documentation of GenericImageView::view to mention its panics.

I am writing a non-panicking binary that captures screenshots of a window. If the user resizes their window unexpectedly, the coordinates/dimensions I pass in to GenericImageView::view may become invalid. I would like to be able to get an Err so I can handle this behavior myself.

I am unsure if the error I utilized here is correct within this context -- please let me know if there is another I should be using/if I should create a new one!

imlazyeye avatar Jun 12 '25 17:06 imlazyeye

I think Option is generally preferable for try_ methods that have only one failure mode.

We should certainly add the "panics" section to the docs on the view method, but I'm not convinced on adding try_view. It feels very specialized and reasonably straightforward to work around in user code.

fintelia avatar Jun 15 '25 22:06 fintelia

The responsibility of the implementation of the check seems to me like it should belong in our code. Similar to the standard library having added checked variants of split even though for a long time it had the argument that its precondition would be simple to check. And mind you, in comparison this precondition is harder to get right due to overflows.

197g avatar Jun 16 '25 09:06 197g

Agreed, I think there's precedent for crates guiding users through what failure states could occur through the return of their types, not just the documentation. It's still the user's responsibility to handle this error case, but I think the crate is responsible for guiding the user through what errors they will potentially run into.

I think Option is generally preferable for try_ methods that have only one failure mode.

Typically I follow the same philosophy, however in cases where your error case is the result of a mistake rather than "there is not something there", Result feels more appropriate. I think there's an argument both ways for where this particular example lies, but personally Result seems most natural.

imlazyeye avatar Jun 20 '25 16:06 imlazyeye

redid above work after rebasing to main's refactor

imlazyeye avatar Jun 20 '25 16:06 imlazyeye