asciicker_rs/y6/
utils.rs

1use std::error::Error;
2use std::fmt::{Debug, Display, Formatter};
3
4/// Error used to implement [`TryInto`] traits for packets.
5#[derive(Debug, Clone)]
6pub enum PacketParseError {
7    /// This error variant is raised if length of the packet in bytes
8    /// doesn't match the appropriate constant length.
9    SizeMismatch(usize, usize),
10    /// This error variant is raised if C-style string doesn't have terminating null byte
11    NoNullByte(Vec<u8>),
12}
13
14impl Display for PacketParseError {
15    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
16        match self {
17            PacketParseError::SizeMismatch(expected, got) => {
18                write!(
19                    f,
20                    "Size mismatch during parsing: expected: {}, got: {}",
21                    expected, got
22                )
23            }
24            PacketParseError::NoNullByte(bytes) => {
25                write!(
26                    f,
27                    "No null byte found while parsing following bytes: {:?}",
28                    bytes
29                )
30            }
31        }
32    }
33}
34
35impl Error for PacketParseError {}
36
37/// Generic runtime error for all of the high level computation of this library.
38#[derive(Debug, Clone)]
39pub struct RuntimeError {
40    /// String describing what error had happened
41    pub what: String,
42}
43
44impl RuntimeError {
45    /// Create error from [`String`]
46    pub fn from_string(s: String) -> Self {
47        Self { what: s }
48    }
49}
50
51impl Display for RuntimeError {
52    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
53        writeln!(f, "Runtime error: {}", self.what)
54    }
55}
56
57impl Error for RuntimeError {}
58
59/// Something like strlen from C
60#[doc(hidden)]
61pub(crate) fn first_nul(bytes: &[u8]) -> Option<usize> {
62    let mut size = 0;
63    for byte in bytes {
64        if *byte == b'\0' {
65            return Some(size);
66        }
67        size += 1;
68    }
69    None
70}