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

james.p.leblanc james.p.leblanc at gmail.com
Fri Aug 6 18:02:01 UTC 2021


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


More information about the Digitalmars-d-learn mailing list