haprox-rs 0.2.0

A HaProxy protocol parser.
Documentation
/*-
 * haprox-rs - a HaProxy protocol parser.
 * 
 * Copyright 2025 Aleksandr Morozov
 * The scram-rs crate can be redistributed and/or modified
 * under the terms of either of the following licenses:
 *
 *   1. the Mozilla Public License Version 2.0 (the “MPL”) OR
 *                     
 *   2. EUROPEAN UNION PUBLIC LICENCE v. 1.2 EUPL © the European Union 2007, 2016
 */

use std::fmt;

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum HaProxErrType
{
    /// Argument is invalid.
    ArgumentEinval,

    /// Input/Output error.
    IoError,

    /// Any error related to reading data from packet and 
    /// producing error.
    MalformedData,

    /// The protocol version is not supported.
    ProtocolNotSuported,

    /// The banner of the packet is unknown.
    IncorrectBanner,

    /// Unexpected EOF while reading.
    ProtocolMsgIncomplete,

    /// Received unknown data.
    ProtocolUnknownData
}

impl fmt::Display for HaProxErrType
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        match self
        {
            HaProxErrType::ArgumentEinval => 
                write!(f, "EINVAL"),
            HaProxErrType::IoError => 
                write!(f, "IOERROR"),
            HaProxErrType::MalformedData => 
                write!(f, "MALFORMED_DATA"),
            HaProxErrType::ProtocolNotSuported => 
                write!(f, "PROTO_NOT_SUPPORTED"),
            HaProxErrType::IncorrectBanner =>
                write!(f, "INCORRECT_BANNER"),
            HaProxErrType::ProtocolMsgIncomplete => 
                write!(f, "MESSAGE_INCOMPLETE"),
            HaProxErrType::ProtocolUnknownData => 
                write!(f, "UNKNOWN_DATA"),
        }
    }
}

/// Error description.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HaProxErr
{
    /// Error type
    err_type: HaProxErrType, 

    /// Error msg
    msg: String,
}

impl fmt::Display for HaProxErr
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        write!(f, "[{}]: {}", self.err_type, self.msg)
    }
}

impl HaProxErr
{
    /// Creates new error message.
    pub 
    fn new(err_type: HaProxErrType, msg: String) -> Self
    {
        return Self{ err_type: err_type, msg: msg };
    }

    /// Returns error type.
    pub 
    fn get_err_type(&self) -> HaProxErrType
    {
        return self.err_type;
    }

    /// Returns error msg.
    pub 
    fn get_msg(&self) -> &str
    {
        return &self.msg;
    }
}

pub type HaProxRes<R> = Result<R, HaProxErr>;


#[macro_export]
macro_rules! return_error 
{
    ($err_type:tt, $($arg:tt)*) => (
        return std::result::Result::Err($crate::error::HaProxErr::new($crate::error::HaProxErrType::$err_type, format!($($arg)*)))
    )
}

#[macro_export]
macro_rules! map_error 
{
    ($err_type:tt, $($arg:tt)*) => (
        $crate::error::HaProxErr::new($crate::error::HaProxErrType::$err_type, format!($($arg)*))
    )
}