Menu
CoddyTech

Final: Stock Ledger

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

challenge icon

Challenge

Medium

Port the complete C# reference into the supplied Rust API. 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 C# reference uses classes, a sorted dictionary with ordinal comparison, and nullable quantities. Rust should own names and use a map; its Result communicates rejection and Option distinguishes a missing name from a stored zero.

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 C# reference for the same valid input contract. Port its behavior into the specified Rust API; do not copy its ownership assumptions:

using System;
using System.Collections.Generic;
using System.Globalization;
class Stock {
    public int Quantity { get; private set; }
    public bool Apply(int delta) {
        int next = Quantity + delta;
        if (next < 0) return false;
        Quantity = next;
        return true;
    }
}
class Ledger {
    private readonly SortedDictionary<string, Stock> items =
        new SortedDictionary<string, Stock>(StringComparer.Ordinal);
    public bool Apply(string name, int delta) {
        Stock stock;
        if (items.TryGetValue(name, out stock)) return stock.Apply(delta);
        stock = new Stock();
        if (!stock.Apply(delta)) return false;
        items.Add(name, stock);
        return true;
    }
    public int? Quantity(string name) {
        Stock stock;
        return items.TryGetValue(name, out stock) ? (int?)stock.Quantity : null;
    }
    public string Report() {
        var lines = new List<string>();
        foreach (var item in items)
            if (item.Value.Quantity > 0)
                lines.Add(item.Key + ":" + item.Value.Quantity.ToString(CultureInfo.InvariantCulture));
        return lines.Count == 0 ? "empty" : string.Join("\n", lines);
    }
}
class Program {
    static void Main() {
        string[] tokens = Console.In.ReadToEnd().Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
        var ledger = new Ledger();
        int rejected = 0;
        for (int i = 0; i < tokens.Length; i += 2) {
            int delta = int.Parse(tokens[i + 1], CultureInfo.InvariantCulture);
            if (!ledger.Apply(tokens[i], delta)) rejected++;
        }
        Console.WriteLine("rejected:" + rejected.ToString(CultureInfo.InvariantCulture));
        Console.WriteLine(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 C# Developers

Practice on your own: Online Rust compiler