On Friday, 6 August 2021 at 18:02:01 UTC, james.p.leblanc wrote:
mes
On Friday, 6 August 2021 at 17:25:24 UTC, Tejas wrote:

Okay we were overthinking the solution.

Just use a static array

```d
int[your_max_length]/*or whatever type*/ var;
```

You're good to go!

I almost feel stupid now lol

Hello Tejas,

Kind thanks for your replies ... all are appreciated.

However, do NOT feel stupid ... the motivation behind why
I cannot use a standard int[your_max_length] (in other words,
use a static array), is because I need to do a specified
memory alignment (known at compile time) on my slice, or array.

I understand that neither a slice or an array is capable to doing an arbitrary memory alignment. (But, perhaps I am wrong about this ...)

I believe structs can be aligned, but need to learn more about
the speicific of that.

In the meantime, I have written a way to get an aligned slice from a static array. Ugly beginner code is below. While I believe this basic idea should work, I would like to guarantee that my slice does not get
moved in memory (destroying the alignment).

Ugly code here:

----------------------------------------------

import std.stdio;

enum MAXLENGTH = 1024;
enum ALIGN = 128;

void main(){

   // static array to allow creation of aligned slice
   ubyte[MAXLENGTH+ALIGN] u;

   writeln("u.ptr:  ", u.ptr);
   auto u_i = cast(ulong) u.ptr;

   auto u_excess = u_i%ALIGN;
   writeln("u_excess: ", u_excess);

   ulong mustadd;
   if(u_excess !=0){
   mustadd = ALIGN-u_excess;
   }
   writeln("mustadd:  ", mustadd);

   // create aligned pointer for our needed slice
   auto zp = cast(double*) (u.ptr + mustadd);

   // create slice
   double[] z = zp[0 .. MAXLENGTH];
   writeln("z.ptr:  ", z.ptr);
   writeln("z.length:  ", z.length);
   auto z_i = cast(ulong) z.ptr;
   auto z_excess = z_i%ALIGN;
   writeln("z_excess:  ", z_excess);
}

If you're being that specialized, don't bother with fundamental data types, the hunt for simplicity will lead you to create very complex things.

As HS Teoh said, take a look at ```align```:
https://dlang.org/spec/attribute.html#align

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);
}
```

Reply via email to