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
use serde::{Deserialize, Serialize};
use ex3_error::OtherError;
use ex3_serde::{bincode, cbor};
use crate::{AssetAmount, AssetId};
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct Withdraw {
pub asset: AssetId,
pub amount: AssetAmount,
}
impl Withdraw {
pub fn encode(&self) -> Vec<u8> {
bincode::serialize(&(&self.asset, &self.amount)).unwrap()
}
pub fn decode(data: &[u8]) -> Result<Self, OtherError> {
let (asset, amount) = bincode::deserialize(data)
.map_err(|e| OtherError::new(format!("Failed to deserialize Withdraw: {}", e)))?;
Ok(Self { asset, amount })
}
pub fn cbor_encode(&self) -> Vec<u8> {
cbor::serialize(&(&self.asset, &self.amount)).unwrap()
}
pub fn cbor_decode(data: &[u8]) -> Result<Self, OtherError> {
let (asset, amount) = cbor::deserialize(data).unwrap();
Ok(Self { asset, amount })
}
}
impl TryFrom<&[u8]> for Withdraw {
type Error = OtherError;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
match Withdraw::cbor_decode(value) {
Ok(withdraw) => Ok(withdraw),
Err(_) => match Withdraw::decode(value) {
Ok(withdraw) => Ok(withdraw),
Err(e) => Err(e),
},
}
}
}