Const generic `RangeSlice`

I've seen various discussion along these lines before, and perhaps a crate for it already exists, but...

Proposal: a slice newtype/"smart pointer" type which has a const generic LENGTH: Range<usize> and enforces a type-level invariant that the LENGTH range contains the length of the inner slice.

pub struct RangeSlice<'a, T, const LENGTH: Range<usize>> {
    inner: &'a [T]

Notably this type can't yet be written on stable Rust as it needs feature(adt_const_params) but could be implemented as a nightly-only crate.

However, it seems like the sort of thing that would benefit with direct integration with the slice primitive type, although that can be worked around using extension traits.

Is there any current work happening along these lines, or perhaps a crate? Or failing either of those, does anyone else think something like this would eventually be beneficial in core?

1 Like

The minimum "at least as long as" is clearly beneficial. What benefit would a maximum length provide?

(As a primitive type this'd probably be spelled &[T; MIN..MAX].)

These sorts of ranged inputs with a minimum and maximum size are frequently found in cryptography, where various algorithmic inputs can be variable-sized but with a specified minimum and maximum.

Here's a specific example:

  • The length in bytes of the salt is between 8 and 48 bytes
  • The hash output is encoded in B64. Its length shall be between 12 and 64 bytes