surrealcs_kernel/messages/serialization/
header.rs

1//! Defines a simple header for serialization and deserialization of messages. Should be used for
2//! all messages sent between the client and server.
3use nanoservices_utils::errors::{NanoServiceError, NanoServiceErrorStatus};
4
5use crate::messages::serialization::traits::IntoVecBytes;
6
7// To define the size of the message.
8pub type MessageHeader = Header<usize>;
9
10/// A simple header struct to be used for serialization and deserialization of messages.
11///
12#[derive(Debug, PartialEq)]
13pub struct Header<T: Sized + IntoVecBytes + Clone> {
14	pub value: T,
15}
16
17impl<T: Sized + IntoVecBytes + Clone> Header<T> {
18	/// Converts the header into a vector of bytes.
19	///
20	/// # Returns
21	/// a vector of bytes representing the header
22	pub fn to_bytes(&self) -> Vec<u8> {
23		T::to_be_bytes(self.value.clone())
24	}
25}
26
27impl Header<usize> {
28	/// Converts a slice of bytes into a message header.
29	///
30	/// # Arguments
31	/// * `bytes`: the vector of bytes to be converted
32	///
33	/// # Returns
34	/// the message header
35	pub fn from_bytes(bytes: &[u8; 8]) -> MessageHeader {
36		MessageHeader {
37			value: usize::from_be_bytes([
38				bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
39			]),
40		}
41	}
42
43	/// Converts a vector of bytes into a message header.
44	///
45	/// # Arguments
46	/// * `bytes`: the vector of bytes to be converted
47	///
48	/// # Returns
49	/// the message header
50	pub fn from_vector_bytes(bytes: Vec<u8>) -> Result<MessageHeader, NanoServiceError> {
51		if bytes.len() != 8 {
52			return Err(NanoServiceError::new(
53				format!("Invalid byte length for meta header {}, should be 8", bytes.len()),
54				NanoServiceErrorStatus::BadRequest,
55			));
56		}
57		Ok(MessageHeader {
58			value: usize::from_be_bytes([
59				bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
60			]),
61		})
62	}
63}
64
65#[cfg(test)]
66mod tests {
67	use super::*;
68
69	#[test]
70	fn test_message_header() {
71		let header = MessageHeader {
72			value: 5,
73		};
74		let bytes = header.to_bytes();
75		assert_eq!(bytes.len(), 8);
76		let header = MessageHeader::from_bytes(&[
77			bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
78		]);
79		assert_eq!(header.value, 5);
80	}
81
82	#[test]
83	fn test_message_header_from_vector_bytes() {
84		let header = MessageHeader::from_vector_bytes(vec![0, 0, 0, 0, 0, 0, 0, 5]).unwrap();
85		assert_eq!(header.value, 5);
86	}
87
88	#[test]
89	fn test_message_header_from_vector_bytes_invalid() {
90		let header = MessageHeader::from_vector_bytes(vec![0, 0, 0, 0, 0, 0, 0, 5, 6]);
91		assert!(header.is_err());
92	}
93}