From 5ee921a0e4c6dd39e9d934c47ef777a796139ce9 Mon Sep 17 00:00:00 2001 From: Jens Peters Date: Mon, 4 Dec 2023 20:36:06 +0100 Subject: [PATCH] 2023: Add performance hack for day 3 Not a good idea for all kinds of strings. --- 2023/src/day03.rs | 2 +- 2023/src/util/mod.rs | 2 ++ 2023/src/util/strings.rs | 5 +++++ 3 files changed, 8 insertions(+), 1 deletion(-) create mode 100644 2023/src/util/strings.rs diff --git a/2023/src/day03.rs b/2023/src/day03.rs index 0653b80..1c8e200 100644 --- a/2023/src/day03.rs +++ b/2023/src/day03.rs @@ -109,7 +109,7 @@ fn parse_map(input: &String) -> Vec { }) .collect::>(); - if i >= 1 && input.chars().nth(i - 1).unwrap_or('_').is_digit(10) { + if i >= 1 && char_at(input, i - 1).is_digit(10) { parts.last_mut().unwrap().number.push(c); parts .last_mut() diff --git a/2023/src/util/mod.rs b/2023/src/util/mod.rs index db858ee..fff6149 100644 --- a/2023/src/util/mod.rs +++ b/2023/src/util/mod.rs @@ -1,5 +1,7 @@ mod days; mod input; +mod strings; pub use days::DAYS; pub use input::read_input; +pub use strings::char_at; diff --git a/2023/src/util/strings.rs b/2023/src/util/strings.rs new file mode 100644 index 0000000..8e57496 --- /dev/null +++ b/2023/src/util/strings.rs @@ -0,0 +1,5 @@ +#[inline(always)] +pub fn char_at(str: &str, index: usize) -> char { + // Not a good idea for all kinds of strings. + *(&str[index..index + 1].chars().nth(0).unwrap()) +}