density icon indicating copy to clipboard operation
density copied to clipboard

RFC: byteCopy (aka. memcpy)

Open axic opened this issue 10 years ago • 0 comments

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;
    }

axic avatar Apr 07 '16 23:04 axic