Skip to content

Commit

Permalink
f64: additional conversions
Browse files Browse the repository at this point in the history
  • Loading branch information
hackaugusto committed Mar 28, 2024
1 parent ee09344 commit 5973566
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions math/src/field/f64/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -537,6 +537,13 @@ impl From<u8> for BaseElement {
}
}

impl From<bool> for BaseElement {
/// Converts an bool value into a field element.
fn from(value: bool) -> Self {
Self::new(value as u64)
}
}

impl TryFrom<u64> for BaseElement {
type Error = String;

Expand Down Expand Up @@ -612,6 +619,42 @@ impl From<BaseElement> for u64 {
}
}

impl TryFrom<BaseElement> for u32 {
type Error = String;

fn try_from(value: BaseElement) -> Result<Self, Self::Error> {
value.as_int().try_into().map_err(|e| format!("{}", e))
}
}

impl TryFrom<BaseElement> for u16 {
type Error = String;

fn try_from(value: BaseElement) -> Result<Self, Self::Error> {
value.as_int().try_into().map_err(|e| format!("{}", e))
}
}

impl TryFrom<BaseElement> for u8 {
type Error = String;

fn try_from(value: BaseElement) -> Result<Self, Self::Error> {
value.as_int().try_into().map_err(|e| format!("{}", e))
}
}

impl TryFrom<BaseElement> for bool {
type Error = String;

fn try_from(value: BaseElement) -> Result<Self, Self::Error> {
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
Expand Down

0 comments on commit 5973566

Please sign in to comment.