mirror of
https://github.com/roc-lang/roc.git
synced 2025-09-29 14:54:47 +00:00
flesh out api for RocResult
This commit is contained in:
parent
c2934a509a
commit
007d777865
2 changed files with 84 additions and 0 deletions
|
@ -11,6 +11,9 @@ use crate::helpers::llvm::assert_evals_to;
|
|||
|
||||
use indoc::indoc;
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use roc_std::{RocResult, RocStr};
|
||||
|
||||
#[test]
|
||||
#[cfg(any(feature = "gen-llvm"))]
|
||||
fn with_default() {
|
||||
|
@ -219,3 +222,37 @@ fn is_err() {
|
|||
bool
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(any(feature = "gen-llvm"))]
|
||||
fn roc_result_ok() {
|
||||
assert_evals_to!(
|
||||
indoc!(
|
||||
r#"
|
||||
result : Result I64 {}
|
||||
result = Ok 42
|
||||
|
||||
result
|
||||
"#
|
||||
),
|
||||
RocResult::ok(42),
|
||||
RocResult<i64, ()>
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(any(feature = "gen-llvm"))]
|
||||
fn roc_result_err() {
|
||||
assert_evals_to!(
|
||||
indoc!(
|
||||
r#"
|
||||
result : Result I64 Str
|
||||
result = Err "foo"
|
||||
|
||||
result
|
||||
"#
|
||||
),
|
||||
RocResult::err(RocStr::from_slice(b"foo")),
|
||||
RocResult<i64, RocStr>
|
||||
);
|
||||
}
|
||||
|
|
|
@ -764,6 +764,42 @@ pub struct RocResult<T, E> {
|
|||
tag: RocResultTag,
|
||||
}
|
||||
|
||||
impl<T, E> core::fmt::Debug for RocResult<T, E>
|
||||
where
|
||||
T: core::fmt::Debug,
|
||||
E: core::fmt::Debug,
|
||||
{
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self.as_result_of_refs() {
|
||||
Ok(payload) => write!(f, "RocOk({:?})", payload),
|
||||
Err(payload) => write!(f, "RocErr({:?})", payload),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, E> PartialEq for RocResult<T, E>
|
||||
where
|
||||
T: PartialEq,
|
||||
E: PartialEq,
|
||||
{
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.as_result_of_refs() == other.as_result_of_refs()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, E> Clone for RocResult<T, E>
|
||||
where
|
||||
T: Clone,
|
||||
E: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
match self.as_result_of_refs() {
|
||||
Ok(payload) => RocResult::ok(ManuallyDrop::into_inner(payload.clone())),
|
||||
Err(payload) => RocResult::err(ManuallyDrop::into_inner(payload.clone())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, E> RocResult<T, E> {
|
||||
pub fn ok(payload: T) -> Self {
|
||||
Self {
|
||||
|
@ -804,6 +840,17 @@ impl<T, E> RocResult<T, E> {
|
|||
|
||||
unsafe { value.assume_init() }
|
||||
}
|
||||
|
||||
fn as_result_of_refs(&self) -> Result<&ManuallyDrop<T>, &ManuallyDrop<E>> {
|
||||
use RocResultTag::*;
|
||||
|
||||
unsafe {
|
||||
match self.tag {
|
||||
RocOk => Ok(&self.payload.ok),
|
||||
RocErr => Err(&self.payload.err),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, E> From<RocResult<T, E>> for Result<T, E> {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue