Skip to content

Consider a custom type for easier size hints #201

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

Open
Tracked by #217
kpreid opened this issue Nov 4, 2024 · 3 comments · May be fixed by #218
Open
Tracked by #217

Consider a custom type for easier size hints #201

kpreid opened this issue Nov 4, 2024 · 3 comments · May be fixed by #218

Comments

@kpreid
Copy link
Contributor

kpreid commented Nov 4, 2024

When writing required manual Arbitrary implementations, one of the more painful elements is writing the size_hint() code, because it's a lot of arbitrary::size_hint::* function calls that must mirror the arbitrary() code. If size_hint() used a custom struct type instead of a tuple, this code could be made much more concise and legible using operators and method calls. For example, this size_hint method for one required and one possibly-required field,

fn size_hint(depth: usize) -> (usize, Option<usize>) {
    arbitrary::size_hint::and(
        Foo::size_hint(depth),
        arbitrary::size_hint::or((0, Some(0)), Bar::size_hint(depth)),
    )
}

could become something like

fn size_hint(depth: usize) -> arbitrary::SizeHint {
    Foo::size_hint(depth) + (arbitrary::SizeHint::ZERO | Bar::size_hint(depth))
}

(The original code could become shorter with some uses, but the use is itself additional boilerplate to write, particularly since it needs to be placed inside a #[cfg(feature = "arbitrary")] if there is one.)

As written, this is, of course, a breaking change of type, so it would require an arbitrary 2.0, and this isn’t worth that. I only wish to present this idea for consideration in case breaking changes are needed for other reasons.

@kpreid
Copy link
Contributor Author

kpreid commented Apr 8, 2025

A further idea: the SizeHint type could distinguish “this type or one of its parts did not produce a size hint” from “this type has no upper size limit”. This would help troubleshoot missing size_hint() implementations. (This feature could also be added later, as long as SizeHint isn't designed with wholly public fields.)

@Manishearth
Copy link
Member

+1

@kpreid
Copy link
Contributor Author

kpreid commented Apr 10, 2025

I'm working on this now.

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