Menu
CoddyTech

Final: Stock Ledger

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

challenge icon

Challenge

Medium

Port the complete Lua reference into the supplied Rust API. Lua status returns become explicit Rust Result values; table-held objects become owned Rust state. Input has up to 100 name delta rows, names lowercase ASCII words of at most 31 bytes and deltas from -1000 to 1000. Empty input is valid. Stock::new() -> Stock starts at zero; quantity(&self) -> i32 reads it; apply(&mut self, delta: i32) -> Result<(), &'static str> rejects a negative resulting quantity with Err("negative"), leaving state unchanged. Ledger::new() -> Ledger starts empty; its apply(&mut self, name: &str, delta: i32) has the same result contract, and must not create a missing item when rejecting. quantity(&self, name: &str) -> Option<i32> distinguishes missing from zero. report(&self) -> String lists only positive stocks as name:quantity in name order, separated by newlines, or empty. Return rejected:N, then the report on following lines. Calls to report do not change state. The Lua table stores references to Stock tables; Rust should own names and stock values in a map. Preserve the distinction between a missing item and an item with zero quantity.

Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.

Your code goes in exercise.rs, stock.rs, ledger.rs. main.rs holds the supplied input/output code and cannot be edited.

Complete Lua reference for the same valid input contract:

local Stock = {}
Stock.__index = Stock
function Stock.new() return setmetatable({amount = 0}, Stock) end
function Stock:quantity() return self.amount end
function Stock:apply(delta)
    local next_amount = self.amount + delta
    if next_amount < 0 then return false end
    self.amount = next_amount
    return true
end
local Ledger = {}
Ledger.__index = Ledger
function Ledger.new() return setmetatable({entries = {}}, Ledger) end
function Ledger:apply(name, delta)
    local stock = self.entries[name] or Stock.new()
    if not stock:apply(delta) then return false end
    self.entries[name] = stock
    return true
end
function Ledger:quantity(name)
    local stock = self.entries[name]
    if stock == nil then return nil end
    return stock:quantity()
end
function Ledger:report()
    local names, rows = {}, {}
    for name in pairs(self.entries) do names[#names + 1] = name end
    table.sort(names)
    for _, name in ipairs(names) do
        local amount = self.entries[name]:quantity()
        if amount > 0 then rows[#rows + 1] = name .. ":" .. amount end
    end
    return #rows == 0 and "empty" or table.concat(rows, "\n")
end
local ledger, rejected = Ledger.new(), 0
local words = {}
for word in io.read("*a"):gmatch("%S+") do words[#words + 1] = word end
for index = 1, #words, 2 do
    if not ledger:apply(words[index], tonumber(words[index + 1])) then
        rejected = rejected + 1
    end
end
print("rejected:" .. rejected .. "\n" .. ledger:report())

Try it yourself

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod stock;
mod ledger;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // BEGIN PUBLIC API PROBES
let mut s = stock::Stock::new(); assert_eq!(s.quantity(), 0);
    s.apply(11).unwrap(); assert_eq!(s.apply(-12), Err("negative")); assert_eq!(s.quantity(), 11);
    s.apply(-11).unwrap(); assert_eq!(s.quantity(), 0);
    let mut l = ledger::Ledger::new(); assert_eq!(l.quantity("held"), None);
    assert_eq!(l.apply("held", -8), Err("negative")); assert_eq!(l.quantity("held"), None);
    l.apply("held", 17).unwrap(); l.apply("alpha", 2).unwrap();
    assert_eq!(l.apply("held", -18), Err("negative")); assert_eq!(l.quantity("held"), Some(17));
    assert_eq!(l.report(), "alpha:2\nheld:17"); assert_eq!(l.report(), "alpha:2\nheld:17");
    l.apply("alpha", -2).unwrap(); assert_eq!(l.quantity("alpha"), Some(0)); assert_eq!(l.report(), "held:17");
    assert_eq!(ledger::Ledger::new().report(), "empty");
    // END PUBLIC API PROBES
    println!("{}", exercise::solve(&input));
}

All lessons in Rust for Lua Developers

Practice on your own: Online Rust compiler