Setting a hard limit on slice size, is this possible?

Paul Backus snarwin at gmail.com
Fri Aug 6 11:58:59 UTC 2021


On Friday, 6 August 2021 at 10:50:19 UTC, james.p.leblanc wrote:
> I am aware of the "capacity" concept with slices.
>
> But, I would like to know if it is possible to set a
> hard limit on a slice size.
>
> I prefer it to error and crash instead of a doing an
> extension or reallocation.

I don't think there's any way to make built-in slices behave like 
this, but you can pretty easily define your own wrapper type:

```d
struct MySlice(T, size_t maxLength)
{
     private T[] payload;

     invariant(payload.length <= maxLength);

     this(T[] slice) { payload = slice; }

     T opIndex(size_t i) { return payload[i]; }

     // etc.
}
```


More information about the Digitalmars-d-learn mailing list