Conversion of field elements into bytes

This commit is contained in:
Mark Spanbroek 2023-11-02 09:57:54 +01:00 committed by markspanbroek
parent 5e980dd816
commit 1c7c5d4ec4
2 changed files with 13 additions and 0 deletions

View File

@ -1,6 +1,7 @@
import ./types import ./types
import constantine/math/arithmetic import constantine/math/arithmetic
import constantine/math/io/io_bigints import constantine/math/io/io_bigints
import constantine/math/config/curves
func unmarshal*(_: type F, bytes: openArray[byte]): F = func unmarshal*(_: type F, bytes: openArray[byte]): F =
## Converts bytes into a field element. The byte array is interpreted as a ## Converts bytes into a field element. The byte array is interpreted as a
@ -25,3 +26,9 @@ func unmarshal*(_: type seq[F], bytes: openArray[byte]): seq[F] =
elements.add(element) elements.add(element)
chunkStart += chunkLen chunkStart += chunkLen
return elements return elements
func marshal*(element: F): array[32, byte] =
## Converts a field element into its canonical representation in little-endian
## byte order. Uses at most 254 bits, the remaining 6 most-significant bits
## are set to 0.
assert marshal(result, element.toBig(), littleEndian)

View File

@ -33,3 +33,9 @@ suite "unmarshalling":
check bool(elements[1] == expected2) check bool(elements[1] == expected2)
check bool(elements[2] == expected3) check bool(elements[2] == expected3)
test "converts field element into little-endian bytes":
var element: F
setMinusOne(element) # largest element in the field
var expected: array[32, byte]
marshal(expected, element.toBig(), littleEndian)
check element.marshal() == expected