diff --git a/poseidon2/io.nim b/poseidon2/io.nim index d5b44e1..2c8dd6b 100644 --- a/poseidon2/io.nim +++ b/poseidon2/io.nim @@ -38,7 +38,8 @@ iterator elements*(bytes: openArray[byte], _: type F): F = yield finalElement # Remark: since `fromInt()` does not work at compile time, this doesn't either -func toF*(a: int) : F = - var y : F - y.fromInt(a) - return y +func toF*(a: SomeInteger | SomeUnsignedInt) : F = + when a is SomeInteger: + fromInt(result, a) + else: + fromUInt(result, a) diff --git a/tests/poseidon2/testIo.nim b/tests/poseidon2/testIo.nim index 97be438..23b1ce9 100644 --- a/tests/poseidon2/testIo.nim +++ b/tests/poseidon2/testIo.nim @@ -1,6 +1,7 @@ import std/unittest import std/sequtils import constantine/math/io/io_bigints +import constantine/math/io/io_fields import constantine/math/arithmetic import poseidon2/types import poseidon2/io @@ -54,3 +55,29 @@ suite "conversion to/from bytes": var expected: array[32, byte] marshal(expected, element.toBig(), littleEndian) check element.toBytes() == expected + +suite "conversion from integers": + + test "converts unsigned integers to a field element": + + proc checkConversion[I](integer: I) = + var expected: F + fromUint(expected, integer) + check bool(integer.toF == expected) + + checkConversion(0x11'u8) + checkConversion(0x1122'u16) + checkConversion(0x11223344'u32) + checkConversion(0x1122334455667788'u64) + + test "converts signed integers to a field element": + + proc checkConversion[I](integer: I) = + var expected: F + fromInt(expected, integer) + check bool(integer.toF == expected) + + checkConversion(0x11'i8) + checkConversion(0x1122'i16) + checkConversion(0x11223344'i32) + checkConversion(0x1122334455667788'i64)