Not planned
Description
I'd like to propose the addition of implicit conversion from integral numbers (byte
, short
, int
, long
) to byte array. The concrete use case is code dealing with bitwise operations, mostly related to cryptography.
My wish is to write something like this:
@ParameterizedTest
@ValueSource(ints = {Integer.MIN_VALUE, 0, 0xFF, 0xFFFF, 0xFFFFFF, Integer.MAX_VALUE})
void test(byte[] byteArray) {
assertThat(byteArray).hasSize(4);
}
where I can leverage binary and hexadecimal literals which are automatically converted to a byte array using a ByteBuffer
with Big Endian order.
I put together a small poc with a custom argument converter. If the proposal is accepted, I'm happy to raise a PR about it.
Deliverables
- A new implicit conversion from
byte
/short
/int
/long
tobyte[]
Activity
sbrannen commentedon Sep 2, 2021
For that use case, you wouldn't use an
ArgumentConverter
since that can only convert a single argument.Rather, you would use an
ArgumentsAggregator
to aggregate all arguments into a single array.sbrannen commentedon Sep 2, 2021
In addition, I don't see how we could introduce implicit support for that without breaking existing use cases, but perhaps I'm overlooking something.
scordio commentedon Sep 2, 2021
@sbrannen I meant something different. Probably a more detailed example would've explained it better.
I don't want to aggregate all the arguments in a single array, I want each argument to be converted into a dedicated byte array, with array size depending on the primitive type.
Following my example:
each integer would be converted to a separate byte array of size 4, being the size in bytes of the integer type (i.e.,
Integer.BYTES
). In case of byte values, each array would have size 1; shorts would have arrays of size 2, and longs would have arrays of size 8.The test cases for the custom converter might explain it better than my words 🙂
scordio commentedon Sep 3, 2021
Written in a style similar to the official docs, this is what I'd like to have:
byte
/Byte
byte[]
0xF
→ByteBuffer.allocate(Byte.BYTES).put((byte) 0xF).array()
short
/Short
byte[]
0xFFF
→ByteBuffer.allocate(Short.BYTES).putShort((short) 0xFFF).array()
int
/Integer
byte[]
0xFFFFFFF
→ByteBuffer.allocate(Integer.BYTES).putInt(0xFFFFFFF).array()
long
/Long
byte[]
0xFFFFFFFFL
→ByteBuffer.allocate(Long.BYTES).putLong(0xFFFFFFFFL).array()
[-]Implicit conversion from numbers to byte array[/-][+]Implicit conversion from integral numbers to byte array[/+]Add implicit conversion from integral types to byte array
scordio commentedon Sep 7, 2021
I raised #2711 to help evaluate this feature.
Add implicit conversion from integral types to byte array
29 remaining items