Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

f64: additional conversions #268

Merged
merged 1 commit into from
Mar 29, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading