-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
feat(ecs): add Assume
and Unpack
traits for Result
conversion
#17739
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
5824f4f
feat(utils): add `OptionExt` trait for `Result` conversion
JeanMertz e0c3704
fixup! feat(utils): add `OptionExt` trait for `Result` conversion
JeanMertz f384475
fixup! feat(utils): add `OptionExt` trait for `Result` conversion
JeanMertz 1d84460
Merge branch 'main' into option-ext
JeanMertz 210faa7
resolve review feedback
JeanMertz 130af8b
Update crates/bevy_ecs/src/result.rs
JeanMertz 650378d
resolve review feedback
JeanMertz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 hidden or 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,66 @@ | ||
use super::Error; | ||
|
||
/// Assume that `Self<T>` is `T`, otherwise return the provided error. | ||
alice-i-cecile marked this conversation as resolved.
Show resolved
Hide resolved
|
||
/// | ||
/// This can be a drop-in replacement for `expect`, combined with the question mark operator and | ||
/// [`Result`](super::Result) return type, to get the same ergonomics as `expect` but without the | ||
/// panicking behavior (when using a non-panicking error handler). | ||
pub trait Assume<T> { | ||
/// The error type returned by [`Assume::assume`]. | ||
alice-i-cecile marked this conversation as resolved.
Show resolved
Hide resolved
alice-i-cecile marked this conversation as resolved.
Show resolved
Hide resolved
|
||
/// | ||
/// Typically implements the [`Error`] trait, allowing it to match Bevy's fallible system | ||
/// [`Result`](super::Result) return type. | ||
type Error; | ||
|
||
/// Convert `Self<T>` to a `Result<T, Self::Error>`. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. These docs will not be very helpful on mouse-over tooltips. |
||
fn assume<E: Into<Self::Error>>(self, err: E) -> Result<T, Self::Error>; | ||
} | ||
|
||
impl<T> Assume<T> for Option<T> { | ||
type Error = Error; | ||
|
||
fn assume<E: Into<Self::Error>>(self, err: E) -> Result<T, Self::Error> { | ||
self.ok_or_else(|| err.into()) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
use crate::std::string::ToString; | ||
use core::{error::Error, fmt}; | ||
|
||
#[test] | ||
fn test_assume_some() { | ||
let value: Option<i32> = Some(20); | ||
|
||
match value.assume("Error message") { | ||
Ok(value) => assert_eq!(value, 20), | ||
Err(err) => panic!("Unexpected error: {err}"), | ||
} | ||
} | ||
|
||
#[test] | ||
fn test_assume_none_with_str() { | ||
let value: Option<i32> = None; | ||
let err = value.assume("index 1 should exist").unwrap_err(); | ||
assert_eq!(err.to_string(), "index 1 should exist"); | ||
} | ||
|
||
#[test] | ||
fn test_assume_none_with_custom_error() { | ||
#[derive(Debug)] | ||
struct MyError; | ||
|
||
impl fmt::Display for MyError { | ||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
write!(f, "My custom error") | ||
} | ||
} | ||
impl Error for MyError {} | ||
|
||
let value: Option<i32> = None; | ||
let err = value.assume(MyError).unwrap_err(); | ||
assert_eq!(err.to_string(), "My custom error"); | ||
} | ||
} |
This file contains hidden or 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,56 @@ | ||
use core::{error::Error, fmt}; | ||
|
||
/// Unpack `Self<T>` to `T`, otherwise return [`Unpack::Error`]. | ||
alice-i-cecile marked this conversation as resolved.
Show resolved
Hide resolved
|
||
/// | ||
/// This can be a drop-in replacement for `unwrap`, combined with the question mark operator and | ||
/// [`Result`](super::Result) return type, to get the same ergonomics as `unwrap` but without the | ||
/// panicking behavior (when using a non-panicking error handler). | ||
pub trait Unpack<T> { | ||
/// The error type returned by [`Unpack::unpack`]. | ||
/// | ||
/// Typically implements the [`Error`] trait, allowing it to match Bevy's fallible system | ||
/// [`Result`](super::Result) return type. | ||
type Error; | ||
|
||
/// Convert `Self<T>` to a `Result<T, Self::Error>`. | ||
fn unpack(self) -> Result<T, Self::Error>; | ||
} | ||
|
||
impl<T> Unpack<T> for Option<T> { | ||
type Error = NoneError; | ||
|
||
fn unpack(self) -> Result<T, Self::Error> { | ||
self.ok_or(NoneError) | ||
} | ||
} | ||
|
||
/// An [`Error`] which indicates that an [`Option`] was [`None`]. | ||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] | ||
pub struct NoneError; | ||
|
||
impl fmt::Display for NoneError { | ||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
write!(f, "Unexpected None value.") | ||
} | ||
} | ||
|
||
impl Error for NoneError {} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
use crate::std::string::ToString; | ||
|
||
#[test] | ||
fn test_unpack_some() { | ||
let value: Option<i32> = Some(10); | ||
assert_eq!(value.unpack(), Ok(10)); | ||
} | ||
|
||
#[test] | ||
fn test_unpack_none() { | ||
let value: Option<i32> = None; | ||
let err = value.unpack().unwrap_err(); | ||
assert_eq!(err.to_string(), "Unexpected None value."); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.