cu29_traits/
lib.rs

1use bincode::{Decode as dDecode, Encode, Encode as dEncode};
2use serde::{Deserialize, Serialize};
3use std::error::Error;
4use std::fmt::{Debug, Display, Formatter};
5
6/// Common copper Error type.
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct CuError {
9    message: String,
10    cause: Option<String>,
11}
12
13impl Display for CuError {
14    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
15        let context_str = match &self.cause {
16            Some(c) => c.to_string(),
17            None => "None".to_string(),
18        };
19        write!(f, "{}\n   context:{}", self.message, context_str)?;
20        Ok(())
21    }
22}
23
24impl Error for CuError {}
25
26impl From<&str> for CuError {
27    fn from(s: &str) -> CuError {
28        CuError {
29            message: s.to_string(),
30            cause: None,
31        }
32    }
33}
34
35impl From<String> for CuError {
36    fn from(s: String) -> CuError {
37        CuError {
38            message: s,
39            cause: None,
40        }
41    }
42}
43
44impl CuError {
45    pub fn new_with_cause(message: &str, cause: impl Error) -> CuError {
46        CuError {
47            message: message.to_string(),
48            cause: Some(cause.to_string()),
49        }
50    }
51
52    pub fn add_cause(mut self, context: &str) -> CuError {
53        self.cause = Some(context.into());
54        self
55    }
56}
57
58// Generic Result type for copper.
59pub type CuResult<T> = Result<T, CuError>;
60
61/// Defines a basic write, append only stream trait to be able to log or send serializable objects.
62pub trait WriteStream<E: Encode>: Sync + Send + Debug {
63    fn log(&mut self, obj: &E) -> CuResult<()>;
64    fn flush(&mut self) -> CuResult<()> {
65        Ok(())
66    }
67}
68
69/// Defines the types of what can be logged in the unified logger.
70#[derive(dEncode, dDecode, Copy, Clone, Debug, PartialEq)]
71pub enum UnifiedLogType {
72    Empty,             // Dummy default used as a debug marker
73    StructuredLogLine, // This is for the structured logs (ie. debug! etc..)
74    CopperList,        // This is the actual data log storing activities between tasks.
75    LastEntry,         // This is a special entry that is used to signal the end of the log.
76}
77
78/// A CopperListTuple needs to be encodable, decodable and fixed size in memory.
79pub trait CopperListTuple: bincode::Encode + bincode::Decode<()> + Debug {} // Decode is Sized
80
81// Also anything that follows this contract can be a payload (blanket implementation)
82impl<T> CopperListTuple for T where T: bincode::Encode + bincode::Decode<()> + Debug {} // Decode is Sized