Skip to content

Instantly share code, notes, and snippets.

@andreafspeziale
Created December 17, 2019 23:06
Show Gist options
  • Save andreafspeziale/8ff1a5f461e0e39d868fab358ccece9b to your computer and use it in GitHub Desktop.
Save andreafspeziale/8ff1a5f461e0e39d868fab358ccece9b to your computer and use it in GitHub Desktop.
Unpack a concatenated dynamic size bytes
/**
 * @dev Returns an array of bytes from the concat of dynamic size bytes.
 * @param data  The concatenated bytes.
 * @param sizes The size of each bytes.
 */
function unpack(
  bytes memory data,
  uint32[] memory sizes
)
  internal
  pure
  returns(bytes[] memory)
{
  bytes[] memory results = new bytes[](sizes.length);
  uint position = 0;
  for (uint i = 0; i < sizes.length; i++) {
    results[i] = data.slice(position, sizes[i]);
    position += sizes[i];
  }
  require(
    position == data.length,
    "fn: unpack(), msg: wrong data length (dynamic)"
  );
  return results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment