density
density copied to clipboard
RFC: byteCopy (aka. memcpy)
Piece of code to copy chunks of bytes:
function copyBytes(bytes from, uint fromOffset, uint length, uint toOffset) returns (bytes) {
bytes memory to = new bytes(toOffset + length);
return copyBytes(from, fromOffset, length, to, toOffset);
}
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
// Buffer too small
throw; // Should be a better way?
}
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}