Menu
CoddyTech

Port a Rust Inventory

Lesson 47 of 48 in Coddy's Lua for Rust Developers course.

challenge icon

Challenge

Medium

Port the reference Rust program into Lua modules. Each input line is a lowercase ASCII name, a colon, and a signed integer delta. Aggregate by name, retain only positive final totals, sort names ascending and return name=total entries joined by commas. Return empty when none remain. Implement inventory.aggregate(lines) in inventory.lua; app formats the result. All input lines are well-formed.

Edit app.lua, inventory.lua. The visible locked main.lua reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.

Public API checks: inventory.aggregate(lines) returns a fresh table of summed signed deltas, retaining zero totals. Empty input yields an empty table. Formatting and filtering happen in app. The locked driver checks this behavior before calling app.run. These checks print nothing when successful.

Rust 2021 reference

use std::collections::BTreeMap;
use std::io::{self, Read};
fn aggregate(input: &str) -> BTreeMap<String, i64> {
    let mut counts = BTreeMap::new();
    for line in input.lines() {
        let (name, delta) = line.split_once(':').unwrap();
        *counts.entry(name.to_owned()).or_insert(0) += delta.parse::<i64>().unwrap();
    }
    counts
}
fn main() {
    let mut input = String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    let rows: Vec<_> = aggregate(&input).into_iter()
        .filter(|(_, total)| *total > 0)
        .map(|(name, total)| format!("{}={}", name, total)).collect();
    println!("{}", if rows.is_empty() { "empty".to_owned() } else { rows.join(",") });
}

The Rust BTreeMap uses entry with or_insert(0) to initialize missing counts and iterates in key order. In Lua, distinguish a missing key from a stored zero, accumulate signed deltas, then sort the report keys explicitly. A signed integer here has optional - followed by digits; no plus sign is supplied. Keep aggregation separate from filtering so the public module still returns zero and negative totals.

Try it yourself

-- Public API checks
do
local inventory=require("inventory")
local counts=inventory.aggregate({"pen:3","pen:-1","book:0"})
assert(counts.pen==2 and counts.book==0,"aggregate must sum signed deltas by name")
local empty=inventory.aggregate({})
assert(next(empty)==nil,"aggregate empty input returns an empty table")
assert(counts.pen==2,"aggregation calls retain independent result state")
end
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))

All lessons in Lua for Rust Developers

Practice on your own: Online Lua compiler