neure是一個(gè)簡(jiǎn)單小巧的字符串解析庫(kù), 我在開發(fā)aopt時(shí)為了優(yōu)化編譯時(shí)間而開發(fā)的替代regex的庫(kù). 目前代碼架構(gòu)非常簡(jiǎn)單, 性能上比regex更快, 和nom的速度不相上下. 設(shè)計(jì)上參考了regex.Readme有一個(gè)和regex比較的代碼,可以嘗試一下.
https://github.com/araraloren/neure
補(bǔ)充一個(gè)和nom例子比較的代碼,開啟lto=fat時(shí)性能不相上下
use neure::*; use nom::{ bytes::{tag, take_while_m_n}, combinator::map_res, sequence::tuple, IResult, }; #[derive(Debug, PartialEq)] pub struct Color { pub red: u8, pub green: u8, pub blue: u8, } fn from_hex(input: &str) -> Result{ u8::from_str_radix(input, 16) } fn is_hex_digit(c: char) -> bool { c.is_digit(16) } fn hex_primary(input: &str) -> IResult<&str, u8> { map_res(take_while_m_n(2, 2, is_hex_digit), from_hex)(input) } fn hex_color(input: &str) -> IResult<&str, Color> { let (input, _) = tag("#")(input)?; let (input, (red, green, blue)) = tuple((hex_primary, hex_primary, hex_primary))(input)?; Ok((input, Color { red, green, blue })) } fn main() -> Result<(), Box > { let mut storer = SpanStorer::new(1); let color_str = "#2F14DF"; let parser = |storer: &mut SpanStorer, str: &str| -> Result<(), neure::Error> { let pound = neure!('#'); let hex = neure!(['0' - '9' 'A' - 'F']{2}); let mut ctx = CharsCtx::default().with_str(str); ctx.reset(); ctx.try_mat(£)?; ctx.try_cap(0, storer, &hex)?; ctx.try_cap(0, storer, &hex)?; ctx.try_cap(0, storer, &hex)?; Ok(()) }; measure(100000, 100000, || { if parser(storer.reset(), color_str).is_ok() { let mut strs = storer.substrs(color_str, 0).unwrap(); assert_eq!( Color { red: u8::from_str_radix(strs.next().unwrap(), 16).unwrap(), green: u8::from_str_radix(strs.next().unwrap(), 16).unwrap(), blue: u8::from_str_radix(strs.next().unwrap(), 16).unwrap(), }, Color { red: 47, green: 20, blue: 223, } ); 1 } else { 0 } }); measure(100000, 100000, || { if hex_color("#2F14DF").unwrap() == ( "", Color { red: 47, green: 20, blue: 223, }, ) { 1 } else { 0 } }); Ok(()) } pub fn measure(n: usize, size: usize, mut f: impl FnMut() -> i32) { use std::Instant; let start = Instant::now(); let mut sum = 0; for _ in 0..n { sum += f(); } let time = start.elapsed(); println!( "Size = {size}, Cost time {} with test {} times: {} --> {}", time.as_secs_f64(), n, time.as_secs_f64() / n as f64, sum, ); }
審核編輯:湯梓紅
-
字符串
+關(guān)注
關(guān)注
1文章
585瀏覽量
20612 -
代碼
+關(guān)注
關(guān)注
30文章
4835瀏覽量
69117 -
編譯
+關(guān)注
關(guān)注
0文章
662瀏覽量
33066 -
GitHub
+關(guān)注
關(guān)注
3文章
474瀏覽量
16613
原文標(biāo)題:【大家的項(xiàng)目】nuere - 簡(jiǎn)單小巧快速的字符串解析庫(kù)
文章出處:【微信號(hào):Rust語言中文社區(qū),微信公眾號(hào):Rust語言中文社區(qū)】歡迎添加關(guān)注!文章轉(zhuǎn)載請(qǐng)注明出處。
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
字符串移位包含的問題解決方案
什么是復(fù)制字符串?Python如何復(fù)制字符串
strtok拆分字符串
![strtok拆分<b class='flag-5'>字符串</b>](https://file.elecfans.com/web1/M00/D9/4E/pIYBAF_1ac2Ac0EEAABDkS1IP1s689.png)
評(píng)論