Hello,
I am trying to solve a problem.
Problem statement : Implement a simple function copying a bytes memory array in most gas efficient way using inline assembly (The copied array must be a deep copy. In other words, the copy cannot merely be a reference to the original array.)
Here is my code. Would be great if someone can help me
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.19;
abstract contract Challenge {
/**
* @notice Returns a copy of the given array in a gas efficient way.
* @dev This contract will be called internally.
* @param array The array to copy.
* @return copy The copied array.
*/
function copyArray(bytes memory array)
internal
pure
returns (bytes memory copy)
{
assembly {
let length := mload(array)
copy := mload(0x40)
mstore(0x40, add(copy, add(32, mul(length, 32))))
mstore(copy, length)
if gt(length, 0) {
let src := add(array, 32)
let dst := add(copy, 32)
let end := add(src, mul(length, 32))
for { } lt(src, end) { } {
mstore(dst, mload(src))
src := add(src, 32)
dst := add(dst, 32)
}
}
}
//return copy;
}
}