Skip to content

Exhaust sequences up to a length? #50

@kpreid

Description

@kpreid

It might be useful to have a utility type which allows producing collections up to a certain length. Perhaps:

/// * N = max size
/// * C = collection type
/// * T = element type
struct UpTo<const N: usize, C, T> { ... }

impl<const N: usize, C, T> UpTo<N, C, T> {
    fn into_inner(self) -> C { ... }
}

impl<const N: usize, C, T> Exhaust for UpTo<N, C, T>
where
    T: Exhaust,
    C: FromIterator<T>,
{ ... }

This is not a very elegant interface, but the important part of deciding whether to provide it is how difficult the algorithm to actually produce the items turns out to be — how much work we save the user. (Perhaps we should expose the algorithm and not a type that uses it?) For small cases, a user could just

#[derive(Exhaust)]
enum UpTo3<T> {
    Zero,
    One([T; 1]),
    Two([T; 2]),
    Three([T; 3]),
}

but that can't be generic over length, and is sorted by length instead of lexicographically. Another derive-based approach, producing lexicographic ordering, would be

#[derive(Exhaust)]
enum Another<T, C> {
    No(C),
    Yes(T, C),
}

type UpTo3<T> = Another<T, Another<T, Another<T, ()>>>;

but again, it isn't const generic and would give the compiler a lot of work to do.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions