-
-
Notifications
You must be signed in to change notification settings - Fork 408
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement TryFromJs for Either<L, R> (#3822)
* Implement TryFromJs for Either<L, R> * Add explicit feature in Cargo.toml
- Loading branch information
Showing
4 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
//! Implementation of [`TryFromJs`] for [`Either`]. | ||
//! | ||
//! This will try to deserialize for the [`Either::Left`] type | ||
//! first, and if it fails will try the [`Either::Right`] type. | ||
//! | ||
//! Upon failure of both, the second failure will be returned. | ||
#![cfg(feature = "either")] | ||
|
||
use crate::value::TryFromJs; | ||
use boa_engine::{Context, JsResult, JsValue}; | ||
use either::Either; | ||
|
||
impl<L, R> TryFromJs for Either<L, R> | ||
where | ||
L: TryFromJs, | ||
R: TryFromJs, | ||
{ | ||
#[inline] | ||
fn try_from_js(value: &JsValue, context: &mut Context) -> JsResult<Self> { | ||
L::try_from_js(value, context) | ||
.map(Self::Left) | ||
.or_else(|_| R::try_from_js(value, context).map(Self::Right)) | ||
} | ||
} | ||
|
||
#[test] | ||
fn either() { | ||
let v = JsValue::Integer(123); | ||
let mut context = Context::default(); | ||
|
||
assert_eq!( | ||
Either::<i32, i32>::try_from_js(&v, &mut context), | ||
Ok(Either::Left(123)) | ||
); | ||
assert_eq!( | ||
Either::<i32, String>::try_from_js(&v, &mut context), | ||
Ok(Either::Left(123)) | ||
); | ||
assert_eq!( | ||
Either::<String, i32>::try_from_js(&v, &mut context), | ||
Ok(Either::Right(123)) | ||
); | ||
assert!(Either::<String, String>::try_from_js(&v, &mut context).is_err()); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters