Skip to content

Commit

Permalink
refactor: replace BytesLib with assembly block
Browse files Browse the repository at this point in the history
  • Loading branch information
b00ste committed Oct 12, 2023
1 parent abeac4f commit e908016
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import {
import {
EnumerableSet
} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {BytesLib} from "solidity-bytes-utils/contracts/BytesLib.sol";

// modules
import {
Expand Down Expand Up @@ -103,14 +102,26 @@ abstract contract LSP8CompatibleERC721 is
) public view virtual returns (string memory) {
bytes memory data = _getData(_LSP4_METADATA_KEY);

// offset = bytes4(hashSig) + bytes32(contentHash) -> 4 + 32 = 36
uint256 offset = 36;
if (data.length <= 36) {
return "";
}

bytes memory uriBytes = BytesLib.slice(
data,
offset,
data.length - offset
);
uint256 requiredLength = data.length - 36;
bytes memory uriBytes;
// solhint-disable-next-line no-inline-assembly
assembly {
uriBytes := mload(0x40)
mstore(uriBytes, requiredLength)
for {
let i := 0
} lt(i, requiredLength) {
i := add(i, 32)
} {
mstore(add(uriBytes, add(i, 32)), mload(add(data, add(i, 68))))
}
// Update the free memory pointer
mstore(0x40, add(uriBytes, add(32, requiredLength)))
}
return string(uriBytes);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import {
import {
EnumerableSet
} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {BytesLib} from "solidity-bytes-utils/contracts/BytesLib.sol";

// modules
import {
Expand Down Expand Up @@ -111,14 +110,26 @@ abstract contract LSP8CompatibleERC721InitAbstract is
) public view virtual returns (string memory) {
bytes memory data = _getData(_LSP4_METADATA_KEY);

// offset = bytes4(hashSig) + bytes32(contentHash) -> 4 + 32 = 36
uint256 offset = 36;
if (data.length <= 36) {
return "";
}

bytes memory uriBytes = BytesLib.slice(
data,
offset,
data.length - offset
);
uint256 requiredLength = data.length - 36;
bytes memory uriBytes;
// solhint-disable-next-line no-inline-assembly
assembly {
uriBytes := mload(0x40)
mstore(uriBytes, requiredLength)
for {
let i := 0
} lt(i, requiredLength) {
i := add(i, 32)
} {
mstore(add(uriBytes, add(i, 32)), mload(add(data, add(i, 68))))
}
// Update the free memory pointer
mstore(0x40, add(uriBytes, add(32, requiredLength)))
}
return string(uriBytes);
}

Expand Down

0 comments on commit e908016

Please sign in to comment.