haystack_types/
common.rs

1use nom::multi::many0;
2use nom::bytes::complete::take_while1;
3use nom::character::complete::alphanumeric1;
4use nom::combinator::recognize;
5use nom::bytes::complete::tag;
6use nom::branch::alt;
7use num::Float;
8use core::str::FromStr;
9use std::fmt::{self,Display,Formatter};
10use crate::{h_val::HVal, io::HBox, NumTrait};
11use nom::{IResult, Parser};
12
13#[derive(Debug,PartialEq)]
14pub enum Txt<'a> {
15    Const(&'a str),
16    Owned(String)
17}
18
19impl <'a>Txt<'a> {
20    pub fn chars(&self) -> std::str::Chars {
21        match self {
22            Txt::Const(s) => s.chars(),
23            Txt::Owned(s) => s.chars(),
24        }
25    }
26
27    pub fn len(&self) -> usize {
28        match self {
29            Txt::Const(s) => s.len(),
30            Txt::Owned(s) => s.len(),
31        }
32    }
33
34    pub fn find(&self, pat: &str) -> Option<usize> {
35        match self {
36            Txt::Const(s) => s.find(pat),
37            Txt::Owned(s) => s.find(pat),
38        }
39    }
40}
41
42impl <'a>Display for Txt<'a> {
43    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
44        match self {
45            Txt::Const(s) => write!(f, "{}", s),
46            Txt::Owned(s) => write!(f, "{}", s),
47        }
48    }
49}
50
51pub fn escape_str(c: char, buf: &mut String) -> fmt::Result {
52    if c < ' ' || c == '"' || c == '\\' {
53        buf.push('\\');
54        match c {
55            '\n' => buf.push('n'),
56            '\r' => buf.push('r'),
57            '\t' => buf.push('t'),
58            '"' => buf.push('"'),
59            '\\' => buf.push('\\'),
60            _ => {
61                buf.push_str("u00");
62                let tmp = std::char::from_u32(0xf).ok_or(fmt::Error)?;
63                if c < tmp { buf.push('0') }
64                buf.push_str(&format!("{:X}", c.to_digit(16).ok_or(fmt::Error)?));
65            }
66        };
67    } else {
68        buf.push(c);
69    }
70    Ok(())
71}
72
73pub fn unicode_char(ex: char) -> impl Fn(char) -> bool {
74    move |c| c >= 0x20 as char && c != '\\' && c != ex
75}
76
77pub fn id(input: &str) -> IResult<&str,&str> {
78    let lower = |c: char| { c>='a' && c<='z' };
79    recognize(((
80        take_while1(lower),
81        many0(alt((alphanumeric1,tag("_"))))
82    ))).parse(input)
83}
84
85pub trait ZincWriter<'a,T: NumTrait + 'a> {
86    fn to_zinc(&self, buf: &mut String) -> fmt::Result;
87}
88
89pub trait ZincReader<'a,T: NumTrait + 'a> {
90    fn parse<'b>(buf: &'b str) -> IResult<&'b str, HBox<'a,T>> where 'a: 'b;
91}
92
93pub trait JsonWriter<'a,T: NumTrait + 'a> {
94    fn to_json(&self, buf: &mut String) -> fmt::Result;
95}
96
97pub trait TrioWriter<'a,T: NumTrait + 'a> {
98    fn to_trio(&self, buf: &mut String) -> fmt::Result;
99}