Skip to content

Instantly share code, notes, and snippets.

@Hafthor
Last active August 5, 2022 23:12
Show Gist options
  • Save Hafthor/8fe5584148c54faa136f297042a3f963 to your computer and use it in GitHub Desktop.
Save Hafthor/8fe5584148c54faa136f297042a3f963 to your computer and use it in GitHub Desktop.
// Copyright (c) 2022 Hafthor Stefansson
// Distributed under the MIT/X11 software license
// Ref: http://www.opensource.org/licenses/mit-license.php.
static unsafe void UnsafeSet(byte[] a, uint d, uint c, byte v) {
unchecked {
ushort v2 = (ushort)(v << 8 | v);
uint v4 = (uint)v2 << 16 | v2;
ulong v8 = (ulong)v4 << 32 | v4;
fixed (byte* p = a) {
byte* di = p + d;
if (c >= 1 && (d & 1) != 0) { // word align
*((byte*)di) = v; di++; c--; d++;
}
if (c >= 2 && (d & 2) != 0) { // dword align
*((ushort*)di) = v2; di += 2; c -= 2; d += 2;
}
if (c >= 4 && (d & 4) != 0) { // qword align
*((uint*)di) = v4; di += 4; c -= 4;
}
while (c >= 8) { // qword set
*((ulong*)di) = v8; di += 8; c -= 8;
}
if (c >= 4) { // dword remainder
*((uint*)di) = v4; di += 4; c -= 4;
}
if (c >= 2) { // word remainder
*((ushort*)di) = v2; di += 2; c -= 2;
}
if (c >= 1) { // byte remainder
*((byte*)di) = v; // di++; c--;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment