Final: Stock Ledger
Lesson 47 of 48 in Coddy's Rust for Go Developers course.
Challenge
MediumPort the complete Go 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 Go map stores pointers to mutable stock values. Rust should own its names and stock values in a map; preserve the distinction between a missing key and a present 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 Go reference for the same valid input contract:
package main
import (
"bufio"
"errors"
"fmt"
"os"
"sort"
"strings"
)
type Stock struct { quantity int }
func (s *Stock) Apply(delta int) error {
if s.quantity + delta < 0 { return errors.New("negative") }
s.quantity += delta
return nil
}
func (s Stock) Quantity() int { return s.quantity }
type Ledger struct { rows map[string]*Stock }
func NewLedger() *Ledger { return &Ledger{rows: make(map[string]*Stock)} }
func (l *Ledger) Apply(name string, delta int) error {
stock, exists := l.rows[name]
if !exists { stock = &Stock{} }
if err := stock.Apply(delta); err != nil { return err }
if !exists { l.rows[name] = stock }
return nil
}
func (l *Ledger) Quantity(name string) (int, bool) {
stock, ok := l.rows[name]
if !ok { return 0, false }
return stock.Quantity(), true
}
func (l *Ledger) Report() string {
names := make([]string, 0)
for name, stock := range l.rows {
if stock.Quantity() > 0 { names = append(names, name) }
}
sort.Strings(names)
lines := make([]string, 0, len(names))
for _, name := range names { lines = append(lines, fmt.Sprintf("%s:%d", name, l.rows[name].Quantity())) }
if len(lines) == 0 { return "empty" }
return strings.Join(lines, "\n")
}
func main() {
in := bufio.NewReader(os.Stdin)
ledger := NewLedger()
rejected := 0
for {
var name string
var delta int
if _, err := fmt.Fscan(in, &name, &delta); err != nil { break }
if ledger.Apply(name, delta) != nil { rejected++ }
}
fmt.Printf("rejected:%d\n%s\n", rejected, 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 Go 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