TExcelTAD
Home › Cargo in Depth › Cargo Exercises

Cargo Exercises

Each exercise is a piece of logic Cargo runs on every build, written as a pure function with the tests already in place. Run the starter first: it prints wrong answers (None, empty lists), which shows what the tests expect. Complete the code marked TODO until the output matches the expected output, then compare with the solution. The last exercise is a real Cargo session to fix.

Exercise 1: Expand a version requirement

Topics: Version Requirements & SemVer

Return the half-open range (lowest, first_excluded) that a caret (^, or no operator) or tilde (~) requirement allows, as version strings. Missing components count as 0. Remember the 0.x rule for carets.

python · try it yourself
def expand(req):
    # TODO: strip the operator, pad the version to 3 parts, compute the upper bound
    return None

for r in ["1.2.3", "^1.2", "1", "0.2.3", "0.0.3", "~1.2.3", "~1", "^0"]:
    print(f"{r:7} -> {expand(r)}")
1.2.3   -> None
^1.2    -> None
1       -> None
0.2.3   -> None
0.0.3   -> None
~1.2.3  -> None
~1      -> None
^0      -> None

Expected output:

text
1.2.3   -> ('1.2.3', '2.0.0')
^1.2    -> ('1.2.0', '2.0.0')
1       -> ('1.0.0', '2.0.0')
0.2.3   -> ('0.2.3', '0.3.0')
0.0.3   -> ('0.0.3', '0.0.4')
~1.2.3  -> ('1.2.3', '1.3.0')
~1      -> ('1.0.0', '2.0.0')
^0      -> ('0.0.0', '1.0.0')
Show solution
python
def expand(req):
    op = "~" if req.startswith("~") else "^"
    given = [int(x) for x in req.lstrip("^~").split(".")]
    n = len(given)
    ma, mi, pa = given + [0] * (3 - n)
    if op == "~":
        hi = (ma + 1, 0, 0) if n == 1 else (ma, mi + 1, 0)
    elif ma > 0 or n == 1:
        hi = (ma + 1, 0, 0)
    elif mi > 0 or n == 2:
        hi = (0, mi + 1, 0)
    else:
        hi = (0, 0, pa + 1)
    fmt = lambda v: ".".join(map(str, v))
    return fmt((ma, mi, pa)), fmt(hi)

^0 and 0 mean >=0.0.0, <1.0.0: with only one component given, the caret allows everything below the next major version, even for 0.

Exercise 2: Resolve features

Topics: Features: default, dep: and ?

Given a crate's [features] table and the features requested on the command line, return (features, deps): the sorted list of enabled features of the crate, and a sorted list of the optional dependencies that are turned on, written name or name/feature when a dependency feature is enabled. Rules: "dep:x" enables dependency x; "x/f" enables x and its feature f; "x?/f" enables f on x only if x ends up enabled by something else; default is included unless no_default is true.

python · try it yourself
def resolve(table, requested, no_default=False):
    # TODO: expand features transitively, collect deps, apply weak (?) entries at the end
    return None

table = {
    "default": ["names"],
    "names": [],
    "hex": [],
    "palettes": ["dep:palette"],
    "serde": ["dep:serde", "palette?/serde"],
    "full": ["hex", "palettes", "serde"],
}
print(resolve(table, []))
print(resolve(table, ["serde"], no_default=True))
print(resolve(table, ["serde", "palettes"]))
print(resolve(table, ["full"], no_default=True))
None
None
None
None

Expected output:

text
(['default', 'names'], [])
(['serde'], ['serde'])
(['default', 'names', 'palettes', 'serde'], ['palette', 'palette/serde', 'serde'])
(['full', 'hex', 'palettes', 'serde'], ['palette', 'palette/serde', 'serde'])
Show solution
python
def resolve(table, requested, no_default=False):
    feats, deps, weak = set(), set(), []
    todo = list(requested) + ([] if no_default else ["default"])
    while todo:
        f = todo.pop()
        if f in feats:
            continue
        feats.add(f)
        for item in table.get(f, []):
            if item.startswith("dep:"):
                deps.add(item[4:])
            elif "?/" in item:
                weak.append(item.split("?/"))
            elif "/" in item:
                d, df = item.split("/")
                deps.update([d, f"{d}/{df}"])
            else:
                todo.append(item)
    for d, df in weak:                     # weak entries only apply to enabled deps
        if d in deps:
            deps.add(f"{d}/{df}")
    return sorted(feats), sorted(deps)

The weak entries are applied after everything else is expanded: whether palette is on can depend on a feature that is processed later.

Exercise 3: Plan a cargo update

Topics: Cargo.lock, cargo update & --precise

Given the locked versions, the caret requirements from Cargo.toml and the versions available on the registry, return the lines cargo update would print, sorted by name: Updating name vOLD -> vNEW when a newer compatible version exists, Unchanged name vOLD (available: vX) when only an incompatible newer version exists (show the newest one), and nothing when the lock is already current. Use the expand idea from Exercise 1 (a helper compatible is given).

python · try it yourself
def ver(s):
    return tuple(int(x) for x in s.split("."))

