Skip to content

Commit 6934934

Browse files
committed
Adds option unwrap helper macro
1 parent 56d099a commit 6934934

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

src/assert.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff 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)]
199218
mod tests {
200219
use anchor_lang::prelude::*;

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff 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
}

0 commit comments

Comments
 (0)