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

Paul Backus snarwin at gmail.com
Fri Aug 6 22:15:00 UTC 2021


On Friday, 6 August 2021 at 19:03:53 UTC, Tejas wrote:
>
> Stealing Paul's answer now:
> ```d
> import std;
>
> enum your_max_length = 1000;
> enum your_align = 256;
> struct MySlice(T/*, size_t maxLength*/)
> {
>     private align(your_align)T payload;
>
>     //invariant(payload.length <= maxLength);
>
>     //this(T[] slice) { payload = slice; }
>
>     //T opIndex(size_t i) { return payload[i]; }
> }
> void main()
> {
>    MySlice!(int/*, 1000*/)[your_max_length] slice;
>     writeln(slice.sizeof);
> }
> ```

You can actually pass the alignment as a parameter too:

```d
struct Aligned(T, size_t alignment)
     if (alignment >= T.alignof)
{
     align(alignment) T payload;
     alias payload this;
}

void main()
{
     Aligned!(int, 16)[4] x;
     assert(x.alignof == 16);
     assert(x.sizeof == 64);

     Aligned!(int[4], 16) y;
     assert(y.alignof == 16);
     assert(y.sizeof == 16);
}
```


More information about the Digitalmars-d-learn mailing list