pulsar_network/
message.rs

1use astro_format::arrays;
2use crate::{ Message, Context };
3use std::error::Error;
4
5impl Context {
6
7    pub fn from_bytes(byte: &[u8]) -> Result<Self, Box<dyn Error>> {
8        match byte[0] {
9            1_u8 => Ok(Context::Block),
10            2_u8 => Ok(Context::BlockRequest),
11            3_u8 => Ok(Context::CancelTransaction),
12            4_u8 => Ok(Context::Transaction),
13            _ => Err("Context from byte error!")?
14        }
15    }
16
17    pub fn to_bytes(&self) -> Vec<u8> {
18        match self {
19            Context::Block => vec![1_u8],
20            Context::BlockRequest => vec![2_u8],
21            Context::CancelTransaction => vec![3_u8],
22            Context::Transaction => vec![4_u8],
23        }
24    }
25
26}
27
28impl Message {
29
30    pub fn new(context: Context, body: &[u8]) -> Self {
31
32        Message {
33            body: body.to_vec(),
34            context: context,
35        }
36
37    }
38
39    pub fn from_bytes(bytes: &[u8]) -> Result<Self, Box<dyn Error>> {
40
41        let details = arrays::decode(bytes)?;
42        
43        if details.len() == 2 {
44
45            match Context::from_bytes(details[1]) {
46
47                Ok(c) => {
48                    
49                    Ok(Message {
50                        body: details[0].to_vec(),
51                        context: c
52                    })
53                },
54                
55                Err(e) => Err(e)?
56            }            
57        } else {
58            Err("Message from bytes error!")?
59        }
60    }
61
62    pub fn to_bytes(&self) -> Vec<u8> {
63
64        arrays::encode(&[
65            &self.body,
66            &self.context.to_bytes(),
67        ])
68        
69    }
70
71}