arbitrary icon indicating copy to clipboard operation
arbitrary copied to clipboard

Consider a custom type for easier size hints

Open kpreid opened this issue 1 year ago • 3 comments

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 avatar Nov 04 '24 00:11 kpreid

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.)

kpreid avatar Apr 08 '25 22:04 kpreid

+1

Manishearth avatar Apr 09 '25 00:04 Manishearth

I'm working on this now.

kpreid avatar Apr 10 '25 01:04 kpreid