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 autogen_alpn::{AlpnType, ALPNS_LIST};



pub mod autogen_alpn;

/// A structure which describes the ALPNs.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AlpnProtocolId
{
    pub ident: AlpnType,
    pub ident_seq: &'static [u8],
    pub ident_str: &'static str,
    pub descr: &'static str,
}

impl AlpnProtocolId
{
    /// Returns the static reference to Alpn protocol ID record.
    pub 
    fn get_by_alpn_type(altp: AlpnType) -> &'static AlpnProtocolId
    {
        return &ALPNS_LIST[altp as usize];
    }

    /// Returns the statuc reference to Apln protocol ID record by the string identification
    /// i.e http/1.0
    pub 
    fn get_by_ident_str(ident: &str) -> Option<&'static AlpnProtocolId>
    {
        let idx = ALPNS_LIST.binary_search_by_key(&ident,|v| v.ident_str).ok()?;

        return Some(&ALPNS_LIST[idx]);
    }

    /// Returns the statuc reference to Apln protocol ID record by the string identification
    /// i.e b"\x68\x32\x63" -> h2c
    pub 
    fn get_by_ident_seq(ident: &[u8]) -> Option<&'static AlpnProtocolId>
    {
        let idx = ALPNS_LIST.binary_search_by_key(&ident,|v| v.ident_seq).ok()?;

        return Some(&ALPNS_LIST[idx]);
    }
}

#[cfg(test)]
mod tests
{
    use crate::protocol::autogen::autogen_alpn::AlpnType;

    use super::AlpnProtocolId;

    #[test]
    fn test_get_by_ident_str()
    {
        let a1 = AlpnProtocolId::get_by_ident_str("h2c");
        assert_eq!(Some(AlpnProtocolId::get_by_alpn_type(AlpnType::Http2OverTcp)), a1);

        let a1 = AlpnProtocolId::get_by_ident_str("http/1.0");
        assert_eq!(Some(AlpnProtocolId::get_by_alpn_type(AlpnType::Http10)), a1);

        let a1 = AlpnProtocolId::get_by_ident_str("https/1.0");
        assert_eq!(None, a1);

        let a1 = AlpnProtocolId::get_by_ident_seq(b"\x68\x32\x63");
        assert_eq!(Some(AlpnProtocolId::get_by_alpn_type(AlpnType::Http2OverTcp)), a1);

        let a1 = AlpnProtocolId::get_by_ident_seq(b"\x68\x74\x74\x70\x2f\x31\x2e\x30");
        assert_eq!(Some(AlpnProtocolId::get_by_alpn_type(AlpnType::Http10)), a1);
    }
}