File tree Expand file tree Collapse file tree 2 files changed +21
-0
lines changed Expand file tree Collapse file tree 2 files changed +21
-0
lines changed Original file line number Diff line number Diff line change @@ -195,6 +195,25 @@ macro_rules! invariant {
195195 } ;
196196}
197197
198+ /// Attempts to unwrap an [Option], and if it fails, prints an error.
199+ ///
200+ /// # Example
201+ ///
202+ /// ```
203+ /// let one = 1;
204+ /// let two = 2;
205+ /// let my_value = unwrap_opt!(one.checked_sub(2), "cannot do this"); // returns an error
206+ /// ```
207+ #[ macro_export]
208+ macro_rules! unwrap_opt{
209+ ( $option: expr, $err: expr $( , ) ?) => {
210+ $option. ok_or_else( || -> {
211+ msg!( "Option unwrap failed: {:?}" , $err) ;
212+ ProgramError { $crate:: VipersError :: OptionUnwrapFailed . into( ) }
213+ } ) ?
214+ } ;
215+ }
216+
198217#[ cfg( test) ]
199218mod tests {
200219 use anchor_lang:: prelude:: * ;
Original file line number Diff line number Diff line change @@ -40,4 +40,6 @@ pub enum VipersError {
4040 InvalidATA ,
4141 #[ msg( "Invariant failed." ) ]
4242 InvariantFailed ,
43+ #[ msg( "Option unwrap failed." ) ]
44+ OptionUnwrapFailed ,
4345}
You can’t perform that action at this time.
0 commit comments