From 4cf700bcfe157ebc82cdf7321a16959b7a4add57 Mon Sep 17 00:00:00 2001 From: jfecher Date: Fri, 15 Mar 2024 08:40:43 -0500 Subject: [PATCH] feat: Add more impls on Option (#4549) # Description ## Problem\* Resolves ## Summary\* Adds more trait implementations on the Option type. ## Additional Context This PR depends on https://github.com/noir-lang/noir/pull/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 https://github.com/noir-lang/noir/pull/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. --- noir_stdlib/src/option.nr | 52 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/noir_stdlib/src/option.nr b/noir_stdlib/src/option.nr index 1c32f758af..c94a1cf836 100644 --- a/noir_stdlib/src/option.nr +++ b/noir_stdlib/src/option.nr @@ -1,3 +1,7 @@ +use crate::hash::{Hash, Hasher}; +use crate::cmp::{Ordering, Ord, Eq}; +use crate::default::Default; + struct Option { _is_some: bool, _value: T, @@ -152,3 +156,51 @@ impl Option { } } } + +impl Default for Option { + fn default() -> Self { + Option::none() + } +} + +impl Eq for Option 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 Hash for Option where T: Hash { + fn hash(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 Ord for Option 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() + } + } + } +}