def compatible(req, v):
    p = [int(x) for x in req.split(".")]
    lo = tuple(p + [0] * (3 - len(p)))
    if p[0] > 0 or len(p) == 1: hi = (p[0] + 1, 0, 0)
    elif len(p) == 2 or p[1] > 0: hi = (0, lo[1] + 1, 0)
    else: hi = (0, 0, lo[2] + 1)
    return lo <= ver(v) < hi

def plan(locked, reqs, available):
    # TODO
    return []

locked = {"serde": "1.0.200", "getrandom": "0.2.17", "regex": "1.13.1", "units": "0.2.0"}
reqs = {"serde": "1.0.200", "getrandom": "0.2", "regex": "1.12", "units": "0.2"}
available = {
    "serde": ["1.0.199", "1.0.200", "1.0.229"],
    "getrandom": ["0.2.16", "0.2.17", "0.3.4", "0.4.3"],
    "regex": ["1.12.2", "1.13.1"],
    "units": ["0.2.0", "0.2.1", "0.3.0"],
}
print("\n".join(plan(locked, reqs, available)) or "(nothing to update)")
(nothing to update)

Expected output:

text
Unchanged getrandom v0.2.17 (available: v0.4.3)
Updating serde v1.0.200 -> v1.0.229
Updating units v0.2.0 -> v0.2.1 (available: v0.3.0)
Show solution
python
def plan(locked, reqs, available):
    out = []
    for name in sorted(locked):
        vs = sorted(available[name], key=ver)
        ok = [v for v in vs if compatible(reqs[name], v)]
        best, newest = ok[-1], vs[-1]
        note = f" (available: v{newest})" if newest != best else ""
        if ver(best) > ver(locked[name]):
            out.append(f"Updating {name} v{locked[name]} -> v{best}{note}")
        elif note:
            out.append(f"Unchanged {name} v{locked[name]}{note}")
    return out

Real cargo update prints Unchanged lines only with --verbose (otherwise a summary note), and adds MSRV information when it skipped a version for that reason (Field Notes).

Exercise 4: Find duplicate versions

Topics: Duplicate Versions & cargo tree -d

Given lockfile entries as name version strings, return a sorted list of name: v1, v2 lines for every crate that appears in more than one version, with versions sorted numerically. That's cargo tree -d --depth 0 without the tree.

python · try it yourself
def duplicates(entries):
    # TODO: group versions by name
    return []

lock = ["rand_core 0.6.4", "rand_core 0.10.1", "serde 1.0.229", "syn 2.0.119", "syn 3.0.9",
        "getrandom 0.2.17", "getrandom 0.4.3", "libc 0.2.191", "syn 2.0.119"]
print("\n".join(duplicates(lock)) or "(no duplicates)")
(no duplicates)

Expected output:

text
getrandom: 0.2.17, 0.4.3
rand_core: 0.6.4, 0.10.1
syn: 2.0.119, 3.0.9
Show solution
python
def duplicates(entries):
    by_name = {}
    for e in entries:
        name, v = e.split()
        by_name.setdefault(name, set()).add(v)
    key = lambda v: tuple(int(x) for x in v.split("."))
    return [f"{n}: {', '.join(sorted(vs, key=key))}"
            for n, vs in sorted(by_name.items()) if len(vs) > 1]

The repeated syn 2.0.119 is the same version twice, not a duplicate: use a set. And 0.10.1 must sort after 0.6.4, which a string sort gets wrong.

Exercise 5: Fix the build

Topics: Features, Dependency Kinds

This program should print a JSON object, but it doesn't compile. Read the errors and fix one line of Cargo.toml (don't touch the Rust code).

bash · try it yourself
cargo new report --vcs none -q
cd report
cat >> Cargo.toml <<'T'
serde = "1"
serde_json = "1"
T
cat > src/main.rs <<'RS'
#[derive(serde::Serialize)]
struct Report { name: &'static str, passed: u32, failed: u32 }

fn main() {
    let r = Report { name: "nightly", passed: 41, failed: 1 };
    println!("{}", serde_json::to_string(&r).unwrap());
}
RS
cargo build -q 2>&1 | grep -E '^error|^note|help: ' | head -4
error[E0433]: cannot find `Serialize` in `serde`
note: found an item that was configured out
error[E0277]: the trait bound `Report: serde::Serialize` is not satisfied
help: the trait `Serialize` is not implemented for `Report`

Expected output once fixed (cargo run -q):

text
{"name":"nightly","passed":41,"failed":1}
Show solution

The Serialize derive macro lives behind serde's derive feature, which is off by default:

toml
serde = { version = "1", features = ["derive"] }

(cargo add serde --features derive writes exactly that.) The error message is the clue: the trait Serialize exists, but the derive macro of the same name doesn't until the feature is on.

Test yourself

In Exercise 2, why must weak (?) entries be applied after all other features are expanded?

  1. They are slower
  2. Whether the dependency is enabled can depend on a feature processed later
  3. Cargo processes features alphabetically
  4. They can't enable features

Why compare versions as tuples of integers rather than strings?

  1. It's faster
  2. As strings, "0.10.1" sorts before "0.6.4", which is wrong
  3. Python requires it
  4. To support pre-releases