From b58cc700ad25b358748dbb74e7da901d0bdca0fc Mon Sep 17 00:00:00 2001 From: Weikeng Chen Date: Mon, 23 Nov 2020 16:30:17 -0800 Subject: [PATCH] Add ToBytes and FromBytes for u128 (#94) * add the to and from bytes for u128 * update the CHANGELOG --- CHANGELOG.md | 2 +- ff/src/bytes.rs | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b8e9ddce8..d954f18f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,7 @@ - #31 (ark-ec) Speedup point doubling on twisted edwards curves - #35 (ark-ff) Implement `ToConstraintField` for `bool` - #48 (ark-ff) Speedup `sqrt` on `QuadExtField` - +- #94 (ark-ff) Implement `ToBytes` and `FromBytes` for `u128` ### Bug fixes - #36 (ark-ec) In Short-Weierstrass curves, include an infinity bit in `ToConstraintField`. diff --git a/ff/src/bytes.rs b/ff/src/bytes.rs index 257a18d9e..5ddf42fe9 100644 --- a/ff/src/bytes.rs +++ b/ff/src/bytes.rs @@ -100,6 +100,29 @@ macro_rules! array_bytes { Ok(res) } } + + impl ToBytes for [u128; $N] { + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + for num in self { + writer.write_all(&num.to_le_bytes())?; + } + Ok(()) + } + } + + impl FromBytes for [u128; $N] { + #[inline] + fn read(mut reader: R) -> IoResult { + let mut res = [0u128; $N]; + for num in res.iter_mut() { + let mut bytes = [0u8; 16]; + reader.read_exact(&mut bytes)?; + *num = u128::from_le_bytes(bytes); + } + Ok(res) + } + } }; } @@ -225,6 +248,22 @@ impl FromBytes for u64 { } } +impl ToBytes for u128 { + #[inline] + fn write(&self, mut writer: W) -> IoResult<()> { + writer.write_all(&self.to_le_bytes()) + } +} + +impl FromBytes for u128 { + #[inline] + fn read(mut reader: R) -> IoResult { + let mut bytes = [0u8; 16]; + reader.read_exact(&mut bytes)?; + Ok(u128::from_le_bytes(bytes)) + } +} + impl ToBytes for () { #[inline] fn write(&self, _writer: W) -> IoResult<()> {