Skip to content

Instantly share code, notes, and snippets.

@jackmott
Last active June 13, 2018 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackmott/76291e24c87c3d4c211728efe15d9383 to your computer and use it in GitHub Desktop.
Save jackmott/76291e24c87c3d4c211728efe15d9383 to your computer and use it in GitHub Desktop.
rust vs c
// An example of how tuples and treating if statements as expressions makes things nicer
// C version, a snippet from simlpex noise.
int i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords
int i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords
if (x0 >= y0) {
if (y0 >= z0) {
i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 1; k2 = 0;
}
else if (x0 >= z0) {
i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 0; k2 = 1;
}
else {
i1 = 0; j1 = 0; k1 = 1; i2 = 1; j2 = 0; k2 = 1;
}
}
else {
if (y0<z0) {
i1 = 0; j1 = 0; k1 = 1; i2 = 0; j2 = 1; k2 = 1;
}
else if (x0<z0) {
i1 = 0; j1 = 1; k1 = 0; i2 = 0; j2 = 1; k2 = 1;
}
else {
i1 = 0; j1 = 1; k1 = 0; i2 = 1; j2 = 1; k2 = 0;
}
}
// Rust version, less code, variables never exist in unitialized state.
let (i1, j1, k1, i2, j2, k2) =
if x0 >= y0 {
if y0 >= z0 {
(1, 0, 0, 1, 1, 0)
} else if x0 >= z0 {
(1, 0, 0, 1, 0, 1)
} else {
(0, 0, 1, 1, 0, 1)
}
} else {
if y0 < z0 {
(0, 0, 1, 0, 1, 1)
} else if x0 < z0 {
(0, 1, 0, 0, 1, 1)
} else {
(0, 1, 0, 1, 1, 0)
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment