diff --git a/math/src/field/f64/mod.rs b/math/src/field/f64/mod.rs index d8a788dec..cd4b07c2f 100644 --- a/math/src/field/f64/mod.rs +++ b/math/src/field/f64/mod.rs @@ -537,6 +537,13 @@ impl From for BaseElement { } } +impl From for BaseElement { + /// Converts an bool value into a field element. + fn from(value: bool) -> Self { + Self::new(value as u64) + } +} + impl TryFrom for BaseElement { type Error = String; @@ -612,6 +619,42 @@ impl From for u64 { } } +impl TryFrom for u32 { + type Error = String; + + fn try_from(value: BaseElement) -> Result { + value.as_int().try_into().map_err(|e| format!("{}", e)) + } +} + +impl TryFrom for u16 { + type Error = String; + + fn try_from(value: BaseElement) -> Result { + value.as_int().try_into().map_err(|e| format!("{}", e)) + } +} + +impl TryFrom for u8 { + type Error = String; + + fn try_from(value: BaseElement) -> Result { + value.as_int().try_into().map_err(|e| format!("{}", e)) + } +} + +impl TryFrom for bool { + type Error = String; + + fn try_from(value: BaseElement) -> Result { + match value.as_int() { + 0 => Ok(false), + 1 => Ok(true), + v => Err(format!("Field element does not represent a boolean, got {}", v)), + } + } +} + impl AsBytes for BaseElement { fn as_bytes(&self) -> &[u8] { // TODO: take endianness into account