Skip to content

Commit

Permalink
feat: add unwrap_or and unwrap_default (#4203)
Browse files Browse the repository at this point in the history
  • Loading branch information
Eikix authored Oct 12, 2023
1 parent da581bf commit 52ec2d3
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions corelib/src/option.cairo
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
use array::ArrayTrait;
use serde::Serde;
use array::SpanTrait;

#[derive(Copy, Drop, Serde, PartialEq)]
enum Option<T> {
Some: T,
Expand All @@ -20,7 +16,12 @@ trait OptionTrait<T> {
fn is_some(self: @Option<T>) -> bool;
/// Returns `true` if the `Option` is `Option::None`.
fn is_none(self: @Option<T>) -> bool;
/// If `self` is `Option::Some(x)`, returns `x`. Otherwise, returns the provided default.
fn unwrap_or<+Drop<T>>(self: Option<T>, default: T) -> T;
/// If `self` is `Option::Some(x)`, returns `x`. Otherwise, returns `Default::<T>::default()`.
fn unwrap_or_default<+Default<T>>(self: Option<T>) -> T;
}

impl OptionTraitImpl<T> of OptionTrait<T> {
#[inline(always)]
fn expect(self: Option<T>, err: felt252) -> T {
Expand Down Expand Up @@ -58,4 +59,20 @@ impl OptionTraitImpl<T> of OptionTrait<T> {
Option::None => true,
}
}

#[inline]
fn unwrap_or<+Drop<T>>(self: Option<T>, default: T) -> T {
match self {
Option::Some(x) => x,
Option::None => default,
}
}

#[inline]
fn unwrap_or_default<+Default<T>>(self: Option<T>) -> T {
match self {
Option::Some(x) => x,
Option::None => Default::default(),
}
}
}

0 comments on commit 52ec2d3

Please sign in to comment.