1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
//!  The output `Result` of an [Instruction], tagged as a `success` (`Ok`) or
//!  `failure` (`Error`), or returned/inlined directly.
//!
//!  [Instruction]: crate::task::Instruction

use crate::{Error, Unit};
#[cfg(feature = "diesel")]
use diesel::{
    backend::Backend,
    deserialize::{self, FromSql, FromSqlRow},
    expression::AsExpression,
    serialize::{self, IsNull, Output, ToSql},
    sql_types::Binary,
    sqlite::Sqlite,
};
use libipld::Ipld;
#[cfg(feature = "diesel")]
use libipld::{cbor::DagCborCodec, prelude::Codec};
use serde::{Deserialize, Serialize};

const OK: &str = "ok";
const ERR: &str = "error";
const JUST: &str = "just";

/// Resultant output of an executed [Instruction].
///
/// [Instruction]: super::Instruction
#[cfg(feature = "diesel")]
#[cfg_attr(docsrs, doc(cfg(feature = "diesel")))]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, AsExpression, FromSqlRow)]
#[diesel(sql_type = Binary)]
pub enum Result<T> {
    /// `Ok` branch.
    Ok(T),
    /// `Error` branch.
    Error(T),
    /// `Just` branch, meaning `just the value`. Used for
    /// not incorporating unwrapped ok/error into arg/param, where a
    /// result may show up directly.
    Just(T),
}

/// Output of an executed [Instruction].
///
/// [Instruction]: super::Instruction
#[cfg(not(feature = "diesel"))]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Result<T> {
    /// `Ok` branch.
    Ok(T),
    /// `Error` branch.
    Error(T),
    /// `Just` branch, meaning `just the value`. Used for
    /// not incorporating unwrapped ok/error into arg/param, where a
    /// result may show up directly.
    Just(T),
}

impl<T> Result<T> {
    /// Owned, inner result of a [Task] invocation.
    ///
    /// [Task]: super::Task
    pub fn into_inner(self) -> T {
        match self {
            Result::Ok(inner) => inner,
            Result::Error(inner) => inner,
            Result::Just(inner) => inner,
        }
    }

    /// Referenced, inner result of a [Task] invocation.
    ///
    /// [Task]: super::Task
    pub fn inner(&self) -> &T {
        match self {
            Result::Ok(inner) => inner,
            Result::Error(inner) => inner,
            Result::Just(inner) => inner,
        }
    }
}

impl<T> From<Result<T>> for Ipld
where
    Ipld: From<T>,
{
    fn from(result: Result<T>) -> Self {
        match result {
            Result::Ok(res) => Ipld::List(vec![OK.into(), res.into()]),
            Result::Error(res) => Ipld::List(vec![ERR.into(), res.into()]),
            Result::Just(res) => Ipld::List(vec![JUST.into(), res.into()]),
        }
    }
}

impl<T> TryFrom<Ipld> for Result<T>
where
    T: From<Ipld>,
{
    type Error = Error<Unit>;

    fn try_from(ipld: Ipld) -> std::result::Result<Self, Error<Unit>> {
        if let Ipld::List(v) = ipld {
            match &v[..] {
                [Ipld::String(result), res] if result == OK => {
                    Ok(Result::Ok(res.to_owned().into()))
                }
                [Ipld::String(result), res] if result == ERR => {
                    Ok(Result::Error(res.to_owned().into()))
                }
                [Ipld::String(result), res] if result == JUST => {
                    Ok(Result::Just(res.to_owned().into()))
                }
                other_ipld => Err(Error::unexpected_ipld(other_ipld.to_owned().into())),
            }
        } else {
            Err(Error::not_an_ipld_list())
        }
    }
}

impl<T> TryFrom<&Ipld> for Result<T>
where
    T: From<Ipld>,
{
    type Error = Error<Unit>;

    fn try_from(ipld: &Ipld) -> std::result::Result<Self, Error<Unit>> {
        TryFrom::try_from(ipld.to_owned())
    }
}

/// Diesel, [Sqlite] [ToSql] implementation.
#[cfg(feature = "diesel")]
#[cfg_attr(docsrs, doc(cfg(feature = "diesel")))]
impl ToSql<Binary, Sqlite> for Result<Ipld>
where
    [u8]: ToSql<Binary, Sqlite>,
{
    fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Sqlite>) -> serialize::Result {
        let ipld = Ipld::from(self.to_owned());
        out.set_value(DagCborCodec.encode(&ipld)?);
        Ok(IsNull::No)
    }
}

/// Diesel, [Sqlite] [FromSql] implementation.
#[cfg(feature = "diesel")]
#[cfg_attr(docsrs, doc(cfg(feature = "diesel")))]
impl<DB> FromSql<Binary, DB> for Result<Ipld>
where
    DB: Backend,
    *const [u8]: FromSql<Binary, DB>,
{
    fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
        let raw_bytes = <*const [u8] as FromSql<Binary, DB>>::from_sql(bytes)?;
        let raw_bytes: &[u8] = unsafe { &*raw_bytes };
        let decoded: Ipld = DagCborCodec.decode(raw_bytes)?;
        Ok(Result::try_from(decoded)?)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn ipld_roundtrip() {
        let res1 = Result::Error(Ipld::String("bad stuff".to_string()));
        let res2 = Result::Ok(Ipld::String("ok stuff".to_string()));
        let res3 = Result::Just(Ipld::String("just the right stuff".to_string()));
        let ipld1 = Ipld::from(res1.clone());
        let ipld2 = Ipld::from(res2.clone());
        let ipld3 = Ipld::from(res3.clone());

        assert_eq!(ipld1, Ipld::List(vec!["error".into(), "bad stuff".into()]));
        assert_eq!(ipld2, Ipld::List(vec!["ok".into(), "ok stuff".into()]));
        assert_eq!(
            ipld3,
            Ipld::List(vec!["just".into(), "just the right stuff".into()])
        );

        assert_eq!(res1, ipld1.try_into().unwrap());
        assert_eq!(res2, ipld2.try_into().unwrap());
        assert_eq!(res3, ipld3.try_into().unwrap());
    }

    #[test]
    fn ser_de() {
        let res1 = Result::Error(Ipld::String("bad stuff".to_string()));
        let res2 = Result::Ok(Ipld::String("ok stuff".to_string()));
        let res3 = Result::Just(Ipld::String("just the right stuff".to_string()));

        let ser = serde_json::to_string(&res1).unwrap();
        let de = serde_json::from_str(&ser).unwrap();
        assert_eq!(res1, de);

        let ser = serde_json::to_string(&res2).unwrap();
        let de = serde_json::from_str(&ser).unwrap();
        assert_eq!(res2, de);

        let ser = serde_json::to_string(&res3).unwrap();
        let de = serde_json::from_str(&ser).unwrap();
        assert_eq!(res3, de);
    }
}