haprox-rs 0.2.0

A HaProxy protocol parser.
Documentation
use std::io::Error;

use crate::{error::{HaProxErr, HaProxRes}, map_error, return_error};

pub(crate)
fn is_printable_utf8(u: &str, err_lbl: &str) -> HaProxRes<()>
{
    for p in u.chars()
    {
        // any character that can be printed except control chars
        if p.is_control() == true || p.is_ascii_whitespace() == true || p.is_ascii_control() == true 
        {
            return_error!(ArgumentEinval,
                "non-printable characters found in: '{}' for '{}'", sanitize_str_unicode(u), err_lbl);
        }
    }

    return Ok(());
}

pub(crate)
fn is_printable_ascii(u: &str, err_lbl: &str) -> HaProxRes<()>
{
    for p in u.chars()
    {
        // any character that can be printed except control chars
        if p.is_control() == true || p.is_ascii_whitespace() == true || p.is_ascii_control() == true ||
            p.is_ascii() == false
        {
            return_error!(ArgumentEinval,
                "non-printable characters found in: '{}' for '{}'", sanitize_str_unicode(u), err_lbl);
        }
    }

    return Ok(());
}

pub(crate)
fn sanitize_str_unicode(st: &str) -> String
{
    let mut out = String::with_capacity(st.len());

    for c in st.chars()
    {
        if c.is_alphanumeric() == true ||
            c.is_ascii_punctuation() == true ||
            c == ' '
        {
            out.push(c);
        }
        else
        {
            let mut buf = [0_u8; 4];
            c.encode_utf8(&mut buf);

            let formatted: String = 
                buf[0..c.len_utf8()].into_iter()
                    .map(|c| format!("\\x{:02x}", c))
                    .collect();

            out.push_str(&formatted);
        }
    }

    return out;
}

pub
fn map_io_err(err: Error) -> HaProxErr
{
    return map_error!(IoError, "{}", err)
}