candid/types/
result.rs

1use crate::types::{CandidType, Compound, Field, Label, Serializer, Type, TypeInner};
2use serde::{Deserialize, Serialize};
3
4#[allow(non_camel_case_types)]
5#[derive(Deserialize, Debug, Clone, Serialize)]
6pub enum MotokoResult<T, E> {
7    ok(T),
8    err(E),
9}
10impl<T, E> MotokoResult<T, E> {
11    pub fn into_result(self) -> Result<T, E> {
12        match self {
13            MotokoResult::ok(v) => Ok(v),
14            MotokoResult::err(e) => Err(e),
15        }
16    }
17}
18impl<T, E> From<Result<T, E>> for MotokoResult<T, E> {
19    fn from(r: Result<T, E>) -> Self {
20        match r {
21            Ok(v) => MotokoResult::ok(v),
22            Err(e) => MotokoResult::err(e),
23        }
24    }
25}
26impl<T, E> CandidType for MotokoResult<T, E>
27where
28    T: CandidType,
29    E: CandidType,
30{
31    fn _ty() -> Type {
32        TypeInner::Variant(vec![
33            // Make sure the field id is sorted by idl_hash
34            Field {
35                id: Label::Named("ok".to_owned()).into(),
36                ty: T::ty(),
37            },
38            Field {
39                id: Label::Named("err".to_owned()).into(),
40                ty: E::ty(),
41            },
42        ])
43        .into()
44    }
45    fn idl_serialize<S>(&self, serializer: S) -> Result<(), S::Error>
46    where
47        S: Serializer,
48    {
49        match *self {
50            MotokoResult::ok(ref v) => {
51                let mut ser = serializer.serialize_variant(0)?;
52                Compound::serialize_element(&mut ser, v)
53            }
54            MotokoResult::err(ref e) => {
55                let mut ser = serializer.serialize_variant(1)?;
56                Compound::serialize_element(&mut ser, e)
57            }
58        }
59    }
60}