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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A custom error enum lets each failure carry the exact context a caller needs to report it.
- 2Splitting a grammar into small parts — comma, slash, dash — turns a messy string into composable cases.
- 3Collecting into a BTreeSet deduplicates and sorts overlapping ranges for free.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/parsing-a-cron-field-in-rust-explained-rust-e286/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.