Refactor LibBytes.readBytes4 for consistency

This commit is contained in:
Remco Bloemen
2018-06-13 18:28:11 +02:00
parent 4bf4f96f47
commit 943e556f43
4 changed files with 25 additions and 14 deletions

View File

@@ -104,7 +104,7 @@ contract AssetProxyOwner is
pure
returns (bool)
{
bytes4 first4Bytes = data.readFirst4();
bytes4 first4Bytes = data.readBytes4(0);
require(REMOVE_AUTHORIZED_ADDRESS_SELECTOR == first4Bytes);
return true;
}

View File

@@ -187,15 +187,19 @@ contract TestLibBytes {
return b;
}
/// @dev Reads the first 4 bytes from a byte array of arbitrary length.
/// @param b Byte array to read first 4 bytes from.
/// @return First 4 bytes of data.
function publicReadFirst4(bytes memory b)
/// @dev Reads an unpadded bytes4 value from a position in a byte array.
/// @param b Byte array containing a bytes4 value.
/// @param index Index in byte array of bytes4 value.
/// @return bytes4 value from byte array.
function publicReadBytes4(
bytes memory b,
uint256 index
)
public
pure
returns (bytes4 result)
{
result = b.readFirst4();
result = b.readBytes4(index);
return result;
}

View File

@@ -430,16 +430,19 @@ library LibBytes {
writeBytes32(b, index, bytes32(input));
}
/// @dev Reads the first 4 bytes from a byte array of arbitrary length.
/// @param b Byte array to read first 4 bytes from.
/// @return First 4 bytes of data.
function readFirst4(bytes memory b)
/// @dev Reads an unpadded bytes4 value from a position in a byte array.
/// @param b Byte array containing a bytes4 value.
/// @param index Index in byte array of bytes4 value.
/// @return bytes4 value from byte array.
function readBytes4(
bytes memory b,
uint256 index)
internal
pure
returns (bytes4 result)
{
require(
b.length >= 4,
b.length >= index + 4,
GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED
);
assembly {

View File

@@ -459,17 +459,21 @@ describe('LibBytes', () => {
});
});
describe('readFirst4', () => {
describe('readBytes4', () => {
// AssertionError: expected promise to be rejected with an error including 'revert' but it was fulfilled with '0x08c379a0'
it('should revert if byte array has a length < 4', async () => {
const byteArrayLessThan4Bytes = '0x010101';
return expectRevertOrOtherErrorAsync(
libBytes.publicReadFirst4.callAsync(byteArrayLessThan4Bytes),
libBytes.publicReadBytes4.callAsync(
byteArrayLessThan4Bytes,
new BigNumber(0)),
constants.LIB_BYTES_GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED,
);
});
it('should return the first 4 bytes of a byte array of arbitrary length', async () => {
const first4Bytes = await libBytes.publicReadFirst4.callAsync(byteArrayLongerThan32Bytes);
const first4Bytes = await libBytes.publicReadBytes4.callAsync(
byteArrayLongerThan32Bytes,
new BigNumber(0));
const expectedFirst4Bytes = byteArrayLongerThan32Bytes.slice(0, 10);
expect(first4Bytes).to.equal(expectedFirst4Bytes);
});