initial commit
This commit is contained in:
10
exercises/02_basic_calculator/08_overflow/Cargo.toml
Normal file
10
exercises/02_basic_calculator/08_overflow/Cargo.toml
Normal file
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "overflow"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lints.rust]
|
||||
# We silence dead code warnings for the time being in order to reduce
|
||||
# compiler noise.
|
||||
# We'll re-enable them again once we explain how visibility works in Rust.
|
||||
dead_code = "allow"
|
||||
49
exercises/02_basic_calculator/08_overflow/src/lib.rs
Normal file
49
exercises/02_basic_calculator/08_overflow/src/lib.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
// Customize the `dev` profile to wrap around on overflow.
|
||||
// Check Cargo's documentation to find out the right syntax:
|
||||
// https://doc.rust-lang.org/cargo/reference/profiles.html
|
||||
//
|
||||
// For reasons that we'll explain later, the customization needs to be done in the `Cargo.toml`
|
||||
// at the root of the repository, not in the `Cargo.toml` of the exercise.
|
||||
|
||||
pub fn factorial(n: u32) -> u32 {
|
||||
let mut result = 1;
|
||||
for i in 1..=n {
|
||||
result *= i;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::factorial;
|
||||
|
||||
#[test]
|
||||
fn twentieth() {
|
||||
// 20! is 2432902008176640000, which is too large to fit in a u32
|
||||
// With the default dev profile, this will panic when you run `cargo test`
|
||||
// We want it to wrap around instead
|
||||
assert_eq!(factorial(20), 2_192_834_560);
|
||||
// ☝️
|
||||
// A large number literal using underscores to improve readability!
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first() {
|
||||
assert_eq!(factorial(0), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn second() {
|
||||
assert_eq!(factorial(1), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn third() {
|
||||
assert_eq!(factorial(2), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fifth() {
|
||||
assert_eq!(factorial(5), 120);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user