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

Fix lossly cast in value_to_usize #82

Closed
wants to merge 1 commit into from
Closed

Conversation

davidpdrsn
Copy link
Member

Checklist

  • I have read the Contributor Guide
  • I have read and agree to the Code of Conduct
  • I have added a description of my changes and why I'd like them included in the section below

Description of Changes

Turns out going key_path::get(1) infers 1 to be an i32, since get takes an impl Into<Value>. So we somehow need to cast from at least i32 to usize for accessing lists and arrays with key paths.

To remove the lossly conversion I can think of two options:

  1. Use TryFrom and panic if the conversion fails. This would only happen when accessing a very large list.
  2. key_path::get is also used for accessing maps (hence why it takes impl Into<Value>) but we could make separate functions for list/array and map access. Perhaps get_seq(usize) and get_map(impl Into<Value>).

I personally prefer option one because I like how list/array and map access is the same, but it is perhaps a bit disingenuous. I like how it matches rusts' Index trait though. What do you think @bnjbvr?

Related Issues

Fixes #76

Copy link
Contributor

@bnjbvr bnjbvr left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since mirror-mirror is a lib, it's nice to avoid panicking as much as possible, especially if considering fuzzing situations where randomly generated keypaths would hit such a case trivially. Could we instead return None for those cases, and add in the doc-comment for KeyPath and the macro that indexes larger than usize::max_value() won't work?

@bnjbvr
Copy link
Contributor

bnjbvr commented Jan 10, 2023

(Sorry I didn't see the question at first.)

From options 1 and 2, option 2 looks slightly nicer to me, for the reason that it doesn't panic.

Returning None as I suggested could also work nicely, in my opinion: if you pass an index type that's bigger than a usize, you couldn't feed it to Vec::get anyways, so it conceptually returns nothing, hence None. The panic also conceptually works, but that morphs what would be a compile-time error (indexing with a larger-than-usize) into a runtime-error, and that would still be hit easily with fuzzers.

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

Successfully merging this pull request may close these issues.

value_to_usize loses precision
2 participants