Skip to content

Instantly share code, notes, and snippets.

@Hafthor
Last active August 5, 2022 15:10
Show Gist options
  • Save Hafthor/0e9b13da0dfee11c925f74e36af15824 to your computer and use it in GitHub Desktop.
Save Hafthor/0e9b13da0dfee11c925f74e36af15824 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 UnsafeCopy(byte[] sa, uint s, byte[] da, uint d, uint c) {
unchecked {
fixed (byte* sp = sa, dp = da) {
byte* si = sp + s, di = dp + d;
if (c >= 1 && (d & 1) != 0) { // word align
*((byte*)di) = *((byte*)si);
si++; di++; c--; d++;
}
if (c >= 2 && (d & 2) != 0) { // dword align
*((short*)di) = *((short*)si);
si += 2; di += 2; c -= 2; d += 2;
}
if (c >= 4 && (d & 4) != 0) { // qword align
*((int*)di) = *((int*)si);
si += 4; di += 4; c -= 4;
}
while (c >= 8) { // qword copy
*((long*)di) = *((long*)si);
si += 8; di += 8; c -= 8;
}
if (c >= 4) { // dword remainder
*((int*)di) = *((int*)si);
si += 4; di += 4; c -= 4;
}
if (c >= 2) { // word remainder
*((short*)di) = *((short*)si);
si += 2; di += 2; c -= 2;
}
if (c >= 1) { // byte remainder
*((byte*)di) = *((byte*)si);
// si++; di++; c--;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment