Skip to content
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

feat(ecs): add Assume and Unpack traits for Result conversion #17739

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions crates/bevy_utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,12 @@ extern crate alloc;
/// This includes the most common types in this crate, re-exported for your convenience.
pub mod prelude {
pub use crate::default;
#[cfg(feature = "alloc")]
pub use crate::option_ext::OptionExt as _;
JeanMertz marked this conversation as resolved.
Show resolved Hide resolved
}

#[cfg(feature = "alloc")]
pub mod option_ext;
pub mod synccell;
pub mod syncunsafecell;

Expand All @@ -34,6 +38,8 @@ mod parallel_queue;
pub use once::OnceFlag;

pub use default::default;
#[cfg(feature = "alloc")]
pub use option_ext::NoneError;

#[cfg(feature = "std")]
pub use parallel_queue::*;
Expand Down
90 changes: 90 additions & 0 deletions crates/bevy_utils/src/option_ext.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
//! Extensions to the [`Option`] type used in Bevy.
JeanMertz marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I also think the odds of these being included in std are slim. And assume, once Bevy's error type isn't just a boxed core Error, couldn't possibly live in std. And even if unpack were to land in std, it would likely be closer to the "years" timeframe than the "months" timeframe.


use crate::alloc::boxed::Box;
use core::{error::Error, fmt};

/// A custom type which implements [`Error`], used to indicate 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 {}

/// Extension trait for [`Option`].
pub trait OptionExt<T> {
JeanMertz marked this conversation as resolved.
Show resolved Hide resolved
/// Convert an `Option<T>` to a `Result<T, NoneError>`.
fn unpack(self) -> Result<T, NoneError>;

/// Convert an `Option<T>` to a `Result<T, Box<dyn Error>>`.
fn assume<E: Into<Box<dyn Error>>>(self, err: E) -> Result<T, Box<dyn Error>>;
}

/// Extensions for [`Option`].
impl<T> OptionExt<T> for Option<T> {
/// Convert an `Option<T>` to a `Result<T, NoneError>`.
fn unpack(self) -> Result<T, NoneError> {
self.ok_or(NoneError)
}

/// Convert an `Option<T>` to a `Result<T, Box<dyn Error>>`.
fn assume<E: Into<Box<dyn Error>>>(self, err: E) -> Result<T, Box<dyn Error>> {
self.ok_or_else(|| err.into())
}
}
#[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.");
}

#[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");
}
}
Loading