Skip to content

Commit

Permalink
feat: Add more impls on Option (#4549)
Browse files Browse the repository at this point in the history
# Description

## Problem\*

Resolves 

## Summary\*

Adds more trait implementations on the Option type.

## Additional Context

This PR depends on #4470 to be
merged first since it requires `bool: Hash`

## Documentation\*

Check one:
- [ ] No documentation needed.
- [ ] Documentation included in this PR.
- [x] **[Exceptional Case]** Documentation to be submitted in a separate
PR.
- Once both this and #4470 are
merged I think I'll add all the new impls to the docs at once.

# PR Checklist\*

- [x] I have tested the changes locally.
- [x] I have formatted the changes with [Prettier](https://prettier.io/)
and/or `cargo fmt` on default settings.
  • Loading branch information
jfecher committed Mar 15, 2024
1 parent 8396e21 commit 4cf700b
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions noir_stdlib/src/option.nr
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
use crate::hash::{Hash, Hasher};
use crate::cmp::{Ordering, Ord, Eq};
use crate::default::Default;

struct Option<T> {
_is_some: bool,
_value: T,
Expand Down Expand Up @@ -152,3 +156,51 @@ impl<T> Option<T> {
}
}
}

impl<T> Default for Option<T> {
fn default() -> Self {
Option::none()
}
}

impl<T> Eq for Option<T> where T: Eq {
fn eq(self, other: Self) -> bool {
if self._is_some == other._is_some {
if self._is_some {
self._value == other._value
} else {
true
}
} else {
false
}
}
}

impl<T> Hash for Option<T> where T: Hash {
fn hash<H>(self, state: &mut H) where H: Hasher {
self._is_some.hash(state);
if self._is_some {
self._value.hash(state);
}
}
}

// For this impl we're declaring Option::none < Option::some
impl<T> Ord for Option<T> where T: Ord {
fn cmp(self, other: Self) -> Ordering {
if self._is_some {
if other._is_some {
self._value.cmp(other._value)
} else {
Ordering::greater()
}
} else {
if other._is_some {
Ordering::less()
} else {
Ordering::equal()
}
}
}
}

0 comments on commit 4cf700b

Please sign in to comment.