haprox_rs/
common.rs

1use std::io::Error;
2
3use crate::{error::{HaProxErr, HaProxRes}, map_error, return_error};
4
5pub(crate)
6fn is_printable_utf8(u: &str, err_lbl: &str) -> HaProxRes<()>
7{
8    for p in u.chars()
9    {
10        // any character that can be printed except control chars
11        if p.is_control() == true || p.is_ascii_whitespace() == true || p.is_ascii_control() == true 
12        {
13            return_error!(ArgumentEinval,
14                "non-printable characters found in: '{}' for '{}'", sanitize_str_unicode(u), err_lbl);
15        }
16    }
17
18    return Ok(());
19}
20
21pub(crate)
22fn is_printable_ascii(u: &str, err_lbl: &str) -> HaProxRes<()>
23{
24    for p in u.chars()
25    {
26        // any character that can be printed except control chars
27        if p.is_control() == true || p.is_ascii_whitespace() == true || p.is_ascii_control() == true ||
28            p.is_ascii() == false
29        {
30            return_error!(ArgumentEinval,
31                "non-printable characters found in: '{}' for '{}'", sanitize_str_unicode(u), err_lbl);
32        }
33    }
34
35    return Ok(());
36}
37
38pub(crate)
39fn sanitize_str_unicode(st: &str) -> String
40{
41    let mut out = String::with_capacity(st.len());
42
43    for c in st.chars()
44    {
45        if c.is_alphanumeric() == true ||
46            c.is_ascii_punctuation() == true ||
47            c == ' '
48        {
49            out.push(c);
50        }
51        else
52        {
53            let mut buf = [0_u8; 4];
54            c.encode_utf8(&mut buf);
55
56            let formatted: String = 
57                buf[0..c.len_utf8()].into_iter()
58                    .map(|c| format!("\\x{:02x}", c))
59                    .collect();
60
61            out.push_str(&formatted);
62        }
63    }
64
65    return out;
66}
67
68pub
69fn map_io_err(err: Error) -> HaProxErr
70{
71    return map_error!(IoError, "{}", err)
72}