Skip to content

Commit

Permalink
Add unwrap_or api for bxl.Result
Browse files Browse the repository at this point in the history
Summary: RFC: https://fb.workplace.com/groups/buck2dev/permalink/3899367573684619/

Reviewed By: JakobDegen

Differential Revision: D68863757

fbshipit-source-id: 00ee1c5550364342d693708a5a3f54af820db69f
  • Loading branch information
Nero5023 authored and facebook-github-bot committed Jan 30, 2025
1 parent 85d3c23 commit 6fffc05
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
18 changes: 18 additions & 0 deletions app/buck2_bxl/src/bxl/starlark_defs/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,17 @@ fn result_methods(builder: &mut MethodsBuilder) {
}
}

/// If the result is an `Ok`, return the inner value, otherwise return the default
fn unwrap_or<'v>(
this: ValueTypedComplex<'v, StarlarkResult<'v>>,
#[starlark(require = pos)] default: Value<'v>,
) -> starlark::Result<Value<'v>> {
match this.unpack() {
either::Either::Left(x) => Ok(x.unwrap_or(default)),
either::Either::Right(x) => Ok(x.unwrap_or(default)),
}
}

/// Unwrap the error, returning the inner error if the result is `Err`.
/// If the result is an `Ok`, it will fail
fn unwrap_err<'v>(
Expand Down Expand Up @@ -180,6 +191,13 @@ impl<'v, V: ValueLike<'v>> StarlarkResultGen<V> {
}
}

fn unwrap_or(&self, default: Value<'v>) -> Value<'v> {
match self {
StarlarkResultGen::Ok(val) => val.to_value(),
StarlarkResultGen::Err(_) => default,
}
}

fn unwrap_err(&self) -> buck2_error::Result<StarlarkError> {
match self {
StarlarkResultGen::Ok(val) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@
## Result.is\_ok
## Result.unwrap
## Result.unwrap\_err
## Result.unwrap\_or

0 comments on commit 6fffc05

Please sign in to comment.