Skip to content

Commit

Permalink
Add library to handle bytes memory slices
Browse files Browse the repository at this point in the history
  • Loading branch information
k06a committed Oct 25, 2023
1 parent 390f778 commit 1b17c18
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions contracts/libraries/BytesMemory.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

library BytesMemory {
error OutOfBounds();

struct Slice {
uint256 pointer;
uint256 length;
}

function wrap(bytes memory data) internal pure returns(Slice memory) {
uint256 pointer;
assembly ("memory-safe") { // solhint-disable-line no-inline-assembly

Check warning on line 15 in contracts/libraries/BytesMemory.sol

View check run for this annotation

Codecov / codecov/patch

contracts/libraries/BytesMemory.sol#L13-L15

Added lines #L13 - L15 were not covered by tests
pointer := add(data, 0x20)
}

return Slice({

Check warning on line 19 in contracts/libraries/BytesMemory.sol

View check run for this annotation

Codecov / codecov/patch

contracts/libraries/BytesMemory.sol#L19

Added line #L19 was not covered by tests
pointer: pointer,
length: data.length
});
}

function slice(Slice memory data, uint256 offset, uint256 size) internal pure returns(Slice memory) {

Check warning on line 25 in contracts/libraries/BytesMemory.sol

View check run for this annotation

Codecov / codecov/patch

contracts/libraries/BytesMemory.sol#L25

Added line #L25 was not covered by tests
if (offset + size > data.length) revert OutOfBounds();

return Slice({

Check warning on line 28 in contracts/libraries/BytesMemory.sol

View check run for this annotation

Codecov / codecov/patch

contracts/libraries/BytesMemory.sol#L28

Added line #L28 was not covered by tests
pointer: data.pointer + offset,
length: size
});
}

function unwrap(Slice memory piece) internal view returns(bytes memory ret) {
uint256 pointer = piece.pointer;
uint256 length = piece.length;
assembly ("memory-safe") { // solhint-disable-line no-inline-assembly

Check warning on line 37 in contracts/libraries/BytesMemory.sol

View check run for this annotation

Codecov / codecov/patch

contracts/libraries/BytesMemory.sol#L34-L37

Added lines #L34 - L37 were not covered by tests
ret := mload(0x40)
mstore(0x40, add(0x20, length))
mstore(ret, length)

pop(staticcall(gas(), 0x04, pointer, length, add(ret, 0x20), length))
}
}
}

0 comments on commit 1b17c18

Please sign in to comment.