holochain_integrity_types/zome_io.rs
1use holochain_serialized_bytes::prelude::*;
2
3// Every externed function that the zome developer exposes to holochain returns `ExternIO`.
4// The zome developer can expose callbacks in a "sparse" way based on names and the functions
5// can take different input (e.g. validation vs. hooks like init, etc.).
6// All we can say is that some SerializedBytes are being received and returned.
7// In the case of ZomeExtern functions exposed to a client, the data input/output is entirely
8// arbitrary so we can't say anything at all. In this case the happ developer must BYO
9// deserialization context to match the client, either directly or via. the HDK.
10// Note though, that _unlike_ zome externs, the host _does_ know exactly the guest should be
11// returning for callbacks, it's just that the unpacking of the return happens in two steps:
12// - first the sparse callback is triggered with SB input/output
13// - then the guest inflates the expected input or the host the expected output based on the
14// callback flavour
15
16#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq, Eq)]
17#[serde(transparent)]
18#[repr(transparent)]
19pub struct ExternIO(#[serde(with = "serde_bytes")] pub Vec<u8>);
20
21impl ExternIO {
22 pub fn encode<I>(input: I) -> Result<Self, SerializedBytesError>
23 where
24 I: serde::Serialize + std::fmt::Debug,
25 {
26 Ok(Self(holochain_serialized_bytes::encode(&input)?))
27 }
28 pub fn decode<O>(&self) -> Result<O, SerializedBytesError>
29 where
30 O: serde::de::DeserializeOwned + std::fmt::Debug,
31 {
32 holochain_serialized_bytes::decode(&self.0)
33 }
34
35 pub fn into_vec(self) -> Vec<u8> {
36 self.into()
37 }
38 pub fn as_bytes(&self) -> &[u8] {
39 self.as_ref()
40 }
41}
42
43impl AsRef<[u8]> for ExternIO {
44 fn as_ref(&self) -> &[u8] {
45 &self.0
46 }
47}
48
49impl From<Vec<u8>> for ExternIO {
50 fn from(v: Vec<u8>) -> Self {
51 Self(v)
52 }
53}
54
55impl From<ExternIO> for Vec<u8> {
56 fn from(extern_io: ExternIO) -> Self {
57 extern_io.0
58 }
59}