flesh out api for RocResult

This commit is contained in:
Folkert 2021-12-27 20:01:19 +01:00
parent c2934a509a
commit 007d777865
2 changed files with 84 additions and 0 deletions

View file

@ -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>
);
}

View file

@ -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> {