CNAME / Redirect Chain Resolver (Rust)
Topics: graphs, chain walk, loop detection
Problem
A name server (or an HTTP redirect follower) chases a CNAME/Location chain: each name points at
the next until one has no further record — the canonical target. Walk the chain from a start
name to that target, but refuse to chase forever.
pub enum ResolveError { Loop(Vec<String>), TooLong(usize) }
pub fn resolve(cnames: &BTreeMap<String, String>, start: &str, max_hops: usize)
-> Result<String, ResolveError>;
cnames maps a name to the single name it redirects to. A name with no entry is the
canonical target; resolving it returns itself (zero hops).
- Each hop follows one link. Return
Err(TooLong(max_hops)) if resolving would follow more
than max_hops links.
- Return
Err(Loop(chain)) if the chain revisits a name (including a name that points to
itself); chain is the names visited, in order, before the repeat.
{www→example.com, example.com→lb-01}; start=www, max_hops=10 → "lb-01"
{a→b, b→a}; start=a → Err(Loop(["a","b"]))
{a→b, b→c, c→d}; start=a, max_hops=2 → Err(TooLong(2))
It's a single walk down a linked chain: keep a seen set to catch loops and a hop counter to cap
the length.
Grading
Your solution.rs is compiled together with a trusted tests.rs (which include!s it) using
rustc --test. Only solution.rs is yours to edit.
Sign in to submit your solution.