Skip to content

morganlinton/BeautifulRust / skills/rust-best-practices

rust-best-practices

Unverified

Write idiomatic, robust, maintainable Rust. Use this skill whenever you write, review, refactor, debug, or explain Rust code: new crates, modules, functions, structs, traits, error types, async code, unsafe or FFI code, Cargo.toml, tests, or rustdoc. Trigger on any mention of Rust, cargo, crates, .rs files, the borrow checker, lifetimes, traits, clippy, or rustfmt, even when the user does not ask for "best practices" or "idiomatic" code. Synthesized from the Google Rust Style Guide, the Rust API Guidelines, Effective Rust, Rust Design Patterns, and Microsoft's Pragmatic Rust Guidelines.

FileKindSize
SKILL.mdskill md29.0 KB
evals/bevy-arena-regen/case.yamlconfig783 B
evals/bevy-arena-regen/files/Cargo.lockmanifest32.5 KB
evals/bevy-arena-regen/files/Cargo.tomlmanifest354 B
evals/bevy-arena-regen/files/src/lib.rsscript6.2 KB
evals/bevy-arena-regen/files/tests/arena.rsscript3.3 KB
evals/bevy-arena-regen/graders/01-builds-and-tests-pass.mdmarkdown167 B
evals/bevy-arena-regen/graders/02-regen-tested-headless.mdmarkdown272 B
evals/bevy-arena-regen/graders/03-system-params-by-value.mdmarkdown212 B
evals/bevy-arena-regen/graders/04-keeps-bevy-prelude.mdmarkdown159 B
evals/bevy-arena-regen/graders/05-plain-data-components.mdmarkdown208 B
evals/bevy-arena-regen/graders/06-ordered-after-damage.mdmarkdown334 B
evals/bevy-arena-regen/graders/07-no-panicking-queries.mdmarkdown186 B
evals/bevy-arena-regen/graders/08-clippy-clean.mdmarkdown125 B
evals/bevy-arena-regen/graders/09-health-never-exceeds-max.mdmarkdown134 B
evals/bevy-arena-regen/graders/10-existing-code-not-rewritten.mdmarkdown275 B
evals/bevy-arena-regen/place-files.shexecutablescript62 B
evals/bevy-arena-regen/prompt.mdmarkdown480 B
evals/log-summary-cli/case.yamlconfig581 B
evals/log-summary-cli/graders/01-never-panics-on-bad-input.mdmarkdown212 B
evals/log-summary-cli/graders/02-errors-name-the-file.mdmarkdown104 B
evals/log-summary-cli/graders/03-malformed-lines-counted.mdmarkdown186 B
evals/log-summary-cli/graders/04-paths-as-path-types.mdmarkdown168 B
evals/log-summary-cli/graders/05-sorted-and-skipped-count.mdmarkdown150 B
evals/log-summary-cli/graders/06-dependency-ranges.mdmarkdown134 B
evals/log-summary-cli/graders/07-map-based-counting.mdmarkdown103 B
evals/log-summary-cli/graders/08-aggregation-unit-tested.mdmarkdown147 B
evals/log-summary-cli/prompt.mdmarkdown730 B
evals/refactor-inventory-module/case.yamlconfig677 B
evals/refactor-inventory-module/files/inventory.rsscript3.2 KB
evals/refactor-inventory-module/graders/01-deny-warnings-removed.mdmarkdown90 B
evals/refactor-inventory-module/graders/02-no-rc-refcell-in-api.mdmarkdown141 B
evals/refactor-inventory-module/graders/03-borrowed-param-types.mdmarkdown157 B
evals/refactor-inventory-module/graders/04-error-implements-error.mdmarkdown108 B
evals/refactor-inventory-module/graders/05-no-unwrap-on-fallible-paths.mdmarkdown209 B
evals/refactor-inventory-module/graders/06-getter-renamed.mdmarkdown132 B
evals/refactor-inventory-module/graders/07-bool-param-replaced.mdmarkdown117 B
evals/refactor-inventory-module/graders/08-deterministic-report.mdmarkdown114 B
evals/refactor-inventory-module/graders/09-format-over-concat.mdmarkdown119 B
evals/refactor-inventory-module/graders/10-no-check-then-unwrap.mdmarkdown128 B
evals/refactor-inventory-module/graders/11-changes-listed-with-reasons.mdmarkdown94 B
evals/refactor-inventory-module/graders/12-signature-changes-called-out.mdmarkdown201 B
evals/refactor-inventory-module/place-files.shexecutablescript62 B
evals/refactor-inventory-module/prompt.mdmarkdown507 B
evals/semver-library-api/case.yamlconfig575 B
evals/semver-library-api/graders/01-implements-fromstr.mdmarkdown141 B
evals/semver-library-api/graders/02-implements-display.mdmarkdown94 B
evals/semver-library-api/graders/03-dedicated-error-type.mdmarkdown164 B
evals/semver-library-api/graders/04-common-traits-derived.mdmarkdown127 B
evals/semver-library-api/graders/05-fields-private.mdmarkdown125 B
evals/semver-library-api/graders/06-rustdoc-with-errors-section.mdmarkdown132 B
evals/semver-library-api/graders/07-doc-examples-use-question-mark.mdmarkdown86 B
evals/semver-library-api/graders/08-precedence-rules-tested.mdmarkdown152 B
evals/semver-library-api/graders/09-no-unwrap-in-library-code.mdmarkdown136 B
evals/semver-library-api/graders/10-eq-hash-agree-with-ord.mdmarkdown258 B
evals/semver-library-api/prompt.mdmarkdown667 B
references/bevy.mdmarkdown7.0 KB
references/effective-rust.mdmarkdown13.9 KB
references/google-rust-style-guide.mdmarkdown10.7 KB
references/microsoft-rust-guidelines.mdmarkdown16.2 KB
references/rust-api-guidelines.mdmarkdown11.2 KB
references/rust-design-patterns.mdmarkdown8.2 KB

