avm_interface/
call_service_result.rs

1/*
2 * Copyright 2021 Fluence Labs Limited
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use super::JValue;
18
19use serde::Deserialize;
20use serde::Serialize;
21use std::collections::HashMap;
22
23pub type CallResults = HashMap<u32, CallServiceResult>;
24pub const CALL_SERVICE_SUCCESS: i32 = 0;
25
26/// Represents an executed host function result.
27#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
28pub struct CallServiceResult {
29    /// A error code service or builtin returned, where CALL_SERVICE_SUCCESS represents success.
30    pub ret_code: i32,
31
32    /// Resulted JValue returned by a service string.
33    pub result: JValue,
34}
35
36impl CallServiceResult {
37    pub fn ok(result: JValue) -> Self {
38        Self {
39            ret_code: CALL_SERVICE_SUCCESS,
40            result,
41        }
42    }
43
44    pub fn err(err_code: i32, result: JValue) -> Self {
45        Self {
46            ret_code: err_code,
47            result,
48        }
49    }
50
51    pub fn into_raw(self) -> air_interpreter_interface::CallServiceResult {
52        let CallServiceResult { ret_code, result } = self;
53
54        air_interpreter_interface::CallServiceResult {
55            ret_code,
56            // TODO serializer
57            result: result.to_string(),
58        }
59    }
60}
61
62#[tracing::instrument(level = "debug", skip(call_results))]
63pub fn into_raw_result(call_results: CallResults) -> air_interpreter_interface::CallResults {
64    call_results
65        .into_iter()
66        .map(|(call_id, call_result)| (call_id.to_string(), call_result.into_raw()))
67        .collect::<_>()
68}
69
70use std::fmt;
71
72impl fmt::Display for CallServiceResult {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        write!(f, "ret_code: {}, result: '{}'", self.ret_code, self.result)
75    }
76}