rust 48 lines · 7 steps

Parsing a cron field in Rust

A single cron field like "*/15" or "1-5" expands into a sorted set of valid values, with typed errors for every failure mode.

Explained by highlit
1use std::collections::BTreeSet;
2 
3#[derive(Debug)]
4pub enum FieldError {
5 NotANumber(String),
6 OutOfRange(u8),
7 BadRange(u8, u8),
8 EmptyField,
9}
10 
11pub fn parse_field(field: &str, min: u8, max: u8) -> Result<BTreeSet<u8>, FieldError> {
12 if field.is_empty() {
13 return Err(FieldError::EmptyField);
14 }
15 
16 let mut values = BTreeSet::new();
17 
18 for part in field.split(',') {
19 let (spec, step) = match part.split_once('/') {
20 Some((s, st)) => (s, parse_num(st)?),
21 None => (part, 1),
22 };
23 
24 let (lo, hi) = if spec == "*" {
25 (min, max)
26 } else if let Some((start, end)) = spec.split_once('-') {
27 (parse_num(start)?, parse_num(end)?)
28 } else {
29 let n = parse_num(spec)?;
30 (n, n)
31 };
32 
33 if lo < min || hi > max {
34 return Err(FieldError::OutOfRange(if lo < min { lo } else { hi }));
35 }
36 if lo > hi {
37 return Err(FieldError::BadRange(lo, hi));
38 }
39 
40 values.extend((lo..=hi).step_by(step.max(1) as usize));
41 }
42 
43 Ok(values)
44}
45 
46fn parse_num(s: &str) -> Result<u8, FieldError> {
47 s.parse().map_err(|_| FieldError::NotANumber(s.to_string()))
48}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A custom error enum lets each failure carry the exact context a caller needs to report it.
  2. 2Splitting a grammar into small parts — comma, slash, dash — turns a messy string into composable cases.
  3. 3Collecting into a BTreeSet deduplicates and sorts overlapping ranges for free.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Parsing a cron field in Rust — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code