evals/refactor-inventory-module/files/inventory.rs

View on GitHub
#![deny(warnings)]
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

#[derive(Debug, Clone)]
pub enum InventoryError {
    NotFound,
    Invalid,
    Io,
    Parse,
    Other(String),
}

#[derive(Clone)]
pub struct Item {
    pub name: String,
    pub qty: i64,
    pub price_cents: i64,
    pub is_perishable: bool,
}

pub struct Inventory {
    items: Rc<RefCell<HashMap<String, Item>>>,
}

impl Inventory {
    pub fn new() -> Rc<RefCell<Inventory>> {
        Rc::new(RefCell::new(Inventory {
            items: Rc::new(RefCell::new(HashMap::new())),
        }))
    }

    pub fn get_item(&self, name: &String) -> Option<Item> {
        if self.items.borrow().get(name).is_some() {
            Some(self.items.borrow().get(name).unwrap().clone())
        } else {
            None
        }
    }

    pub fn add_item(&self, name: String, qty: i64, price: i64, perishable: bool) -> Result<(), InventoryError> {
        if qty < 0 || price < 0 {
            return Err(InventoryError::Invalid);
        }
        let item = Item { name: name.clone(), qty: qty, price_cents: price, is_perishable: perishable };
        self.items.borrow_mut().insert(name, item);
        Ok(())
    }

    pub fn total_value(&self, names: &Vec<String>) -> i64 {
        let mut total = 0;
        for n in names {
            let item = self.items.borrow().get(n).unwrap().clone();
            total += item.qty * item.price_cents;
        }
        total
    }

    pub fn restock(&self, name: &String, amount: i64) -> Result<(), InventoryError> {
        if self.items.borrow().get(name).is_some() {
            let mut item = self.items.borrow().get(name).unwrap().clone();
            item.qty += amount;
            self.items.borrow_mut().insert(name.clone(), item);
            Ok(())
        } else {
            Err(InventoryError::NotFound)
        }
    }

    pub fn parse_line(line: &String) -> Result<Item, InventoryError> {
        let parts: Vec<&str> = line.split(',').collect();
        if parts.len() != 4 {
            return Err(InventoryError::Parse);
        }
        let qty = parts[1].trim().parse::<i64>().unwrap();
        let price = parts[2].trim().parse::<i64>().unwrap();
        let perishable = if parts[3].trim() == "true" { true } else { false };
        Ok(Item { name: parts[0].trim().to_string(), qty: qty, price_cents: price, is_perishable: perishable })
    }

    pub fn load(path: &String) -> Result<Rc<RefCell<Inventory>>, InventoryError> {
        let text = std::fs::read_to_string(path).unwrap();
        let inv = Inventory::new();
        for line in text.lines() {
            if line.trim().len() == 0 {
                continue;
            }
            let item = Inventory::parse_line(&line.to_string())?;
            inv.borrow().items.borrow_mut().insert(item.name.clone(), item);
        }
        Ok(inv)
    }

    pub fn report(&self, verbose: bool) -> String {
        let mut s = String::new();
        for (k, v) in self.items.borrow().iter() {
            s = s + &k + ": " + &v.qty.to_string() + "\n";
            if verbose {
                s = s + "  price=" + &v.price_cents.to_string() + " perishable=" + &v.is_perishable.to_string() + "\n";
            }
        }
        s
    }
}
finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the workStars: 322kUpdated Claude CodeCodexVerifiedInstall
systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixesStars: 322kUpdated Claude CodeCodexVerifiedInstall
test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation codeStars: 322kUpdated Claude CodeCodexVerifiedInstall
skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.Stars: 198kUpdated Claude CodeCodexVerifiedInstall