Setting a hard limit on slice size, is this possible?
james.p.leblanc
james.p.leblanc at gmail.com
Sat Aug 7 13:36:52 UTC 2021
On Saturday, 7 August 2021 at 12:08:00 UTC, Paul Backus wrote:
> On Saturday, 7 August 2021 at 07:32:04 UTC, Tejas wrote:
>> And if it really is correct, then it seems once again that
>> static arrays are the answer after all:
>>
>> ```d
>> align(your_alignment) int[your_length] array;
>> ```
>> No need for structs \\('_')/
>
> The main advantage of the struct is that you can heap-allocate
> it:
>
> ```d
> auto array = new Aligned!(int[4], 16);
> ```
**First, thanks all for helping with this question!**
The simple desire to arbitrarily align an array is certainly
looking non-trivial.
Below is a simple program of both the suggested "struct" and
"align array" solutions.
Unfortunately, neither is guaranteed to place the array with the
desired alignnment.
import std.stdio;
enum ALIGNMENT=64;
enum LENGTH=10;
struct Aligned(T, size_t alignment) if (alignment >=
T.alignof)
{
align(alignment) T payload;
alias payload this;
}
void main()
{
writeln("ALIGNMENT: ", ALIGNMENT, ",\t\tLENGTH: ",
LENGTH);
int[23] junk;
align(ALIGNMENT) int[LENGTH] z;
writeln("\nusing 'align(ALIGNMENT) int[LENGTH] z;'");
writeln("\ncast(ulong) z.ptr%ALIGNMENT: ", cast(ulong)
z.ptr%ALIGNMENT);
writeln("int.alignof: ", int.alignof, ",\tint.sizeof: ",
int.sizeof);
writeln("&z[0]", &z[0]);
writeln("&z[1]", &z[1]);
writeln("&z[2]", &z[2]);
writeln("\nusing: 'Aligned!(int, ALIGNMENT)[LENGTH] x;'");
Aligned!(int, ALIGNMENT)[LENGTH] x;
writeln("x.sizeof: ", x.sizeof, "\t\tx.alignof: ",
x.alignof);
writeln("x: ", x);
writeln("\nx.ptr: ", x.ptr);
writeln("&x[0]", &x[0]);
writeln("&x[1]", &x[1]);
writeln("&x[2]", &x[2]);
writeln("\ncast(ulong) x.ptr%ALIGNMENT: ", cast(ulong)
x.ptr%ALIGNMENT);
}
---------------------------------------------------------------
and here is a sample output of a run:
ALIGNMENT: 64, LENGTH: 10
using 'align(ALIGNMENT) int[LENGTH] z;'
cast(ulong) z.ptr%ALIGNMENT: ***32***
int.alignof: 4, int.sizeof: 4
&z[0]7FFFF8D05B60
&z[1]7FFFF8D05B64
&z[2]7FFFF8D05B68
using: 'Aligned!(int, ALIGNMENT)[LENGTH] x;'
x.sizeof: 640 x.alignof: 64
x: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
x.ptr: 7FFFF8D05B90
&x[0]7FFFF8D05B90
&x[1]7FFFF8D05BD0
&x[2]7FFFF8D05C10
cast(ulong) x.ptr%ALIGNMENT: ***16***
---------------------------------------------------------------
Notice, that neither attempt yields an array starting address as
zero modulo the alignment value ...
Also, a bit weird is that the "align array" solution yields
expected
spacing between array elements, but the "struct" solution has
wider
separations ...
------------------------------------------------------
**Again, I am very appreciative of your replies and help with
this.**
I have learned quite a bit from this discussion. However, I
remain
a bit stumped by all of this....
Any ideas out there?
Best Regards,
James
More information about the Digitalmars-d-learn
mailing list