Final: Stock Ledger
Lesson 47 of 48 in Coddy's Rust for Dart Developers course.
Challenge
MediumPort the complete Dart 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 Dart Map stores references to mutable Stock objects; Rust should own names and stocks. The reference sorts ASCII keys explicitly because a Dart map literal preserves insertion order.
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.
The Dart reference distinguishes a missing stock with nullable int? from a present zero. Its boolean result reports failure without exceptions, and a rejected new item is never inserted. The stated integer bounds are safely exact for Dart int; Rust uses the specified integer types. Port the behavior into the required Rust modules.
Complete standalone Dart reference program:
import 'dart:io';
import 'dart:convert';
class Stock {
int _amount = 0;
int quantity() => _amount;
bool apply(int delta) {
final next = _amount + delta;
if (next < 0) return false;
_amount = next;
return true;
}
}
class Ledger {
final _entries = <String, Stock>{};
bool apply(String name, int delta) {
final existing = _entries[name];
final stock = existing ?? Stock();
if (!stock.apply(delta)) return false;
if (existing == null) _entries[name] = stock;
return true;
}
int? quantity(String name) => _entries[name]?.quantity();
String report() {
final names = _entries.keys.toList()..sort();
final rows = <String>[];
for (final name in names) {
final amount = _entries[name]!.quantity();
if (amount > 0) rows.add(name + ':' + amount.toString());
}
return rows.isEmpty ? 'empty' : rows.join('\n');
}
}
String solve(String input) {
final ledger = Ledger();
var rejected = 0;
final trimmed = input.trim();
if (trimmed.isNotEmpty) {
for (final line in const LineSplitter().convert(trimmed)) {
final words = line.trim().split(RegExp(r'\s+'));
if (!ledger.apply(words[0], int.parse(words[1]))) rejected++;
}
}
return 'rejected:' + rejected.toString() + '\n' + ledger.report();
}
Future<void> main() async {
stdout.writeln(solve(await stdin.transform(utf8.decoder).join()));
}
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 Dart Developers
1First Rust Programs
Run Rust ModulesOutput and CommentsModules and VisibilityBindings and TypesNumbers and CastsRecap: Storage Invoice4Ownership and Borrowing
Ownership and MovesShared BorrowsMutable BorrowsLifetimes and ViewsBorrowing Recap3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record ReadingsPractice on your own: Online Rust compiler