Skip to content

Instantly share code, notes, and snippets.

@TheGag96
Created March 11, 2020 02:32
Show Gist options
  • Save TheGag96/243f5da9a93e82db610656244692de92 to your computer and use it in GitHub Desktop.
Save TheGag96/243f5da9a93e82db610656244692de92 to your computer and use it in GitHub Desktop.
D SOA example
import std.string : format;
struct Soa(T, long n) {
static foreach (member; T.tupleof) {
mixin(format("typeof(member)[n] %s;", member.stringof));
}
T opIndex(size_t index) const {
T result = void;
static foreach (member; T.tupleof) {
mixin(format("result.%s = %s[index];", member.stringof, member.stringof));
}
return result;
}
//could be done with opIndexAssign
void set(size_t index, ref T t) {
static foreach (member; T.tupleof) {
mixin(format("%s[index] = t.%s;", member.stringof, member.stringof));
}
}
int opApply(scope int delegate(ref T) dg) {
int result = 0;
foreach (i; 0..n) {
auto t = this[i];
result = dg(t);
set(i, t); //can't differentiate between foreach by value or ref, so this ALWAYS gets called...
if (result) break;
}
return result;
}
//handle const this case (a bit annoying to duplicate...)
int opApply(scope int delegate(ref const T) dg) const {
int result = 0;
foreach (i; 0..n) {
auto t = this[i];
result = dg(t);
if (result) break;
}
return result;
}
}
struct Vector {
float x, y, z;
}
void main() {
import std.stdio;
Soa!(Vector, 16) vecs;
foreach (ref v; vecs) {
v.x = 3;
}
vecs.x[3] = 2.1;
vecs.y[3] = -40;
writeln(vecs);
writeln(vecs[3]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment