Skip to content

Commit

Permalink
parser: Use a lookup table for Delimiter::from_byte. (#358)
Browse files Browse the repository at this point in the history
* parser: Use a lookup table for Delimiter::from_byte.

It's faster.

* tests: Add a benchmark for Delimiters::from_byte
  • Loading branch information
emilio committed Sep 11, 2023
1 parent c97ba60 commit 1ccc577
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 10 deletions.
24 changes: 15 additions & 9 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -335,16 +335,22 @@ impl Delimiters {
}

#[inline]
fn from_byte(byte: Option<u8>) -> Delimiters {
pub(crate) fn from_byte(byte: Option<u8>) -> Delimiters {
const TABLE: [Delimiters; 256] = {
let mut table = [Delimiter::None; 256];
table[b';' as usize] = Delimiter::Semicolon;
table[b'!' as usize] = Delimiter::Bang;
table[b',' as usize] = Delimiter::Comma;
table[b'{' as usize] = Delimiter::CurlyBracketBlock;
table[b'}' as usize] = ClosingDelimiter::CloseCurlyBracket;
table[b']' as usize] = ClosingDelimiter::CloseSquareBracket;
table[b')' as usize] = ClosingDelimiter::CloseParenthesis;
table
};

match byte {
Some(b';') => Delimiter::Semicolon,
Some(b'!') => Delimiter::Bang,
Some(b',') => Delimiter::Comma,
Some(b'{') => Delimiter::CurlyBracketBlock,
Some(b'}') => ClosingDelimiter::CloseCurlyBracket,
Some(b']') => ClosingDelimiter::CloseSquareBracket,
Some(b')') => ClosingDelimiter::CloseParenthesis,
_ => Delimiter::None,
None => Delimiter::None,
Some(b) => TABLE[b as usize],
}
}
}
Expand Down
14 changes: 13 additions & 1 deletion src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use encoding_rs;
use serde_json::{self, json, Map, Value};

use crate::color::{parse_color_with, FromParsedColor};
use crate::{ColorParser, PredefinedColorSpace};
use crate::{ColorParser, PredefinedColorSpace, Delimiters};

#[cfg(feature = "bench")]
use self::test::Bencher;
Expand Down Expand Up @@ -922,6 +922,18 @@ impl<'a> ToJson for CowRcStr<'a> {
}
}

#[bench]
#[cfg(feature = "bench")]
fn delimiter_from_byte(b: &mut Bencher) {
b.iter(|| {
for _ in 0..1000 {
for i in 0..256 {
std::hint::black_box(Delimiters::from_byte(Some(i as u8)));
}
}
})
}

#[cfg(feature = "bench")]
const BACKGROUND_IMAGE: &'static str = include_str!("big-data-url.css");

Expand Down

0 comments on commit 1ccc577

Please sign in to comment.