repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/05_vecs/vecs1.rs | solutions/05_vecs/vecs1.rs | fn array_and_vec() -> ([i32; 4], Vec<i32>) {
let a = [10, 20, 30, 40]; // Array
// Used the `vec!` macro.
let v = vec![10, 20, 30, 40];
(a, v)
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_array_and_vec_similarity() {
let (a, v) = array_and_vec();
assert_eq!(a, *v);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/05_vecs/vecs2.rs | solutions/05_vecs/vecs2.rs | fn vec_loop(input: &[i32]) -> Vec<i32> {
let mut output = Vec::new();
for element in input {
output.push(2 * element);
}
output
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_vec_loop() {
let input = [2, 4, 6, 8, 10];
let ans = vec_loop(&input);
assert_eq!(ans, [4, 8, 12, 16, 20]);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/14_generics/generics2.rs | solutions/14_generics/generics2.rs | struct Wrapper<T> {
value: T,
}
impl<T> Wrapper<T> {
fn new(value: T) -> Self {
Wrapper { value }
}
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn store_u32_in_wrapper() {
assert_eq!(Wrapper::new(42).value, 42);
}
#[test]
fn store_str_in_wrapper() {
assert_eq!(Wrapper::new("Foo").value, "Foo");
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/14_generics/generics1.rs | solutions/14_generics/generics1.rs | // `Vec<T>` is generic over the type `T`. In most cases, the compiler is able to
// infer `T`, for example after pushing a value with a concrete type to the vector.
// But in this exercise, the compiler needs some help through a type annotation.
fn main() {
// `u8` and `i8` can both be converted to `i16`.
let mut numbers: Vec<i16> = Vec::new();
// ^^^^^^^^^^ added
// Don't change the lines below.
let n1: u8 = 42;
numbers.push(n1.into());
let n2: i8 = -1;
numbers.push(n2.into());
println!("{numbers:?}");
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/10_modules/modules1.rs | solutions/10_modules/modules1.rs | mod sausage_factory {
fn get_secret_recipe() -> String {
String::from("Ginger")
}
// Added `pub` before `fn` to make the function accessible outside the module.
pub fn make_sausage() {
get_secret_recipe();
println!("sausage!");
}
}
fn main() {
sausage_factory::make_sausage();
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/10_modules/modules3.rs | solutions/10_modules/modules3.rs | use std::time::{SystemTime, UNIX_EPOCH};
fn main() {
match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
Err(_) => panic!("SystemTime before UNIX EPOCH!"),
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/10_modules/modules2.rs | solutions/10_modules/modules2.rs | mod delicious_snacks {
// Added `pub` and used the expected alias after `as`.
pub use self::fruits::PEAR as fruit;
pub use self::veggies::CUCUMBER as veggie;
mod fruits {
pub const PEAR: &str = "Pear";
pub const APPLE: &str = "Apple";
}
mod veggies {
pub const CUCUMBER: &str = "Cucumber";
pub const CARROT: &str = "Carrot";
}
}
fn main() {
println!(
"favorite snacks: {} and {}",
delicious_snacks::fruit,
delicious_snacks::veggie,
);
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/quizzes/quiz2.rs | solutions/quizzes/quiz2.rs | // Let's build a little machine in the form of a function. As input, we're going
// to give a list of strings and commands. These commands determine what action
// is going to be applied to the string. It can either be:
// - Uppercase the string
// - Trim the string
// - Append "bar" to the string a specified amount of times
//
// The exact form of this will be:
// - The input is going to be a vector of 2-length tuples,
// the first element is the string, the second one is the command.
// - The output element is going to be a vector of strings.
enum Command {
Uppercase,
Trim,
Append(usize),
}
mod my_module {
use super::Command;
// The solution with a loop. Check out `transformer_iter` for a version
// with iterators.
pub fn transformer(input: Vec<(String, Command)>) -> Vec<String> {
let mut output = Vec::new();
for (string, command) in input {
// Create the new string.
let new_string = match command {
Command::Uppercase => string.to_uppercase(),
Command::Trim => string.trim().to_string(),
Command::Append(n) => string + &"bar".repeat(n),
};
// Push the new string to the output vector.
output.push(new_string);
}
output
}
// Equivalent to `transform` but uses an iterator instead of a loop for
// comparison. Don't worry, we will practice iterators later ;)
pub fn transformer_iter(input: Vec<(String, Command)>) -> Vec<String> {
input
.into_iter()
.map(|(string, command)| match command {
Command::Uppercase => string.to_uppercase(),
Command::Trim => string.trim().to_string(),
Command::Append(n) => string + &"bar".repeat(n),
})
.collect()
}
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
// Import `transformer`.
use super::my_module::transformer;
use super::Command;
use super::my_module::transformer_iter;
#[test]
fn it_works() {
for transformer in [transformer, transformer_iter] {
let input = vec![
("hello".to_string(), Command::Uppercase),
(" all roads lead to rome! ".to_string(), Command::Trim),
("foo".to_string(), Command::Append(1)),
("bar".to_string(), Command::Append(5)),
];
let output = transformer(input);
assert_eq!(
output,
[
"HELLO",
"all roads lead to rome!",
"foobar",
"barbarbarbarbarbar",
]
);
}
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/quizzes/quiz3.rs | solutions/quizzes/quiz3.rs | // An imaginary magical school has a new report card generation system written
// in Rust! Currently, the system only supports creating report cards where the
// student's grade is represented numerically (e.g. 1.0 -> 5.5). However, the
// school also issues alphabetical grades (A+ -> F-) and needs to be able to
// print both types of report card!
//
// Make the necessary code changes in the struct `ReportCard` and the impl
// block to support alphabetical report cards in addition to numerical ones.
use std::fmt::Display;
// Make the struct generic over `T`.
struct ReportCard<T> {
// ^^^
grade: T,
// ^
student_name: String,
student_age: u8,
}
// To be able to print the grade, it has to implement the `Display` trait.
impl<T: Display> ReportCard<T> {
// ^^^^^^^ require that `T` implements `Display`.
fn print(&self) -> String {
format!(
"{} ({}) - achieved a grade of {}",
&self.student_name, &self.student_age, &self.grade,
)
}
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn generate_numeric_report_card() {
let report_card = ReportCard {
grade: 2.1,
student_name: "Tom Wriggle".to_string(),
student_age: 12,
};
assert_eq!(
report_card.print(),
"Tom Wriggle (12) - achieved a grade of 2.1",
);
}
#[test]
fn generate_alphabetic_report_card() {
let report_card = ReportCard {
grade: "A+",
student_name: "Gary Plotter".to_string(),
student_age: 11,
};
assert_eq!(
report_card.print(),
"Gary Plotter (11) - achieved a grade of A+",
);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/quizzes/quiz1.rs | solutions/quizzes/quiz1.rs | // Mary is buying apples. The price of an apple is calculated as follows:
// - An apple costs 2 rustbucks.
// - However, if Mary buys more than 40 apples, the price of each apple in the
// entire order is reduced to only 1 rustbuck!
fn calculate_price_of_apples(n_apples: u64) -> u64 {
if n_apples > 40 {
n_apples
} else {
2 * n_apples
}
}
fn main() {
// You can optionally experiment here.
}
// Don't change the tests!
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn verify_test() {
assert_eq!(calculate_price_of_apples(35), 70);
assert_eq!(calculate_price_of_apples(40), 80);
assert_eq!(calculate_price_of_apples(41), 41);
assert_eq!(calculate_price_of_apples(65), 65);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/16_lifetimes/lifetimes1.rs | solutions/16_lifetimes/lifetimes1.rs | // The Rust compiler needs to know how to check whether supplied references are
// valid, so that it can let the programmer know if a reference is at risk of
// going out of scope before it is used. Remember, references are borrows and do
// not own their own data. What if their owner goes out of scope?
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
// ^^^^ ^^ ^^ ^^
if x.len() > y.len() { x } else { y }
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_longest() {
assert_eq!(longest("abcd", "123"), "abcd");
assert_eq!(longest("abc", "1234"), "1234");
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/16_lifetimes/lifetimes3.rs | solutions/16_lifetimes/lifetimes3.rs | // Lifetimes are also needed when structs hold references.
struct Book<'a> {
// ^^^^ added a lifetime annotation
author: &'a str,
// ^^
title: &'a str,
// ^^
}
fn main() {
let book = Book {
author: "George Orwell",
title: "1984",
};
println!("{} by {}", book.title, book.author);
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/16_lifetimes/lifetimes2.rs | solutions/16_lifetimes/lifetimes2.rs | fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
fn main() {
let string1 = String::from("long string is long");
// Solution 1: You can move `strings2` out of the inner block so that it is
// not dropped before the print statement.
let string2 = String::from("xyz");
let result;
{
result = longest(&string1, &string2);
}
println!("The longest string is '{result}'");
// `string2` dropped at the end of the function.
// =========================================================================
let string1 = String::from("long string is long");
let result;
{
let string2 = String::from("xyz");
result = longest(&string1, &string2);
// Solution 2: You can move the print statement into the inner block so
// that it is executed before `string2` is dropped.
println!("The longest string is '{result}'");
// `string2` dropped here (end of the inner scope).
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/00_intro/intro1.rs | solutions/00_intro/intro1.rs | fn main() {
// Congratulations, you finished the first exercise 🎉
// As an introduction to Rustlings, the first exercise only required
// entering `n` in the terminal to go to the next exercise.
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/00_intro/intro2.rs | solutions/00_intro/intro2.rs | fn main() {
// `println!` instead of `printline!`.
println!("Hello world!");
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/21_macros/macros4.rs | solutions/21_macros/macros4.rs | // Added semicolons to separate the macro arms.
#[rustfmt::skip]
macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
($val:expr) => {
println!("Look at this other macro: {}", $val);
};
}
fn main() {
my_macro!();
my_macro!(7777);
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/21_macros/macros2.rs | solutions/21_macros/macros2.rs | // Moved the macro definition to be before its call.
macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
}
fn main() {
my_macro!();
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/21_macros/macros1.rs | solutions/21_macros/macros1.rs | macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
}
fn main() {
my_macro!();
// ^
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/21_macros/macros3.rs | solutions/21_macros/macros3.rs | // Added the `macro_use` attribute.
#[macro_use]
mod macros {
macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
}
}
fn main() {
my_macro!();
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/01_variables/variables5.rs | solutions/01_variables/variables5.rs | fn main() {
let number = "T-H-R-E-E";
println!("Spell a number: {number}");
// Using variable shadowing
// https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#shadowing
let number = 3;
println!("Number plus two is: {}", number + 2);
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/01_variables/variables1.rs | solutions/01_variables/variables1.rs | fn main() {
// Declaring variables requires the `let` keyword.
let x = 5;
println!("x has the value {x}");
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/01_variables/variables2.rs | solutions/01_variables/variables2.rs | fn main() {
// The easiest way to fix the compiler error is to initialize the
// variable `x`. By setting its value to an integer, Rust infers its type
// as `i32` which is the default type for integers.
let x = 42;
// But we can enforce a type different from the default `i32` by adding
// a type annotation:
// let x: u8 = 42;
if x == 10 {
println!("x is ten!");
} else {
println!("x is not ten!");
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/01_variables/variables6.rs | solutions/01_variables/variables6.rs | // The type of constants must always be annotated.
const NUMBER: u64 = 3;
fn main() {
println!("Number: {NUMBER}");
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/01_variables/variables3.rs | solutions/01_variables/variables3.rs | #![allow(clippy::needless_late_init)]
fn main() {
// Reading uninitialized variables isn't allowed in Rust!
// Therefore, we need to assign a value first.
let x: i32 = 42;
println!("Number {x}");
// It is possible to declare a variable and initialize it later.
// But it can't be used before initialization.
let y: i32;
y = 42;
println!("Number {y}");
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/01_variables/variables4.rs | solutions/01_variables/variables4.rs | fn main() {
// In Rust, variables are immutable by default.
// Adding the `mut` keyword after `let` makes the declared variable mutable.
let mut x = 3;
println!("Number {x}");
x = 5;
println!("Number {x}");
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/04_primitive_types/primitive_types3.rs | solutions/04_primitive_types/primitive_types3.rs | fn main() {
// An array with 100 elements of the value 42.
let a = [42; 100];
if a.len() >= 100 {
println!("Wow, that's a big array!");
} else {
println!("Meh, I eat arrays like that for breakfast.");
panic!("Array not big enough, more elements needed");
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/04_primitive_types/primitive_types1.rs | solutions/04_primitive_types/primitive_types1.rs | fn main() {
let is_morning = true;
if is_morning {
println!("Good morning!");
}
let is_evening = !is_morning;
if is_evening {
println!("Good evening!");
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/04_primitive_types/primitive_types6.rs | solutions/04_primitive_types/primitive_types6.rs | fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
#[test]
fn indexing_tuple() {
let numbers = (1, 2, 3);
// Tuple indexing syntax.
let second = numbers.1;
assert_eq!(second, 2, "This is not the 2nd number in the tuple!");
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/04_primitive_types/primitive_types2.rs | solutions/04_primitive_types/primitive_types2.rs | fn main() {
let my_first_initial = 'C';
if my_first_initial.is_alphabetic() {
println!("Alphabetical!");
} else if my_first_initial.is_numeric() {
println!("Numerical!");
} else {
println!("Neither alphabetic nor numeric!");
}
// Example with an emoji.
let your_character = '🦀';
if your_character.is_alphabetic() {
println!("Alphabetical!");
} else if your_character.is_numeric() {
println!("Numerical!");
} else {
println!("Neither alphabetic nor numeric!");
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/04_primitive_types/primitive_types4.rs | solutions/04_primitive_types/primitive_types4.rs | fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
#[test]
fn slice_out_of_array() {
let a = [1, 2, 3, 4, 5];
// 0 1 2 3 4 <- indices
// -------
// |
// +--- slice
// Note that the upper index 4 is excluded.
let nice_slice = &a[1..4];
assert_eq!([2, 3, 4], nice_slice);
// The upper index can be included by using the syntax `..=` (with `=` sign)
let nice_slice = &a[1..=3];
assert_eq!([2, 3, 4], nice_slice);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/04_primitive_types/primitive_types5.rs | solutions/04_primitive_types/primitive_types5.rs | fn main() {
let cat = ("Furry McFurson", 3.5);
// Destructuring the tuple.
let (name, age) = cat;
println!("{name} is {age} years old");
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/02_functions/functions5.rs | solutions/02_functions/functions5.rs | fn square(num: i32) -> i32 {
// Removed the semicolon `;` at the end of the line below to implicitly return the result.
num * num
}
fn main() {
let answer = square(3);
println!("The square of 3 is {answer}");
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/02_functions/functions2.rs | solutions/02_functions/functions2.rs | // The type of function arguments must be annotated.
// Added the type annotation `u64`.
fn call_me(num: u64) {
for i in 0..num {
println!("Ring! Call number {}", i + 1);
}
}
fn main() {
call_me(3);
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/02_functions/functions4.rs | solutions/02_functions/functions4.rs | fn is_even(num: i64) -> bool {
num % 2 == 0
}
// The return type must always be annotated.
fn sale_price(price: i64) -> i64 {
if is_even(price) {
price - 10
} else {
price - 3
}
}
fn main() {
let original_price = 51;
println!("Your sale price is {}", sale_price(original_price));
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/02_functions/functions1.rs | solutions/02_functions/functions1.rs | // Some function with the name `call_me` without arguments or a return value.
fn call_me() {
println!("Hello world!");
}
fn main() {
call_me();
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/02_functions/functions3.rs | solutions/02_functions/functions3.rs | fn call_me(num: u8) {
for i in 0..num {
println!("Ring! Call number {}", i + 1);
}
}
fn main() {
// `call_me` expects an argument.
call_me(5);
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/12_options/options3.rs | solutions/12_options/options3.rs | #[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let optional_point = Some(Point { x: 100, y: 200 });
// Solution 1: Matching over the `Option` (not `&Option`) but without moving
// out of the `Some` variant.
match optional_point {
Some(ref p) => println!("Coordinates are {},{}", p.x, p.y),
// ^^^ added
_ => panic!("No match!"),
}
// Solution 2: Matching over a reference (`&Option`) by added `&` before
// `optional_point`.
match &optional_point {
//^ added
Some(p) => println!("Coordinates are {},{}", p.x, p.y),
_ => panic!("No match!"),
}
println!("{optional_point:?}");
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/12_options/options1.rs | solutions/12_options/options1.rs | // This function returns how much ice cream there is left in the fridge.
// If it's before 22:00 (24-hour system), then 5 scoops are left. At 22:00,
// someone eats it all, so no ice cream is left (value 0). Return `None` if
// `hour_of_day` is higher than 23.
fn maybe_ice_cream(hour_of_day: u16) -> Option<u16> {
match hour_of_day {
0..=21 => Some(5),
22..=23 => Some(0),
_ => None,
}
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn raw_value() {
// Using `unwrap` is fine in a test.
let ice_creams = maybe_ice_cream(12).unwrap();
assert_eq!(ice_creams, 5);
}
#[test]
fn check_ice_cream() {
assert_eq!(maybe_ice_cream(0), Some(5));
assert_eq!(maybe_ice_cream(9), Some(5));
assert_eq!(maybe_ice_cream(18), Some(5));
assert_eq!(maybe_ice_cream(22), Some(0));
assert_eq!(maybe_ice_cream(23), Some(0));
assert_eq!(maybe_ice_cream(24), None);
assert_eq!(maybe_ice_cream(25), None);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/12_options/options2.rs | solutions/12_options/options2.rs | fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
#[test]
fn simple_option() {
let target = "rustlings";
let optional_target = Some(target);
// if-let
if let Some(word) = optional_target {
assert_eq!(word, target);
}
}
#[test]
fn layered_option() {
let range = 10;
let mut optional_integers: Vec<Option<i8>> = vec![None];
for i in 1..=range {
optional_integers.push(Some(i));
}
let mut cursor = range;
// while-let with nested pattern matching
while let Some(Some(integer)) = optional_integers.pop() {
assert_eq!(integer, cursor);
cursor -= 1;
}
assert_eq!(cursor, 0);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/06_move_semantics/move_semantics4.rs | solutions/06_move_semantics/move_semantics4.rs | fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
#[test]
fn move_semantics4() {
let mut x = Vec::new();
let y = &mut x;
// `y` used here.
y.push(42);
// The mutable reference `y` is not used anymore,
// therefore a new reference can be created.
let z = &mut x;
z.push(13);
assert_eq!(x, [42, 13]);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/06_move_semantics/move_semantics3.rs | solutions/06_move_semantics/move_semantics3.rs | fn fill_vec(mut vec: Vec<i32>) -> Vec<i32> {
// ^^^ added
vec.push(88);
vec
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn move_semantics3() {
let vec0 = vec![22, 44, 66];
let vec1 = fill_vec(vec0);
assert_eq!(vec1, [22, 44, 66, 88]);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/06_move_semantics/move_semantics5.rs | solutions/06_move_semantics/move_semantics5.rs | #![allow(clippy::ptr_arg)]
// Borrows instead of taking ownership.
// It is recommended to use `&str` instead of `&String` here. But this is
// enough for now because we didn't handle strings yet.
fn get_char(data: &String) -> char {
data.chars().last().unwrap()
}
// Takes ownership instead of borrowing.
fn string_uppercase(mut data: String) {
data = data.to_uppercase();
println!("{data}");
}
fn main() {
let data = "Rust is great!".to_string();
get_char(&data);
string_uppercase(data);
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/06_move_semantics/move_semantics2.rs | solutions/06_move_semantics/move_semantics2.rs | fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
let mut vec = vec;
vec.push(88);
vec
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn move_semantics2() {
let vec0 = vec![22, 44, 66];
// Cloning `vec0` so that the clone is moved into `fill_vec`, not `vec0`
// itself.
let vec1 = fill_vec(vec0.clone());
assert_eq!(vec0, [22, 44, 66]);
assert_eq!(vec1, [22, 44, 66, 88]);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/solutions/06_move_semantics/move_semantics1.rs | solutions/06_move_semantics/move_semantics1.rs | fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
let mut vec = vec;
// ^^^ added
vec.push(88);
vec
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn move_semantics1() {
let vec0 = vec![22, 44, 66];
let vec1 = fill_vec(vec0);
// `vec0` can't be accessed anymore because it is moved to `fill_vec`.
assert_eq!(vec1, vec![22, 44, 66, 88]);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/src/info_file.rs | src/info_file.rs | use anyhow::{Context, Error, Result, bail};
use serde::Deserialize;
use std::{fs, io::ErrorKind};
use crate::{embedded::EMBEDDED_FILES, exercise::RunnableExercise};
/// Deserialized from the `info.toml` file.
#[derive(Deserialize)]
pub struct ExerciseInfo {
/// Exercise's unique name.
pub name: String,
/// Exercise's directory name inside the `exercises/` directory.
pub dir: Option<String>,
/// Run `cargo test` on the exercise.
#[serde(default = "default_true")]
pub test: bool,
/// Deny all Clippy warnings.
#[serde(default)]
pub strict_clippy: bool,
/// The exercise's hint to be shown to the user on request.
pub hint: String,
/// The exercise is already solved. Ignore it when checking that all exercises are unsolved.
#[serde(default)]
pub skip_check_unsolved: bool,
}
#[inline(always)]
const fn default_true() -> bool {
true
}
impl ExerciseInfo {
/// Path to the exercise file starting with the `exercises/` directory.
pub fn path(&self) -> String {
let mut path = if let Some(dir) = &self.dir {
// 14 = 10 + 1 + 3
// exercises/ + / + .rs
let mut path = String::with_capacity(14 + dir.len() + self.name.len());
path.push_str("exercises/");
path.push_str(dir);
path.push('/');
path
} else {
// 13 = 10 + 3
// exercises/ + .rs
let mut path = String::with_capacity(13 + self.name.len());
path.push_str("exercises/");
path
};
path.push_str(&self.name);
path.push_str(".rs");
path
}
}
impl RunnableExercise for ExerciseInfo {
#[inline]
fn name(&self) -> &str {
&self.name
}
#[inline]
fn dir(&self) -> Option<&str> {
self.dir.as_deref()
}
#[inline]
fn strict_clippy(&self) -> bool {
self.strict_clippy
}
#[inline]
fn test(&self) -> bool {
self.test
}
}
/// The deserialized `info.toml` file.
#[derive(Deserialize)]
pub struct InfoFile {
/// For possible breaking changes in the future for community exercises.
pub format_version: u8,
/// Shown to users when starting with the exercises.
pub welcome_message: Option<String>,
/// Shown to users after finishing all exercises.
pub final_message: Option<String>,
/// List of all exercises.
pub exercises: Vec<ExerciseInfo>,
}
impl InfoFile {
/// Official exercises: Parse the embedded `info.toml` file.
/// Community exercises: Parse the `info.toml` file in the current directory.
pub fn parse() -> Result<Self> {
// Read a local `info.toml` if it exists.
let slf = match fs::read_to_string("info.toml") {
Ok(file_content) => toml::de::from_str::<Self>(&file_content)
.context("Failed to parse the `info.toml` file")?,
Err(e) => {
if e.kind() == ErrorKind::NotFound {
return toml::de::from_str(EMBEDDED_FILES.info_file)
.context("Failed to parse the embedded `info.toml` file");
}
return Err(Error::from(e).context("Failed to read the `info.toml` file"));
}
};
if slf.exercises.is_empty() {
bail!("{NO_EXERCISES_ERR}");
}
Ok(slf)
}
}
const NO_EXERCISES_ERR: &str = "There are no exercises yet!
Add at least one exercise before testing.";
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/src/dev.rs | src/dev.rs | use anyhow::{Context, Result, bail};
use clap::Subcommand;
use std::path::PathBuf;
mod check;
mod new;
mod update;
#[derive(Subcommand)]
pub enum DevCommands {
/// Create a new project for community exercises
New {
/// The path to create the project in
path: PathBuf,
/// Don't try to initialize a Git repository in the project directory
#[arg(long)]
no_git: bool,
},
/// Run checks on the exercises
Check {
/// Require that every exercise has a solution
#[arg(short, long)]
require_solutions: bool,
},
/// Update the `Cargo.toml` file for the exercises
Update,
}
impl DevCommands {
pub fn run(self) -> Result<()> {
match self {
Self::New { path, no_git } => {
if cfg!(debug_assertions) {
bail!("Disabled in the debug build");
}
new::new(&path, no_git).context(INIT_ERR)
}
Self::Check { require_solutions } => check::check(require_solutions),
Self::Update => update::update(),
}
}
}
const INIT_ERR: &str = "Initialization failed.
After resolving the issue, delete the `rustlings` directory (if it was created) and try again";
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/src/cargo_toml.rs | src/cargo_toml.rs | use anyhow::{Context, Result};
use std::path::Path;
use crate::{exercise::RunnableExercise, info_file::ExerciseInfo};
/// Initial capacity of the bins buffer.
pub const BINS_BUFFER_CAPACITY: usize = 1 << 14;
/// Return the start and end index of the content of the list `bin = […]`.
/// bin = [xxxxxxxxxxxxxxxxx]
/// |start_ind |
/// |end_ind
pub fn bins_start_end_ind(cargo_toml: &str) -> Result<(usize, usize)> {
let start_ind = cargo_toml
.find("bin = [")
.context("Failed to find the start of the `bin` list (`bin = [`)")?
+ 7;
let end_ind = start_ind
+ cargo_toml
.get(start_ind..)
.and_then(|slice| slice.as_bytes().iter().position(|c| *c == b']'))
.context("Failed to find the end of the `bin` list (`]`)")?;
Ok((start_ind, end_ind))
}
/// Generate and append the content of the `bin` list in `Cargo.toml`.
/// The `exercise_path_prefix` is the prefix of the `path` field of every list entry.
pub fn append_bins(
buf: &mut Vec<u8>,
exercise_infos: &[ExerciseInfo],
exercise_path_prefix: &[u8],
) {
buf.push(b'\n');
for exercise_info in exercise_infos {
buf.extend_from_slice(b" { name = \"");
buf.extend_from_slice(exercise_info.name.as_bytes());
buf.extend_from_slice(b"\", path = \"");
buf.extend_from_slice(exercise_path_prefix);
buf.extend_from_slice(b"exercises/");
if let Some(dir) = &exercise_info.dir {
buf.extend_from_slice(dir.as_bytes());
buf.push(b'/');
}
buf.extend_from_slice(exercise_info.name.as_bytes());
buf.extend_from_slice(b".rs\" },\n");
let sol_path = exercise_info.sol_path();
if !Path::new(&sol_path).exists() {
continue;
}
buf.extend_from_slice(b" { name = \"");
buf.extend_from_slice(exercise_info.name.as_bytes());
buf.extend_from_slice(b"_sol");
buf.extend_from_slice(b"\", path = \"");
buf.extend_from_slice(exercise_path_prefix);
buf.extend_from_slice(b"solutions/");
if let Some(dir) = &exercise_info.dir {
buf.extend_from_slice(dir.as_bytes());
buf.push(b'/');
}
buf.extend_from_slice(exercise_info.name.as_bytes());
buf.extend_from_slice(b".rs\" },\n");
}
}
/// Update the `bin` list and leave everything else unchanged.
pub fn updated_cargo_toml(
exercise_infos: &[ExerciseInfo],
current_cargo_toml: &str,
exercise_path_prefix: &[u8],
) -> Result<Vec<u8>> {
let (bins_start_ind, bins_end_ind) = bins_start_end_ind(current_cargo_toml)?;
let mut updated_cargo_toml = Vec::with_capacity(BINS_BUFFER_CAPACITY);
updated_cargo_toml.extend_from_slice(¤t_cargo_toml.as_bytes()[..bins_start_ind]);
append_bins(
&mut updated_cargo_toml,
exercise_infos,
exercise_path_prefix,
);
updated_cargo_toml.extend_from_slice(¤t_cargo_toml.as_bytes()[bins_end_ind..]);
Ok(updated_cargo_toml)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_bins_start_end_ind() {
assert_eq!(bins_start_end_ind("").ok(), None);
assert_eq!(bins_start_end_ind("[]").ok(), None);
assert_eq!(bins_start_end_ind("bin = [").ok(), None);
assert_eq!(bins_start_end_ind("bin = ]").ok(), None);
assert_eq!(bins_start_end_ind("bin = []").ok(), Some((7, 7)));
assert_eq!(bins_start_end_ind("bin= []").ok(), None);
assert_eq!(bins_start_end_ind("bin =[]").ok(), None);
assert_eq!(bins_start_end_ind("bin=[]").ok(), None);
assert_eq!(bins_start_end_ind("bin = [\nxxx\n]").ok(), Some((7, 12)));
}
#[test]
fn test_bins() {
let exercise_infos = [
ExerciseInfo {
name: String::from("1"),
dir: None,
test: true,
strict_clippy: true,
hint: String::new(),
skip_check_unsolved: false,
},
ExerciseInfo {
name: String::from("2"),
dir: Some(String::from("d")),
test: false,
strict_clippy: false,
hint: String::new(),
skip_check_unsolved: false,
},
];
let mut buf = Vec::with_capacity(128);
append_bins(&mut buf, &exercise_infos, b"");
assert_eq!(
buf,
br#"
{ name = "1", path = "exercises/1.rs" },
{ name = "2", path = "exercises/d/2.rs" },
"#,
);
assert_eq!(
updated_cargo_toml(
&exercise_infos,
"abc\n\
bin = [xxx]\n\
123",
b"../"
)
.unwrap(),
br#"abc
bin = [
{ name = "1", path = "../exercises/1.rs" },
{ name = "2", path = "../exercises/d/2.rs" },
]
123"#,
);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/src/list.rs | src/list.rs | use anyhow::{Context, Result};
use crossterm::{
QueueableCommand, cursor,
event::{
self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind, MouseEventKind,
},
terminal::{
DisableLineWrap, EnableLineWrap, EnterAlternateScreen, LeaveAlternateScreen,
disable_raw_mode, enable_raw_mode,
},
};
use std::io::{self, StdoutLock, Write};
use crate::app_state::AppState;
use self::state::{Filter, ListState};
mod scroll_state;
mod state;
fn handle_list(app_state: &mut AppState, stdout: &mut StdoutLock) -> Result<()> {
let mut list_state = ListState::build(app_state, stdout)?;
let mut is_searching = false;
loop {
match event::read().context("Failed to read terminal event")? {
Event::Key(key) => {
match key.kind {
KeyEventKind::Release => continue,
KeyEventKind::Press | KeyEventKind::Repeat => (),
}
list_state.message.clear();
if is_searching {
match key.code {
KeyCode::Esc | KeyCode::Enter => {
is_searching = false;
list_state.search_query.clear();
}
KeyCode::Char(c) => {
list_state.search_query.push(c);
list_state.apply_search_query();
}
KeyCode::Backspace => {
list_state.search_query.pop();
list_state.apply_search_query();
}
_ => continue,
}
list_state.draw(stdout)?;
continue;
}
match key.code {
KeyCode::Char('q') => return Ok(()),
KeyCode::Down | KeyCode::Char('j') => list_state.select_next(),
KeyCode::Up | KeyCode::Char('k') => list_state.select_previous(),
KeyCode::Home | KeyCode::Char('g') => list_state.select_first(),
KeyCode::End | KeyCode::Char('G') => list_state.select_last(),
KeyCode::Char('d') => {
if list_state.filter() == Filter::Done {
list_state.set_filter(Filter::None);
list_state.message.push_str("Disabled filter DONE");
} else {
list_state.set_filter(Filter::Done);
list_state.message.push_str(
"Enabled filter DONE │ Press d again to disable the filter",
);
}
}
KeyCode::Char('p') => {
if list_state.filter() == Filter::Pending {
list_state.set_filter(Filter::None);
list_state.message.push_str("Disabled filter PENDING");
} else {
list_state.set_filter(Filter::Pending);
list_state.message.push_str(
"Enabled filter PENDING │ Press p again to disable the filter",
);
}
}
KeyCode::Char('r') => list_state.reset_selected()?,
KeyCode::Char('c') => {
if list_state.selected_to_current_exercise()? {
return Ok(());
}
}
KeyCode::Char('s' | '/') => {
is_searching = true;
list_state.apply_search_query();
}
// Redraw to remove the message.
KeyCode::Esc => (),
_ => continue,
}
}
Event::Mouse(event) => match event.kind {
MouseEventKind::ScrollDown => list_state.select_next(),
MouseEventKind::ScrollUp => list_state.select_previous(),
_ => continue,
},
Event::Resize(width, height) => list_state.set_term_size(width, height),
// Ignore
Event::FocusGained | Event::FocusLost => continue,
}
list_state.draw(stdout)?;
}
}
pub fn list(app_state: &mut AppState) -> Result<()> {
let mut stdout = io::stdout().lock();
stdout
.queue(EnterAlternateScreen)?
.queue(cursor::Hide)?
.queue(DisableLineWrap)?
.queue(EnableMouseCapture)?;
enable_raw_mode()?;
let res = handle_list(app_state, &mut stdout);
// Restore the terminal even if we got an error.
stdout
.queue(LeaveAlternateScreen)?
.queue(cursor::Show)?
.queue(EnableLineWrap)?
.queue(DisableMouseCapture)?
.flush()?;
disable_raw_mode()?;
res
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/src/exercise.rs | src/exercise.rs | use anyhow::Result;
use crossterm::{
QueueableCommand,
style::{Attribute, Color, ResetColor, SetAttribute, SetForegroundColor},
};
use std::io::{self, StdoutLock, Write};
use crate::{
cmd::CmdRunner,
term::{self, CountedWrite, file_path, terminal_file_link, write_ansi},
};
/// The initial capacity of the output buffer.
pub const OUTPUT_CAPACITY: usize = 1 << 14;
pub fn solution_link_line(
stdout: &mut StdoutLock,
solution_path: &str,
emit_file_links: bool,
) -> io::Result<()> {
stdout.queue(SetAttribute(Attribute::Bold))?;
stdout.write_all(b"Solution")?;
stdout.queue(ResetColor)?;
stdout.write_all(b" for comparison: ")?;
file_path(stdout, Color::Cyan, |writer| {
if emit_file_links && let Some(canonical_path) = term::canonicalize(solution_path) {
terminal_file_link(writer, solution_path, &canonical_path)
} else {
writer.stdout().write_all(solution_path.as_bytes())
}
})?;
stdout.write_all(b"\n")
}
// Run an exercise binary and append its output to the `output` buffer.
// Compilation must be done before calling this method.
fn run_bin(
bin_name: &str,
mut output: Option<&mut Vec<u8>>,
cmd_runner: &CmdRunner,
) -> Result<bool> {
if let Some(output) = output.as_deref_mut() {
write_ansi(output, SetAttribute(Attribute::Underlined));
output.extend_from_slice(b"Output");
write_ansi(output, ResetColor);
output.push(b'\n');
}
let success = cmd_runner.run_debug_bin(bin_name, output.as_deref_mut())?;
if let Some(output) = output
&& !success
{
// This output is important to show the user that something went wrong.
// Otherwise, calling something like `exit(1)` in an exercise without further output
// leaves the user confused about why the exercise isn't done yet.
write_ansi(output, SetAttribute(Attribute::Bold));
write_ansi(output, SetForegroundColor(Color::Red));
output.extend_from_slice(b"The exercise didn't run successfully (nonzero exit code)");
write_ansi(output, ResetColor);
output.push(b'\n');
}
Ok(success)
}
/// See `info_file::ExerciseInfo`
pub struct Exercise {
pub dir: Option<&'static str>,
pub name: &'static str,
/// Path of the exercise file starting with the `exercises/` directory.
pub path: &'static str,
pub canonical_path: Option<String>,
pub test: bool,
pub strict_clippy: bool,
pub hint: &'static str,
pub done: bool,
}
impl Exercise {
pub fn terminal_file_link<'a>(
&self,
writer: &mut impl CountedWrite<'a>,
emit_file_links: bool,
) -> io::Result<()> {
file_path(writer, Color::Blue, |writer| {
if emit_file_links && let Some(canonical_path) = self.canonical_path.as_deref() {
terminal_file_link(writer, self.path, canonical_path)
} else {
writer.write_str(self.path)
}
})
}
}
pub trait RunnableExercise {
fn name(&self) -> &str;
fn dir(&self) -> Option<&str>;
fn strict_clippy(&self) -> bool;
fn test(&self) -> bool;
// Compile, check and run the exercise or its solution (depending on `bin_name´).
// The output is written to the `output` buffer after clearing it.
fn run<const FORCE_STRICT_CLIPPY: bool>(
&self,
bin_name: &str,
mut output: Option<&mut Vec<u8>>,
cmd_runner: &CmdRunner,
) -> Result<bool> {
if let Some(output) = output.as_deref_mut() {
output.clear();
}
let build_success = cmd_runner
.cargo("build", bin_name, output.as_deref_mut())
.run("cargo build …")?;
if !build_success {
return Ok(false);
}
// Discard the compiler output because it will be shown again by `cargo test` or Clippy.
if let Some(output) = output.as_deref_mut() {
output.clear();
}
if self.test() {
let output_is_some = output.is_some();
let mut test_cmd = cmd_runner.cargo("test", bin_name, output.as_deref_mut());
if output_is_some {
test_cmd.args(["--", "--color", "always", "--format", "pretty"]);
}
let test_success = test_cmd.run("cargo test …")?;
if !test_success {
run_bin(bin_name, output, cmd_runner)?;
return Ok(false);
}
// Discard the compiler output because it will be shown again by Clippy.
if let Some(output) = output.as_deref_mut() {
output.clear();
}
}
let mut clippy_cmd = cmd_runner.cargo("clippy", bin_name, output.as_deref_mut());
// `--profile test` is required to also check code with `#[cfg(test)]`.
if FORCE_STRICT_CLIPPY || self.strict_clippy() {
clippy_cmd.args(["--profile", "test", "--", "-D", "warnings"]);
} else {
clippy_cmd.args(["--profile", "test"]);
}
let clippy_success = clippy_cmd.run("cargo clippy …")?;
let run_success = run_bin(bin_name, output, cmd_runner)?;
Ok(clippy_success && run_success)
}
/// Compile, check and run the exercise.
/// The output is written to the `output` buffer after clearing it.
#[inline]
fn run_exercise(&self, output: Option<&mut Vec<u8>>, cmd_runner: &CmdRunner) -> Result<bool> {
self.run::<false>(self.name(), output, cmd_runner)
}
/// Compile, check and run the exercise's solution.
/// The output is written to the `output` buffer after clearing it.
fn run_solution(&self, output: Option<&mut Vec<u8>>, cmd_runner: &CmdRunner) -> Result<bool> {
let name = self.name();
let mut bin_name = String::with_capacity(name.len() + 4);
bin_name.push_str(name);
bin_name.push_str("_sol");
self.run::<true>(&bin_name, output, cmd_runner)
}
fn sol_path(&self) -> String {
let name = self.name();
let mut path = if let Some(dir) = self.dir() {
// 14 = 10 + 1 + 3
// solutions/ + / + .rs
let mut path = String::with_capacity(14 + dir.len() + name.len());
path.push_str("solutions/");
path.push_str(dir);
path.push('/');
path
} else {
// 13 = 10 + 3
// solutions/ + .rs
let mut path = String::with_capacity(13 + name.len());
path.push_str("solutions/");
path
};
path.push_str(name);
path.push_str(".rs");
path
}
}
impl RunnableExercise for Exercise {
#[inline]
fn name(&self) -> &str {
self.name
}
#[inline]
fn dir(&self) -> Option<&str> {
self.dir
}
#[inline]
fn strict_clippy(&self) -> bool {
self.strict_clippy
}
#[inline]
fn test(&self) -> bool {
self.test
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/src/app_state.rs | src/app_state.rs | use anyhow::{Context, Error, Result, bail};
use crossterm::{QueueableCommand, cursor, terminal};
use std::{
collections::HashSet,
env,
fs::{File, OpenOptions},
io::{Read, Seek, StdoutLock, Write},
path::{MAIN_SEPARATOR_STR, Path},
process::{Command, Stdio},
sync::{
atomic::{AtomicUsize, Ordering::Relaxed},
mpsc,
},
thread,
};
use crate::{
clear_terminal,
cmd::CmdRunner,
embedded::EMBEDDED_FILES,
exercise::{Exercise, RunnableExercise},
info_file::ExerciseInfo,
term::{self, CheckProgressVisualizer},
};
const STATE_FILE_NAME: &str = ".rustlings-state.txt";
const DEFAULT_CHECK_PARALLELISM: usize = 8;
#[must_use]
pub enum ExercisesProgress {
// All exercises are done.
AllDone,
// A new exercise is now pending.
NewPending,
// The current exercise is still pending.
CurrentPending,
}
pub enum StateFileStatus {
Read,
NotRead,
}
#[derive(Clone, Copy)]
pub enum CheckProgress {
None,
Checking,
Done,
Pending,
}
pub struct AppState {
current_exercise_ind: usize,
exercises: Vec<Exercise>,
// Caches the number of done exercises to avoid iterating over all exercises every time.
n_done: u16,
final_message: String,
state_file: File,
// Preallocated buffer for reading and writing the state file.
file_buf: Vec<u8>,
official_exercises: bool,
cmd_runner: CmdRunner,
emit_file_links: bool,
}
impl AppState {
pub fn new(
exercise_infos: Vec<ExerciseInfo>,
final_message: String,
) -> Result<(Self, StateFileStatus)> {
let cmd_runner = CmdRunner::build()?;
let mut state_file = OpenOptions::new()
.create(true)
.read(true)
.write(true)
.truncate(false)
.open(STATE_FILE_NAME)
.with_context(|| {
format!("Failed to open or create the state file {STATE_FILE_NAME}")
})?;
let dir_canonical_path = term::canonicalize("exercises");
let mut exercises = exercise_infos
.into_iter()
.map(|exercise_info| {
// Leaking to be able to borrow in the watch mode `Table`.
// Leaking is not a problem because the `AppState` instance lives until
// the end of the program.
let path = exercise_info.path().leak();
let name = exercise_info.name.leak();
let dir = exercise_info.dir.map(|dir| &*dir.leak());
let hint = exercise_info.hint.leak().trim_ascii();
let canonical_path = dir_canonical_path.as_deref().map(|dir_canonical_path| {
let mut canonical_path;
if let Some(dir) = dir {
canonical_path = String::with_capacity(
2 + dir_canonical_path.len() + dir.len() + name.len(),
);
canonical_path.push_str(dir_canonical_path);
canonical_path.push_str(MAIN_SEPARATOR_STR);
canonical_path.push_str(dir);
} else {
canonical_path =
String::with_capacity(1 + dir_canonical_path.len() + name.len());
canonical_path.push_str(dir_canonical_path);
}
canonical_path.push_str(MAIN_SEPARATOR_STR);
canonical_path.push_str(name);
canonical_path.push_str(".rs");
canonical_path
});
Exercise {
dir,
name,
path,
canonical_path,
test: exercise_info.test,
strict_clippy: exercise_info.strict_clippy,
hint,
// Updated below.
done: false,
}
})
.collect::<Vec<_>>();
let mut current_exercise_ind = 0;
let mut n_done = 0;
let mut file_buf = Vec::with_capacity(2048);
let state_file_status = 'block: {
if state_file.read_to_end(&mut file_buf).is_err() {
break 'block StateFileStatus::NotRead;
}
// See `Self::write` for more information about the file format.
let mut lines = file_buf.split(|c| *c == b'\n').skip(2);
let Some(current_exercise_name) = lines.next() else {
break 'block StateFileStatus::NotRead;
};
if current_exercise_name.is_empty() || lines.next().is_none() {
break 'block StateFileStatus::NotRead;
}
let mut done_exercises = HashSet::with_capacity(exercises.len());
for done_exercise_name in lines {
if done_exercise_name.is_empty() {
break;
}
done_exercises.insert(done_exercise_name);
}
for (ind, exercise) in exercises.iter_mut().enumerate() {
if done_exercises.contains(exercise.name.as_bytes()) {
exercise.done = true;
n_done += 1;
}
if exercise.name.as_bytes() == current_exercise_name {
current_exercise_ind = ind;
}
}
StateFileStatus::Read
};
file_buf.clear();
file_buf.extend_from_slice(STATE_FILE_HEADER);
let slf = Self {
current_exercise_ind,
exercises,
n_done,
final_message,
state_file,
file_buf,
official_exercises: !Path::new("info.toml").exists(),
cmd_runner,
// VS Code has its own file link handling
emit_file_links: env::var_os("TERM_PROGRAM").is_none_or(|v| v != "vscode"),
};
Ok((slf, state_file_status))
}
#[inline]
pub fn current_exercise_ind(&self) -> usize {
self.current_exercise_ind
}
#[inline]
pub fn exercises(&self) -> &[Exercise] {
&self.exercises
}
#[inline]
pub fn n_done(&self) -> u16 {
self.n_done
}
#[inline]
pub fn n_pending(&self) -> u16 {
self.exercises.len() as u16 - self.n_done
}
#[inline]
pub fn current_exercise(&self) -> &Exercise {
&self.exercises[self.current_exercise_ind]
}
#[inline]
pub fn cmd_runner(&self) -> &CmdRunner {
&self.cmd_runner
}
#[inline]
pub fn emit_file_links(&self) -> bool {
self.emit_file_links
}
// Write the state file.
// The file's format is very simple:
// - The first line is a comment.
// - The second line is an empty line.
// - The third line is the name of the current exercise. It must end with `\n` even if there
// are no done exercises.
// - The fourth line is an empty line.
// - All remaining lines are the names of done exercises.
fn write(&mut self) -> Result<()> {
self.file_buf.truncate(STATE_FILE_HEADER.len());
self.file_buf
.extend_from_slice(self.current_exercise().name.as_bytes());
self.file_buf.push(b'\n');
for exercise in &self.exercises {
if exercise.done {
self.file_buf.push(b'\n');
self.file_buf.extend_from_slice(exercise.name.as_bytes());
}
}
self.state_file
.rewind()
.with_context(|| format!("Failed to rewind the state file {STATE_FILE_NAME}"))?;
self.state_file
.set_len(0)
.with_context(|| format!("Failed to truncate the state file {STATE_FILE_NAME}"))?;
self.state_file
.write_all(&self.file_buf)
.with_context(|| format!("Failed to write the state file {STATE_FILE_NAME}"))?;
Ok(())
}
pub fn set_current_exercise_ind(&mut self, exercise_ind: usize) -> Result<()> {
if exercise_ind == self.current_exercise_ind {
return Ok(());
}
if exercise_ind >= self.exercises.len() {
bail!(BAD_INDEX_ERR);
}
self.current_exercise_ind = exercise_ind;
self.write()
}
pub fn set_current_exercise_by_name(&mut self, name: &str) -> Result<()> {
// O(N) is fine since this method is used only once until the program exits.
// Building a hashmap would have more overhead.
self.current_exercise_ind = self
.exercises
.iter()
.position(|exercise| exercise.name == name)
.with_context(|| format!("No exercise found for '{name}'!"))?;
self.write()
}
// Set the status of an exercise without saving. Returns `true` if the
// status actually changed (and thus needs saving later).
pub fn set_status(&mut self, exercise_ind: usize, done: bool) -> Result<bool> {
let exercise = self
.exercises
.get_mut(exercise_ind)
.context(BAD_INDEX_ERR)?;
if exercise.done == done {
return Ok(false);
}
exercise.done = done;
if done {
self.n_done += 1;
} else {
self.n_done -= 1;
}
Ok(true)
}
// Set the status of an exercise to "pending" and save.
pub fn set_pending(&mut self, exercise_ind: usize) -> Result<()> {
if self.set_status(exercise_ind, false)? {
self.write()?;
}
Ok(())
}
// Official exercises: Dump the original file from the binary.
// Community exercises: Reset the exercise file with `git stash`.
fn reset(&self, exercise_ind: usize, path: &str) -> Result<()> {
if self.official_exercises {
return EMBEDDED_FILES
.write_exercise_to_disk(exercise_ind, path)
.with_context(|| format!("Failed to reset the exercise {path}"));
}
let output = Command::new("git")
.arg("stash")
.arg("push")
.arg("--")
.arg(path)
.stdin(Stdio::null())
.stdout(Stdio::null())
.output()
.with_context(|| format!("Failed to run `git stash push -- {path}`"))?;
if !output.status.success() {
bail!(
"`git stash push -- {path}` didn't run successfully: {}",
String::from_utf8_lossy(&output.stderr),
);
}
Ok(())
}
pub fn reset_current_exercise(&mut self) -> Result<&'static str> {
self.set_pending(self.current_exercise_ind)?;
let exercise = self.current_exercise();
self.reset(self.current_exercise_ind, exercise.path)?;
Ok(exercise.path)
}
// Reset the exercise by index and return its name.
pub fn reset_exercise_by_ind(&mut self, exercise_ind: usize) -> Result<&'static str> {
if exercise_ind >= self.exercises.len() {
bail!(BAD_INDEX_ERR);
}
self.set_pending(exercise_ind)?;
let exercise = &self.exercises[exercise_ind];
self.reset(exercise_ind, exercise.path)?;
Ok(exercise.name)
}
// Return the index of the next pending exercise or `None` if all exercises are done.
fn next_pending_exercise_ind(&self) -> Option<usize> {
let next_ind = self.current_exercise_ind + 1;
self.exercises
// If the exercise done isn't the last, search for pending exercises after it.
.get(next_ind..)
.and_then(|later_exercises| {
later_exercises
.iter()
.position(|exercise| !exercise.done)
.map(|ind| next_ind + ind)
})
// Search from the start.
.or_else(|| {
self.exercises[..self.current_exercise_ind]
.iter()
.position(|exercise| !exercise.done)
})
}
/// Official exercises: Dump the solution file from the binary and return its path.
/// Community exercises: Check if a solution file exists and return its path in that case.
pub fn current_solution_path(&self) -> Result<Option<String>> {
if cfg!(debug_assertions) {
return Ok(None);
}
let current_exercise = self.current_exercise();
if self.official_exercises {
EMBEDDED_FILES
.write_solution_to_disk(self.current_exercise_ind, current_exercise.name)
.map(Some)
} else {
let sol_path = current_exercise.sol_path();
if Path::new(&sol_path).exists() {
return Ok(Some(sol_path));
}
Ok(None)
}
}
fn check_all_exercises_impl(&mut self, stdout: &mut StdoutLock) -> Result<Option<usize>> {
let term_width = terminal::size()
.context("Failed to get the terminal size")?
.0;
let mut progress_visualizer = CheckProgressVisualizer::build(stdout, term_width)?;
let next_exercise_ind = AtomicUsize::new(0);
let mut progresses = vec![CheckProgress::None; self.exercises.len()];
thread::scope(|s| {
let (exercise_progress_sender, exercise_progress_receiver) = mpsc::channel();
let n_threads = thread::available_parallelism()
.map_or(DEFAULT_CHECK_PARALLELISM, |count| count.get());
for _ in 0..n_threads {
let exercise_progress_sender = exercise_progress_sender.clone();
let next_exercise_ind = &next_exercise_ind;
let slf = &self;
thread::Builder::new()
.spawn_scoped(s, move || {
loop {
let exercise_ind = next_exercise_ind.fetch_add(1, Relaxed);
let Some(exercise) = slf.exercises.get(exercise_ind) else {
// No more exercises.
break;
};
if exercise_progress_sender
.send((exercise_ind, CheckProgress::Checking))
.is_err()
{
break;
};
let success = exercise.run_exercise(None, &slf.cmd_runner);
let progress = match success {
Ok(true) => CheckProgress::Done,
Ok(false) => CheckProgress::Pending,
Err(_) => CheckProgress::None,
};
if exercise_progress_sender
.send((exercise_ind, progress))
.is_err()
{
break;
}
}
})
.context("Failed to spawn a thread to check all exercises")?;
}
// Drop this sender to detect when the last thread is done.
drop(exercise_progress_sender);
while let Ok((exercise_ind, progress)) = exercise_progress_receiver.recv() {
progresses[exercise_ind] = progress;
progress_visualizer.update(&progresses)?;
}
Ok::<_, Error>(())
})?;
let mut first_pending_exercise_ind = None;
for exercise_ind in 0..progresses.len() {
match progresses[exercise_ind] {
CheckProgress::Done => {
self.set_status(exercise_ind, true)?;
}
CheckProgress::Pending => {
self.set_status(exercise_ind, false)?;
if first_pending_exercise_ind.is_none() {
first_pending_exercise_ind = Some(exercise_ind);
}
}
CheckProgress::None | CheckProgress::Checking => {
// If we got an error while checking all exercises in parallel,
// it could be because we exceeded the limit of open file descriptors.
// Therefore, try running exercises with errors sequentially.
progresses[exercise_ind] = CheckProgress::Checking;
progress_visualizer.update(&progresses)?;
let exercise = &self.exercises[exercise_ind];
let success = exercise.run_exercise(None, &self.cmd_runner)?;
if success {
progresses[exercise_ind] = CheckProgress::Done;
} else {
progresses[exercise_ind] = CheckProgress::Pending;
if first_pending_exercise_ind.is_none() {
first_pending_exercise_ind = Some(exercise_ind);
}
}
self.set_status(exercise_ind, success)?;
progress_visualizer.update(&progresses)?;
}
}
}
self.write()?;
Ok(first_pending_exercise_ind)
}
// Return the exercise index of the first pending exercise found.
pub fn check_all_exercises(&mut self, stdout: &mut StdoutLock) -> Result<Option<usize>> {
stdout.queue(cursor::Hide)?;
let res = self.check_all_exercises_impl(stdout);
stdout.queue(cursor::Show)?;
res
}
/// Mark the current exercise as done and move on to the next pending exercise if one exists.
/// If all exercises are marked as done, run all of them to make sure that they are actually
/// done. If an exercise which is marked as done fails, mark it as pending and continue on it.
pub fn done_current_exercise<const CLEAR_BEFORE_FINAL_CHECK: bool>(
&mut self,
stdout: &mut StdoutLock,
) -> Result<ExercisesProgress> {
let exercise = &mut self.exercises[self.current_exercise_ind];
if !exercise.done {
exercise.done = true;
self.n_done += 1;
}
if let Some(ind) = self.next_pending_exercise_ind() {
self.set_current_exercise_ind(ind)?;
return Ok(ExercisesProgress::NewPending);
}
if CLEAR_BEFORE_FINAL_CHECK {
clear_terminal(stdout)?;
} else {
stdout.write_all(b"\n")?;
}
if let Some(first_pending_exercise_ind) = self.check_all_exercises(stdout)? {
self.set_current_exercise_ind(first_pending_exercise_ind)?;
return Ok(ExercisesProgress::NewPending);
}
self.render_final_message(stdout)?;
Ok(ExercisesProgress::AllDone)
}
pub fn render_final_message(&self, stdout: &mut StdoutLock) -> Result<()> {
clear_terminal(stdout)?;
stdout.write_all(FENISH_LINE.as_bytes())?;
let final_message = self.final_message.trim_ascii();
if !final_message.is_empty() {
stdout.write_all(final_message.as_bytes())?;
stdout.write_all(b"\n")?;
}
Ok(())
}
}
const BAD_INDEX_ERR: &str = "The current exercise index is higher than the number of exercises";
const STATE_FILE_HEADER: &[u8] = b"DON'T EDIT THIS FILE!\n\n";
const FENISH_LINE: &str = "+----------------------------------------------------+
| You made it to the Fe-nish line! |
+-------------------------- ------------------------+
\\/\x1b[31m
▒▒ ▒▒▒▒▒▒▒▒ ▒▒▒▒▒▒▒▒ ▒▒
▒▒▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒▒▒
▒▒▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒▒▒
░░▒▒▒▒░░▒▒ ▒▒ ▒▒ ▒▒ ▒▒░░▒▒▒▒
▓▓▓▓▓▓▓▓ ▓▓ ▓▓██ ▓▓ ▓▓██ ▓▓ ▓▓▓▓▓▓▓▓
▒▒▒▒ ▒▒ ████ ▒▒ ████ ▒▒░░ ▒▒▒▒
▒▒ ▒▒▒▒▒▒ ▒▒▒▒▒▒ ▒▒▒▒▒▒ ▒▒
▒▒▒▒▒▒▒▒▒▒▓▓▓▓▓▓▒▒▒▒▒▒▒▒▓▓▓▓▓▓▒▒▒▒▒▒▒▒
▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒
▒▒ ▒▒▒▒▒▒▒▒▒▒██████▒▒▒▒▒▒▒▒▒▒ ▒▒
▒▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
▒▒ ▒▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒ ▒▒
▒▒ ▒▒ ▒▒ ▒▒ ▒▒ ▒▒
▒▒ ▒▒ ▒▒ ▒▒\x1b[0m
";
#[cfg(test)]
mod tests {
use super::*;
fn dummy_exercise() -> Exercise {
Exercise {
dir: None,
name: "0",
path: "exercises/0.rs",
canonical_path: None,
test: false,
strict_clippy: false,
hint: "",
done: false,
}
}
#[test]
fn next_pending_exercise() {
let mut app_state = AppState {
current_exercise_ind: 0,
exercises: vec![dummy_exercise(), dummy_exercise(), dummy_exercise()],
n_done: 0,
final_message: String::new(),
state_file: tempfile::tempfile().unwrap(),
file_buf: Vec::new(),
official_exercises: true,
cmd_runner: CmdRunner::build().unwrap(),
emit_file_links: true,
};
let mut assert = |done: [bool; 3], expected: [Option<usize>; 3]| {
for (exercise, done) in app_state.exercises.iter_mut().zip(done) {
exercise.done = done;
}
for (ind, expected) in expected.into_iter().enumerate() {
app_state.current_exercise_ind = ind;
assert_eq!(
app_state.next_pending_exercise_ind(),
expected,
"done={done:?}, ind={ind}",
);
}
};
assert([true, true, true], [None, None, None]);
assert([false, false, false], [Some(1), Some(2), Some(0)]);
assert([false, true, true], [None, Some(0), Some(0)]);
assert([true, false, true], [Some(1), None, Some(1)]);
assert([true, true, false], [Some(2), Some(2), None]);
assert([true, false, false], [Some(1), Some(2), Some(1)]);
assert([false, true, false], [Some(2), Some(2), Some(0)]);
assert([false, false, true], [Some(1), Some(0), Some(0)]);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/src/watch.rs | src/watch.rs | use anyhow::{Error, Result};
use notify::{Config, RecommendedWatcher, RecursiveMode, Watcher};
use std::{
io::{self, Write},
path::Path,
sync::{
atomic::{AtomicBool, Ordering::Relaxed},
mpsc::channel,
},
time::Duration,
};
use crate::{
app_state::{AppState, ExercisesProgress},
list,
};
use self::{notify_event::NotifyEventHandler, state::WatchState, terminal_event::InputEvent};
mod notify_event;
mod state;
mod terminal_event;
static EXERCISE_RUNNING: AtomicBool = AtomicBool::new(false);
// Private unit type to force using the constructor function.
#[must_use = "When the guard is dropped, the input is unpaused"]
pub struct InputPauseGuard(());
impl InputPauseGuard {
#[inline]
pub fn scoped_pause() -> Self {
EXERCISE_RUNNING.store(true, Relaxed);
Self(())
}
}
impl Drop for InputPauseGuard {
#[inline]
fn drop(&mut self) {
EXERCISE_RUNNING.store(false, Relaxed);
}
}
enum WatchEvent {
Input(InputEvent),
FileChange { exercise_ind: usize },
TerminalResize { width: u16 },
NotifyErr(notify::Error),
TerminalEventErr(io::Error),
}
/// Returned by the watch mode to indicate what to do afterwards.
#[must_use]
enum WatchExit {
/// Exit the program.
Shutdown,
/// Enter the list mode and restart the watch mode afterwards.
List,
}
fn run_watch(
app_state: &mut AppState,
notify_exercise_names: Option<&'static [&'static [u8]]>,
) -> Result<WatchExit> {
let (watch_event_sender, watch_event_receiver) = channel();
let mut manual_run = false;
// Prevent dropping the guard until the end of the function.
// Otherwise, the file watcher exits.
let _watcher_guard = if let Some(exercise_names) = notify_exercise_names {
let notify_event_handler =
NotifyEventHandler::build(watch_event_sender.clone(), exercise_names)?;
let mut watcher = RecommendedWatcher::new(
notify_event_handler,
Config::default()
.with_follow_symlinks(false)
.with_poll_interval(Duration::from_secs(1)),
)
.inspect_err(|_| eprintln!("{NOTIFY_ERR}"))?;
watcher
.watch(Path::new("exercises"), RecursiveMode::Recursive)
.inspect_err(|_| eprintln!("{NOTIFY_ERR}"))?;
Some(watcher)
} else {
manual_run = true;
None
};
let mut watch_state = WatchState::build(app_state, watch_event_sender, manual_run)?;
let mut stdout = io::stdout().lock();
watch_state.run_current_exercise(&mut stdout)?;
while let Ok(event) = watch_event_receiver.recv() {
match event {
WatchEvent::Input(InputEvent::Next) => match watch_state.next_exercise(&mut stdout)? {
ExercisesProgress::AllDone => break,
ExercisesProgress::NewPending => watch_state.run_current_exercise(&mut stdout)?,
ExercisesProgress::CurrentPending => (),
},
WatchEvent::Input(InputEvent::Run) => watch_state.run_current_exercise(&mut stdout)?,
WatchEvent::Input(InputEvent::Hint) => watch_state.show_hint(&mut stdout)?,
WatchEvent::Input(InputEvent::List) => return Ok(WatchExit::List),
WatchEvent::Input(InputEvent::CheckAll) => match watch_state
.check_all_exercises(&mut stdout)?
{
ExercisesProgress::AllDone => break,
ExercisesProgress::NewPending => watch_state.run_current_exercise(&mut stdout)?,
ExercisesProgress::CurrentPending => watch_state.render(&mut stdout)?,
},
WatchEvent::Input(InputEvent::Reset) => watch_state.reset_exercise(&mut stdout)?,
WatchEvent::Input(InputEvent::Quit) => {
stdout.write_all(QUIT_MSG)?;
break;
}
WatchEvent::FileChange { exercise_ind } => {
watch_state.handle_file_change(exercise_ind, &mut stdout)?;
}
WatchEvent::TerminalResize { width } => {
watch_state.update_term_width(width, &mut stdout)?;
}
WatchEvent::NotifyErr(e) => return Err(Error::from(e).context(NOTIFY_ERR)),
WatchEvent::TerminalEventErr(e) => {
return Err(Error::from(e).context("Terminal event listener failed"));
}
}
}
Ok(WatchExit::Shutdown)
}
fn watch_list_loop(
app_state: &mut AppState,
notify_exercise_names: Option<&'static [&'static [u8]]>,
) -> Result<()> {
loop {
match run_watch(app_state, notify_exercise_names)? {
WatchExit::Shutdown => break Ok(()),
// It is much easier to exit the watch mode, launch the list mode and then restart
// the watch mode instead of trying to pause the watch threads and correct the
// watch state.
WatchExit::List => list::list(app_state)?,
}
}
}
/// `notify_exercise_names` as None activates the manual run mode.
pub fn watch(
app_state: &mut AppState,
notify_exercise_names: Option<&'static [&'static [u8]]>,
) -> Result<()> {
#[cfg(not(windows))]
{
let stdin_fd = rustix::stdio::stdin();
let mut termios = rustix::termios::tcgetattr(stdin_fd)?;
let original_local_modes = termios.local_modes;
// Disable stdin line buffering and hide input.
termios.local_modes -=
rustix::termios::LocalModes::ICANON | rustix::termios::LocalModes::ECHO;
rustix::termios::tcsetattr(stdin_fd, rustix::termios::OptionalActions::Now, &termios)?;
let res = watch_list_loop(app_state, notify_exercise_names);
termios.local_modes = original_local_modes;
rustix::termios::tcsetattr(stdin_fd, rustix::termios::OptionalActions::Now, &termios)?;
res
}
#[cfg(windows)]
watch_list_loop(app_state, notify_exercise_names)
}
const QUIT_MSG: &[u8] = b"
We hope you're enjoying learning Rust!
If you want to continue working on the exercises at a later point, you can simply run `rustlings` again in this directory.
";
const NOTIFY_ERR: &str = "
The automatic detection of exercise file changes failed :(
Please try running `rustlings` again.
If you keep getting this error, run `rustlings --manual-run` to deactivate the file watcher.
You need to manually trigger running the current exercise using `r` then.
";
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/src/run.rs | src/run.rs | use anyhow::Result;
use crossterm::{
QueueableCommand,
style::{Color, ResetColor, SetForegroundColor},
};
use std::{
io::{self, Write},
process::ExitCode,
};
use crate::{
app_state::{AppState, ExercisesProgress},
exercise::{OUTPUT_CAPACITY, RunnableExercise, solution_link_line},
};
pub fn run(app_state: &mut AppState) -> Result<ExitCode> {
let exercise = app_state.current_exercise();
let mut output = Vec::with_capacity(OUTPUT_CAPACITY);
let success = exercise.run_exercise(Some(&mut output), app_state.cmd_runner())?;
let mut stdout = io::stdout().lock();
stdout.write_all(&output)?;
if !success {
app_state.set_pending(app_state.current_exercise_ind())?;
stdout.write_all(b"Ran ")?;
app_state
.current_exercise()
.terminal_file_link(&mut stdout, app_state.emit_file_links())?;
stdout.write_all(b" with errors\n")?;
return Ok(ExitCode::FAILURE);
}
stdout.queue(SetForegroundColor(Color::Green))?;
stdout.write_all("✓ Successfully ran ".as_bytes())?;
stdout.write_all(exercise.path.as_bytes())?;
stdout.queue(ResetColor)?;
stdout.write_all(b"\n")?;
if let Some(solution_path) = app_state.current_solution_path()? {
stdout.write_all(b"\n")?;
solution_link_line(&mut stdout, &solution_path, app_state.emit_file_links())?;
stdout.write_all(b"\n")?;
}
match app_state.done_current_exercise::<false>(&mut stdout)? {
ExercisesProgress::NewPending | ExercisesProgress::CurrentPending => {
stdout.write_all(b"Next exercise: ")?;
app_state
.current_exercise()
.terminal_file_link(&mut stdout, app_state.emit_file_links())?;
stdout.write_all(b"\n")?;
}
ExercisesProgress::AllDone => (),
}
Ok(ExitCode::SUCCESS)
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/src/init.rs | src/init.rs | use anyhow::{Context, Result, bail};
use crossterm::{
QueueableCommand,
style::{Attribute, Color, ResetColor, SetAttribute, SetForegroundColor},
};
use serde::Deserialize;
use std::{
env::set_current_dir,
fs::{self, create_dir},
io::{self, Write},
path::{Path, PathBuf},
process::{Command, Stdio},
};
use crate::{
cargo_toml::updated_cargo_toml, embedded::EMBEDDED_FILES, exercise::RunnableExercise,
info_file::InfoFile, term::press_enter_prompt,
};
#[derive(Deserialize)]
struct CargoLocateProject {
root: PathBuf,
}
pub fn init() -> Result<()> {
let rustlings_dir = Path::new("rustlings");
if rustlings_dir.exists() {
bail!(RUSTLINGS_DIR_ALREADY_EXISTS_ERR);
}
let locate_project_output = Command::new("cargo")
.arg("locate-project")
.arg("-q")
.arg("--workspace")
.stdin(Stdio::null())
.stderr(Stdio::null())
.output()
.context(
"Failed to run the command `cargo locate-project …`\n\
Did you already install Rust?\n\
Try running `cargo --version` to diagnose the problem.",
)?;
if !Command::new("cargo")
.arg("clippy")
.arg("--version")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.context("Failed to run the command `cargo clippy --version`")?
.success()
{
bail!(
"Clippy, the official Rust linter, is missing.\n\
Please install it first before initializing Rustlings."
)
}
let mut stdout = io::stdout().lock();
let mut init_git = true;
if locate_project_output.status.success() {
if Path::new("exercises").exists() && Path::new("solutions").exists() {
bail!(IN_INITIALIZED_DIR_ERR);
}
let workspace_manifest =
serde_json::de::from_slice::<CargoLocateProject>(&locate_project_output.stdout)
.context(
"Failed to read the field `root` from the output of `cargo locate-project …`",
)?
.root;
let workspace_manifest_content = fs::read_to_string(&workspace_manifest)
.with_context(|| format!("Failed to read the file {}", workspace_manifest.display()))?;
if !workspace_manifest_content.contains("[workspace]")
&& !workspace_manifest_content.contains("workspace.")
{
bail!(
"The current directory is already part of a Cargo project.\n\
Please initialize Rustlings in a different directory"
);
}
stdout.write_all(b"This command will create the directory `rustlings/` as a member of this Cargo workspace.\n\
Press ENTER to continue ")?;
press_enter_prompt(&mut stdout)?;
// Make sure "rustlings" is added to `workspace.members` by making
// Cargo initialize a new project.
let status = Command::new("cargo")
.arg("new")
.arg("-q")
.arg("--vcs")
.arg("none")
.arg("rustlings")
.stdin(Stdio::null())
.stdout(Stdio::null())
.status()?;
if !status.success() {
bail!(
"Failed to initialize a new Cargo workspace member.\n\
Please initialize Rustlings in a different directory"
);
}
stdout.write_all(b"The directory `rustlings` has been added to `workspace.members` in the `Cargo.toml` file of this Cargo workspace.\n")?;
fs::remove_dir_all("rustlings")
.context("Failed to remove the temporary directory `rustlings/`")?;
init_git = false;
} else {
stdout.write_all(b"This command will create the directory `rustlings/` which will contain the exercises.\n\
Press ENTER to continue ")?;
press_enter_prompt(&mut stdout)?;
}
create_dir(rustlings_dir).context("Failed to create the `rustlings/` directory")?;
set_current_dir(rustlings_dir)
.context("Failed to change the current directory to `rustlings/`")?;
let info_file = InfoFile::parse()?;
EMBEDDED_FILES
.init_exercises_dir(&info_file.exercises)
.context("Failed to initialize the `rustlings/exercises` directory")?;
create_dir("solutions").context("Failed to create the `solutions/` directory")?;
fs::write(
"solutions/README.md",
include_bytes!("../solutions/README.md"),
)
.context("Failed to create the file rustlings/solutions/README.md")?;
for dir in EMBEDDED_FILES.exercise_dirs {
let mut dir_path = String::with_capacity(10 + dir.name.len());
dir_path.push_str("solutions/");
dir_path.push_str(dir.name);
create_dir(&dir_path)
.with_context(|| format!("Failed to create the directory {dir_path}"))?;
}
for exercise_info in &info_file.exercises {
let solution_path = exercise_info.sol_path();
fs::write(&solution_path, INIT_SOLUTION_FILE)
.with_context(|| format!("Failed to create the file {solution_path}"))?;
}
let current_cargo_toml = include_str!("../dev-Cargo.toml");
// Skip the first line (comment).
let newline_ind = current_cargo_toml
.as_bytes()
.iter()
.position(|c| *c == b'\n')
.context("The embedded `Cargo.toml` is empty or contains only one line")?;
let current_cargo_toml = current_cargo_toml
.get(newline_ind + 1..)
.context("The embedded `Cargo.toml` contains only one line")?;
let updated_cargo_toml = updated_cargo_toml(&info_file.exercises, current_cargo_toml, b"")
.context("Failed to generate `Cargo.toml`")?;
fs::write("Cargo.toml", updated_cargo_toml)
.context("Failed to create the file `rustlings/Cargo.toml`")?;
fs::write("rust-analyzer.toml", RUST_ANALYZER_TOML)
.context("Failed to create the file `rustlings/rust-analyzer.toml`")?;
fs::write(".gitignore", GITIGNORE)
.context("Failed to create the file `rustlings/.gitignore`")?;
create_dir(".vscode").context("Failed to create the directory `rustlings/.vscode`")?;
fs::write(".vscode/extensions.json", VS_CODE_EXTENSIONS_JSON)
.context("Failed to create the file `rustlings/.vscode/extensions.json`")?;
if init_git {
// Ignore any Git error because Git initialization is not required.
let _ = Command::new("git")
.arg("init")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
stdout.queue(SetForegroundColor(Color::Green))?;
stdout.write_all("Initialization done ✓".as_bytes())?;
stdout.queue(ResetColor)?;
stdout.write_all(b"\n\n")?;
stdout.queue(SetAttribute(Attribute::Bold))?;
stdout.write_all(POST_INIT_MSG)?;
stdout.queue(ResetColor)?;
Ok(())
}
const INIT_SOLUTION_FILE: &[u8] = b"fn main() {
// DON'T EDIT THIS SOLUTION FILE!
// It will be automatically filled after you finish the exercise.
}
";
pub const RUST_ANALYZER_TOML: &[u8] = br#"check.command = "clippy"
check.extraArgs = ["--profile", "test"]
cargo.targetDir = true
"#;
const GITIGNORE: &[u8] = b"Cargo.lock
target/
.vscode/
";
pub const VS_CODE_EXTENSIONS_JSON: &[u8] = br#"{"recommendations":["rust-lang.rust-analyzer"]}"#;
const IN_INITIALIZED_DIR_ERR: &str = "It looks like Rustlings is already initialized in this directory.
If you already initialized Rustlings, run the command `rustlings` for instructions on getting started with the exercises.
Otherwise, please run `rustlings init` again in a different directory.";
const RUSTLINGS_DIR_ALREADY_EXISTS_ERR: &str =
"A directory with the name `rustlings` already exists in the current directory.
You probably already initialized Rustlings.
Run `cd rustlings`
Then run `rustlings` again";
const POST_INIT_MSG: &[u8] = b"Run `cd rustlings` to go into the generated directory.
Then run `rustlings` to get started.
";
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/src/embedded.rs | src/embedded.rs | use anyhow::{Context, Error, Result};
use std::{
fs::{self, create_dir},
io,
};
use crate::info_file::ExerciseInfo;
/// Contains all embedded files.
pub static EMBEDDED_FILES: EmbeddedFiles = rustlings_macros::include_files!();
// Files related to one exercise.
struct ExerciseFiles {
// The content of the exercise file.
exercise: &'static [u8],
// The content of the solution file.
solution: &'static [u8],
// Index of the related `ExerciseDir` in `EmbeddedFiles::exercise_dirs`.
dir_ind: usize,
}
fn create_dir_if_not_exists(path: &str) -> Result<()> {
if let Err(e) = create_dir(path)
&& e.kind() != io::ErrorKind::AlreadyExists
{
return Err(Error::from(e).context(format!("Failed to create the directory {path}")));
}
Ok(())
}
// A directory in the `exercises/` directory.
pub struct ExerciseDir {
pub name: &'static str,
readme: &'static [u8],
}
impl ExerciseDir {
fn init_on_disk(&self) -> Result<()> {
// 20 = 10 + 10
// exercises/ + /README.md
let mut dir_path = String::with_capacity(20 + self.name.len());
dir_path.push_str("exercises/");
dir_path.push_str(self.name);
create_dir_if_not_exists(&dir_path)?;
let mut readme_path = dir_path;
readme_path.push_str("/README.md");
fs::write(&readme_path, self.readme)
.with_context(|| format!("Failed to write the file {readme_path}"))
}
}
/// All embedded files.
pub struct EmbeddedFiles {
/// The content of the `info.toml` file.
pub info_file: &'static str,
exercise_files: &'static [ExerciseFiles],
pub exercise_dirs: &'static [ExerciseDir],
}
impl EmbeddedFiles {
/// Dump all the embedded files of the `exercises/` directory.
pub fn init_exercises_dir(&self, exercise_infos: &[ExerciseInfo]) -> Result<()> {
create_dir("exercises").context("Failed to create the directory `exercises`")?;
fs::write(
"exercises/README.md",
include_bytes!("../exercises/README.md"),
)
.context("Failed to write the file exercises/README.md")?;
for dir in self.exercise_dirs {
dir.init_on_disk()?;
}
let mut exercise_path = String::with_capacity(64);
let prefix = "exercises/";
exercise_path.push_str(prefix);
for (exercise_info, exercise_files) in exercise_infos.iter().zip(self.exercise_files) {
let dir = &self.exercise_dirs[exercise_files.dir_ind];
exercise_path.truncate(prefix.len());
exercise_path.push_str(dir.name);
exercise_path.push('/');
exercise_path.push_str(&exercise_info.name);
exercise_path.push_str(".rs");
fs::write(&exercise_path, exercise_files.exercise)
.with_context(|| format!("Failed to write the exercise file {exercise_path}"))?;
}
Ok(())
}
pub fn write_exercise_to_disk(&self, exercise_ind: usize, path: &str) -> Result<()> {
let exercise_files = &self.exercise_files[exercise_ind];
let dir = &self.exercise_dirs[exercise_files.dir_ind];
dir.init_on_disk()?;
fs::write(path, exercise_files.exercise)
.with_context(|| format!("Failed to write the exercise file {path}"))
}
/// Write the solution file to disk and return its path.
pub fn write_solution_to_disk(
&self,
exercise_ind: usize,
exercise_name: &str,
) -> Result<String> {
create_dir_if_not_exists("solutions")?;
let exercise_files = &self.exercise_files[exercise_ind];
let dir = &self.exercise_dirs[exercise_files.dir_ind];
// 14 = 10 + 1 + 3
// solutions/ + / + .rs
let mut dir_path = String::with_capacity(14 + dir.name.len() + exercise_name.len());
dir_path.push_str("solutions/");
dir_path.push_str(dir.name);
create_dir_if_not_exists(&dir_path)?;
let mut solution_path = dir_path;
solution_path.push('/');
solution_path.push_str(exercise_name);
solution_path.push_str(".rs");
fs::write(&solution_path, exercise_files.solution)
.with_context(|| format!("Failed to write the solution file {solution_path}"))?;
Ok(solution_path)
}
}
#[cfg(test)]
mod tests {
use serde::Deserialize;
use super::*;
#[derive(Deserialize)]
struct ExerciseInfo {
dir: String,
}
#[derive(Deserialize)]
struct InfoFile {
exercises: Vec<ExerciseInfo>,
}
#[test]
fn dirs() {
let exercises = toml::de::from_str::<InfoFile>(EMBEDDED_FILES.info_file)
.expect("Failed to parse `info.toml`")
.exercises;
assert_eq!(exercises.len(), EMBEDDED_FILES.exercise_files.len());
for (exercise, exercise_files) in exercises.iter().zip(EMBEDDED_FILES.exercise_files) {
assert_eq!(
exercise.dir,
EMBEDDED_FILES.exercise_dirs[exercise_files.dir_ind].name,
);
}
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/src/main.rs | src/main.rs | use anyhow::{Context, Result, bail};
use app_state::StateFileStatus;
use clap::{Parser, Subcommand};
use std::{
io::{self, IsTerminal, Write},
path::Path,
process::ExitCode,
};
use term::{clear_terminal, press_enter_prompt};
use self::{app_state::AppState, dev::DevCommands, info_file::InfoFile};
mod app_state;
mod cargo_toml;
mod cmd;
mod dev;
mod embedded;
mod exercise;
mod info_file;
mod init;
mod list;
mod run;
mod term;
mod watch;
const CURRENT_FORMAT_VERSION: u8 = 1;
/// Rustlings is a collection of small exercises to get you used to writing and reading Rust code
#[derive(Parser)]
#[command(version)]
struct Args {
#[command(subcommand)]
command: Option<Subcommands>,
/// Manually run the current exercise using `r` in the watch mode.
/// Only use this if Rustlings fails to detect exercise file changes.
#[arg(long)]
manual_run: bool,
}
#[derive(Subcommand)]
enum Subcommands {
/// Initialize the official Rustlings exercises
Init,
/// Run a single exercise. Runs the next pending exercise if the exercise name is not specified
Run {
/// The name of the exercise
name: Option<String>,
},
/// Check all the exercises, marking them as done or pending accordingly.
CheckAll,
/// Reset a single exercise
Reset {
/// The name of the exercise
name: String,
},
/// Show a hint. Shows the hint of the next pending exercise if the exercise name is not specified
Hint {
/// The name of the exercise
name: Option<String>,
},
/// Commands for developing (community) Rustlings exercises
#[command(subcommand)]
Dev(DevCommands),
}
fn main() -> Result<ExitCode> {
let args = Args::parse();
if cfg!(not(debug_assertions)) && Path::new("dev/rustlings-repo.txt").exists() {
bail!("{OLD_METHOD_ERR}");
}
'priority_cmd: {
match args.command {
Some(Subcommands::Init) => init::init().context("Initialization failed")?,
Some(Subcommands::Dev(dev_command)) => dev_command.run()?,
_ => break 'priority_cmd,
}
return Ok(ExitCode::SUCCESS);
}
if !Path::new("exercises").is_dir() {
println!("{PRE_INIT_MSG}");
return Ok(ExitCode::FAILURE);
}
let info_file = InfoFile::parse()?;
if info_file.format_version > CURRENT_FORMAT_VERSION {
bail!(FORMAT_VERSION_HIGHER_ERR);
}
let (mut app_state, state_file_status) = AppState::new(
info_file.exercises,
info_file.final_message.unwrap_or_default(),
)?;
// Show the welcome message if the state file doesn't exist yet.
if let Some(welcome_message) = info_file.welcome_message {
match state_file_status {
StateFileStatus::NotRead => {
let mut stdout = io::stdout().lock();
clear_terminal(&mut stdout)?;
let welcome_message = welcome_message.trim_ascii();
write!(
stdout,
"{welcome_message}\n\n\
Press ENTER to continue "
)?;
press_enter_prompt(&mut stdout)?;
clear_terminal(&mut stdout)?;
// Flush to be able to show errors occurring before printing a newline to stdout.
stdout.flush()?;
}
StateFileStatus::Read => (),
}
}
match args.command {
None => {
if !io::stdout().is_terminal() {
bail!("Unsupported or missing terminal/TTY");
}
let notify_exercise_names = if args.manual_run {
None
} else {
// For the notify event handler thread.
// Leaking is not a problem because the slice lives until the end of the program.
Some(
&*app_state
.exercises()
.iter()
.map(|exercise| exercise.name.as_bytes())
.collect::<Vec<_>>()
.leak(),
)
};
watch::watch(&mut app_state, notify_exercise_names)?;
}
Some(Subcommands::Run { name }) => {
if let Some(name) = name {
app_state.set_current_exercise_by_name(&name)?;
}
return run::run(&mut app_state);
}
Some(Subcommands::CheckAll) => {
let mut stdout = io::stdout().lock();
if let Some(first_pending_exercise_ind) = app_state.check_all_exercises(&mut stdout)? {
if app_state.current_exercise().done {
app_state.set_current_exercise_ind(first_pending_exercise_ind)?;
}
stdout.write_all(b"\n\n")?;
let pending = app_state.n_pending();
if pending == 1 {
stdout.write_all(b"One exercise pending: ")?;
} else {
write!(
stdout,
"{pending}/{} exercises pending. The first: ",
app_state.exercises().len(),
)?;
}
app_state
.current_exercise()
.terminal_file_link(&mut stdout, app_state.emit_file_links())?;
stdout.write_all(b"\n")?;
return Ok(ExitCode::FAILURE);
} else {
app_state.render_final_message(&mut stdout)?;
}
}
Some(Subcommands::Reset { name }) => {
app_state.set_current_exercise_by_name(&name)?;
let exercise_path = app_state.reset_current_exercise()?;
println!("The exercise {exercise_path} has been reset");
}
Some(Subcommands::Hint { name }) => {
if let Some(name) = name {
app_state.set_current_exercise_by_name(&name)?;
}
println!("{}", app_state.current_exercise().hint);
}
// Handled in an earlier match.
Some(Subcommands::Init | Subcommands::Dev(_)) => (),
}
Ok(ExitCode::SUCCESS)
}
const OLD_METHOD_ERR: &str =
"You are trying to run Rustlings using the old method before version 6.
The new method doesn't include cloning the Rustlings' repository.
Please follow the instructions in `README.md`:
https://github.com/rust-lang/rustlings#getting-started";
const FORMAT_VERSION_HIGHER_ERR: &str =
"The format version specified in the `info.toml` file is higher than the last one supported.
It is possible that you have an outdated version of Rustlings.
Try to install the latest Rustlings version first.";
const PRE_INIT_MSG: &str = r"
Welcome to...
_ _ _
_ __ _ _ ___| |_| (_)_ __ __ _ ___
| '__| | | / __| __| | | '_ \ / _` / __|
| | | |_| \__ \ |_| | | | | | (_| \__ \
|_| \__,_|___/\__|_|_|_| |_|\__, |___/
|___/
The `exercises/` directory couldn't be found in the current directory.
If you are just starting with Rustlings, run the command `rustlings init` to initialize it.";
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/src/term.rs | src/term.rs | use crossterm::{
Command, QueueableCommand,
cursor::MoveTo,
style::{Attribute, Color, ResetColor, SetAttribute, SetForegroundColor},
terminal::{Clear, ClearType},
};
use std::{
fmt, fs,
io::{self, BufRead, StdoutLock, Write},
};
use crate::app_state::CheckProgress;
pub struct MaxLenWriter<'a, 'lock> {
pub stdout: &'a mut StdoutLock<'lock>,
len: usize,
max_len: usize,
}
impl<'a, 'lock> MaxLenWriter<'a, 'lock> {
#[inline]
pub fn new(stdout: &'a mut StdoutLock<'lock>, max_len: usize) -> Self {
Self {
stdout,
len: 0,
max_len,
}
}
// Additional is for emojis that take more space.
#[inline]
pub fn add_to_len(&mut self, additional: usize) {
self.len += additional;
}
}
pub trait CountedWrite<'lock> {
fn write_ascii(&mut self, ascii: &[u8]) -> io::Result<()>;
fn write_str(&mut self, unicode: &str) -> io::Result<()>;
fn stdout(&mut self) -> &mut StdoutLock<'lock>;
}
impl<'lock> CountedWrite<'lock> for MaxLenWriter<'_, 'lock> {
fn write_ascii(&mut self, ascii: &[u8]) -> io::Result<()> {
let n = ascii.len().min(self.max_len.saturating_sub(self.len));
if n > 0 {
self.stdout.write_all(&ascii[..n])?;
self.len += n;
}
Ok(())
}
fn write_str(&mut self, unicode: &str) -> io::Result<()> {
if let Some((ind, c)) = unicode
.char_indices()
.take(self.max_len.saturating_sub(self.len))
.last()
{
self.stdout
.write_all(&unicode.as_bytes()[..ind + c.len_utf8()])?;
self.len += ind + 1;
}
Ok(())
}
#[inline]
fn stdout(&mut self) -> &mut StdoutLock<'lock> {
self.stdout
}
}
impl<'a> CountedWrite<'a> for StdoutLock<'a> {
#[inline]
fn write_ascii(&mut self, ascii: &[u8]) -> io::Result<()> {
self.write_all(ascii)
}
#[inline]
fn write_str(&mut self, unicode: &str) -> io::Result<()> {
self.write_all(unicode.as_bytes())
}
#[inline]
fn stdout(&mut self) -> &mut StdoutLock<'a> {
self
}
}
pub struct CheckProgressVisualizer<'a, 'lock> {
stdout: &'a mut StdoutLock<'lock>,
n_cols: usize,
}
impl<'a, 'lock> CheckProgressVisualizer<'a, 'lock> {
const CHECKING_COLOR: Color = Color::Blue;
const DONE_COLOR: Color = Color::Green;
const PENDING_COLOR: Color = Color::Red;
pub fn build(stdout: &'a mut StdoutLock<'lock>, term_width: u16) -> io::Result<Self> {
clear_terminal(stdout)?;
stdout.write_all("Checking all exercises…\n".as_bytes())?;
// Legend
stdout.write_all(b"Color of exercise number: ")?;
stdout.queue(SetForegroundColor(Self::CHECKING_COLOR))?;
stdout.write_all(b"Checking")?;
stdout.queue(ResetColor)?;
stdout.write_all(b" - ")?;
stdout.queue(SetForegroundColor(Self::DONE_COLOR))?;
stdout.write_all(b"Done")?;
stdout.queue(ResetColor)?;
stdout.write_all(b" - ")?;
stdout.queue(SetForegroundColor(Self::PENDING_COLOR))?;
stdout.write_all(b"Pending")?;
stdout.queue(ResetColor)?;
stdout.write_all(b"\n")?;
// Exercise numbers with up to 3 digits.
// +1 because the last column doesn't end with a whitespace.
let n_cols = usize::from(term_width + 1) / 4;
Ok(Self { stdout, n_cols })
}
pub fn update(&mut self, progresses: &[CheckProgress]) -> io::Result<()> {
self.stdout.queue(MoveTo(0, 2))?;
let mut exercise_num = 1;
for exercise_progress in progresses {
match exercise_progress {
CheckProgress::None => (),
CheckProgress::Checking => {
self.stdout
.queue(SetForegroundColor(Self::CHECKING_COLOR))?;
}
CheckProgress::Done => {
self.stdout.queue(SetForegroundColor(Self::DONE_COLOR))?;
}
CheckProgress::Pending => {
self.stdout.queue(SetForegroundColor(Self::PENDING_COLOR))?;
}
}
write!(self.stdout, "{exercise_num:<3}")?;
self.stdout.queue(ResetColor)?;
if exercise_num != progresses.len() {
if exercise_num % self.n_cols == 0 {
self.stdout.write_all(b"\n")?;
} else {
self.stdout.write_all(b" ")?;
}
exercise_num += 1;
}
}
self.stdout.flush()
}
}
pub struct ProgressCounter<'a, 'lock> {
stdout: &'a mut StdoutLock<'lock>,
total: usize,
counter: usize,
}
impl<'a, 'lock> ProgressCounter<'a, 'lock> {
pub fn new(stdout: &'a mut StdoutLock<'lock>, total: usize) -> io::Result<Self> {
write!(stdout, "Progress: 0/{total}")?;
stdout.flush()?;
Ok(Self {
stdout,
total,
counter: 0,
})
}
pub fn increment(&mut self) -> io::Result<()> {
self.counter += 1;
write!(self.stdout, "\rProgress: {}/{}", self.counter, self.total)?;
self.stdout.flush()
}
}
impl Drop for ProgressCounter<'_, '_> {
fn drop(&mut self) {
let _ = self.stdout.write_all(b"\n\n");
}
}
pub fn progress_bar<'a>(
writer: &mut impl CountedWrite<'a>,
progress: u16,
total: u16,
term_width: u16,
) -> io::Result<()> {
debug_assert!(total <= 999);
debug_assert!(progress <= total);
const PREFIX: &[u8] = b"Progress: [";
const PREFIX_WIDTH: u16 = PREFIX.len() as u16;
const POSTFIX_WIDTH: u16 = "] xxx/xxx".len() as u16;
const WRAPPER_WIDTH: u16 = PREFIX_WIDTH + POSTFIX_WIDTH;
const MIN_LINE_WIDTH: u16 = WRAPPER_WIDTH + 4;
if term_width < MIN_LINE_WIDTH {
writer.write_ascii(b"Progress: ")?;
// Integers are in ASCII.
return writer.write_ascii(format!("{progress}/{total}").as_bytes());
}
let stdout = writer.stdout();
stdout.write_all(PREFIX)?;
let width = term_width - WRAPPER_WIDTH;
let filled = (width * progress) / total;
stdout.queue(SetForegroundColor(Color::Green))?;
for _ in 0..filled {
stdout.write_all(b"#")?;
}
if filled < width {
stdout.write_all(b">")?;
}
let width_minus_filled = width - filled;
if width_minus_filled > 1 {
let red_part_width = width_minus_filled - 1;
stdout.queue(SetForegroundColor(Color::Red))?;
for _ in 0..red_part_width {
stdout.write_all(b"-")?;
}
}
stdout.queue(SetForegroundColor(Color::Reset))?;
write!(stdout, "] {progress:>3}/{total}")
}
pub fn clear_terminal(stdout: &mut StdoutLock) -> io::Result<()> {
stdout
.queue(MoveTo(0, 0))?
.queue(Clear(ClearType::All))?
.queue(Clear(ClearType::Purge))
.map(|_| ())
}
pub fn press_enter_prompt(stdout: &mut StdoutLock) -> io::Result<()> {
stdout.flush()?;
io::stdin().lock().read_until(b'\n', &mut Vec::new())?;
stdout.write_all(b"\n")
}
/// Canonicalize, convert to string and remove verbatim part on Windows.
pub fn canonicalize(path: &str) -> Option<String> {
fs::canonicalize(path)
.ok()?
.into_os_string()
.into_string()
.ok()
.map(|mut path| {
// Windows itself can't handle its verbatim paths.
if cfg!(windows) && path.as_bytes().starts_with(br"\\?\") {
path.drain(..4);
}
path
})
}
pub fn file_path<'a, W: CountedWrite<'a>>(
writer: &mut W,
color: Color,
f: impl FnOnce(&mut W) -> io::Result<()>,
) -> io::Result<()> {
writer
.stdout()
.queue(SetForegroundColor(color))?
.queue(SetAttribute(Attribute::Underlined))?;
f(writer)?;
writer
.stdout()
.queue(SetForegroundColor(Color::Reset))?
.queue(SetAttribute(Attribute::NoUnderline))?;
Ok(())
}
pub fn terminal_file_link<'a>(
writer: &mut impl CountedWrite<'a>,
path: &str,
canonical_path: &str,
) -> io::Result<()> {
writer.stdout().write_all(b"\x1b]8;;file://")?;
writer.stdout().write_all(canonical_path.as_bytes())?;
writer.stdout().write_all(b"\x1b\\")?;
// Only this part is visible.
writer.write_str(path)?;
writer.stdout().write_all(b"\x1b]8;;\x1b\\")
}
pub fn write_ansi(output: &mut Vec<u8>, command: impl Command) {
struct FmtWriter<'a>(&'a mut Vec<u8>);
impl fmt::Write for FmtWriter<'_> {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.0.extend_from_slice(s.as_bytes());
Ok(())
}
}
let _ = command.write_ansi(&mut FmtWriter(output));
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/src/cmd.rs | src/cmd.rs | use anyhow::{Context, Result, bail};
use serde::Deserialize;
use std::{
io::{Read, pipe},
path::PathBuf,
process::{Command, Stdio},
};
/// Run a command with a description for a possible error and append the merged stdout and stderr.
/// The boolean in the returned `Result` is true if the command's exit status is success.
fn run_cmd(mut cmd: Command, description: &str, output: Option<&mut Vec<u8>>) -> Result<bool> {
let spawn = |mut cmd: Command| {
// NOTE: The closure drops `cmd` which prevents a pipe deadlock.
cmd.stdin(Stdio::null())
.spawn()
.with_context(|| format!("Failed to run the command `{description}`"))
};
let mut handle = if let Some(output) = output {
let (mut reader, writer) = pipe().with_context(|| {
format!("Failed to create a pipe to run the command `{description}``")
})?;
let writer_clone = writer.try_clone().with_context(|| {
format!("Failed to clone the pipe writer for the command `{description}`")
})?;
cmd.stdout(writer_clone).stderr(writer);
let handle = spawn(cmd)?;
reader
.read_to_end(output)
.with_context(|| format!("Failed to read the output of the command `{description}`"))?;
output.push(b'\n');
handle
} else {
cmd.stdout(Stdio::null()).stderr(Stdio::null());
spawn(cmd)?
};
handle
.wait()
.with_context(|| format!("Failed to wait on the command `{description}` to exit"))
.map(|status| status.success())
}
// Parses parts of the output of `cargo metadata`.
#[derive(Deserialize)]
struct CargoMetadata {
target_directory: PathBuf,
}
pub struct CmdRunner {
target_dir: PathBuf,
}
impl CmdRunner {
pub fn build() -> Result<Self> {
// Get the target directory from Cargo.
let metadata_output = Command::new("cargo")
.arg("metadata")
.arg("-q")
.arg("--format-version")
.arg("1")
.arg("--no-deps")
.stdin(Stdio::null())
.stderr(Stdio::inherit())
.output()
.context(CARGO_METADATA_ERR)?;
if !metadata_output.status.success() {
bail!("The command `cargo metadata …` failed. Are you in the `rustlings/` directory?");
}
let metadata: CargoMetadata = serde_json::de::from_slice(&metadata_output.stdout)
.context(
"Failed to read the field `target_directory` from the output of the command `cargo metadata …`",
)?;
Ok(Self {
target_dir: metadata.target_directory,
})
}
pub fn cargo<'out>(
&self,
subcommand: &str,
bin_name: &str,
output: Option<&'out mut Vec<u8>>,
) -> CargoSubcommand<'out> {
let mut cmd = Command::new("cargo");
cmd.arg(subcommand).arg("-q").arg("--bin").arg(bin_name);
// A hack to make `cargo run` work when developing Rustlings.
#[cfg(debug_assertions)]
cmd.arg("--manifest-path")
.arg("dev/Cargo.toml")
.arg("--target-dir")
.arg(&self.target_dir);
if output.is_some() {
cmd.arg("--color").arg("always");
}
CargoSubcommand { cmd, output }
}
/// The boolean in the returned `Result` is true if the command's exit status is success.
pub fn run_debug_bin(&self, bin_name: &str, output: Option<&mut Vec<u8>>) -> Result<bool> {
// 7 = "/debug/".len()
let mut bin_path =
PathBuf::with_capacity(self.target_dir.as_os_str().len() + 7 + bin_name.len());
bin_path.push(&self.target_dir);
bin_path.push("debug");
bin_path.push(bin_name);
run_cmd(Command::new(&bin_path), &bin_path.to_string_lossy(), output)
}
}
pub struct CargoSubcommand<'out> {
cmd: Command,
output: Option<&'out mut Vec<u8>>,
}
impl CargoSubcommand<'_> {
#[inline]
pub fn args<'arg, I>(&mut self, args: I) -> &mut Self
where
I: IntoIterator<Item = &'arg str>,
{
self.cmd.args(args);
self
}
/// The boolean in the returned `Result` is true if the command's exit status is success.
#[inline]
pub fn run(self, description: &str) -> Result<bool> {
run_cmd(self.cmd, description, self.output)
}
}
const CARGO_METADATA_ERR: &str = "Failed to run the command `cargo metadata …`
Did you already install Rust?
Try running `cargo --version` to diagnose the problem.";
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_run_cmd() {
let mut cmd = Command::new("echo");
cmd.arg("Hello");
let mut output = Vec::with_capacity(8);
run_cmd(cmd, "echo …", Some(&mut output)).unwrap();
assert_eq!(output, b"Hello\n\n");
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/src/dev/update.rs | src/dev/update.rs | use anyhow::{Context, Result};
use std::fs;
use crate::{
cargo_toml::updated_cargo_toml,
info_file::{ExerciseInfo, InfoFile},
};
// Update the `Cargo.toml` file.
fn update_cargo_toml(
exercise_infos: &[ExerciseInfo],
cargo_toml_path: &str,
exercise_path_prefix: &[u8],
) -> Result<()> {
let current_cargo_toml = fs::read_to_string(cargo_toml_path)
.with_context(|| format!("Failed to read the file `{cargo_toml_path}`"))?;
let updated_cargo_toml =
updated_cargo_toml(exercise_infos, ¤t_cargo_toml, exercise_path_prefix)?;
fs::write(cargo_toml_path, updated_cargo_toml)
.context("Failed to write the `Cargo.toml` file")?;
Ok(())
}
pub fn update() -> Result<()> {
let info_file = InfoFile::parse()?;
if cfg!(debug_assertions) {
// A hack to make `cargo dev update` work when developing Rustlings.
update_cargo_toml(&info_file.exercises, "dev/Cargo.toml", b"../")
.context("Failed to update the file `dev/Cargo.toml`")?;
println!("Updated `dev/Cargo.toml`");
} else {
update_cargo_toml(&info_file.exercises, "Cargo.toml", &[])
.context("Failed to update the file `Cargo.toml`")?;
println!("Updated `Cargo.toml`");
}
Ok(())
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/src/dev/check.rs | src/dev/check.rs | use anyhow::{Context, Error, Result, anyhow, bail};
use std::{
cmp::Ordering,
collections::HashSet,
fs::{self, OpenOptions, read_dir},
io::{self, Read, Write},
path::{Path, PathBuf},
process::{Command, Stdio},
thread,
};
use crate::{
CURRENT_FORMAT_VERSION,
cargo_toml::{BINS_BUFFER_CAPACITY, append_bins, bins_start_end_ind},
cmd::CmdRunner,
exercise::{OUTPUT_CAPACITY, RunnableExercise},
info_file::{ExerciseInfo, InfoFile},
term::ProgressCounter,
};
const MAX_N_EXERCISES: usize = 999;
const MAX_EXERCISE_NAME_LEN: usize = 32;
// Find a char that isn't allowed in the exercise's `name` or `dir`.
fn forbidden_char(input: &str) -> Option<char> {
input.chars().find(|c| !c.is_alphanumeric() && *c != '_')
}
// Check that the `Cargo.toml` file is up-to-date.
fn check_cargo_toml(
exercise_infos: &[ExerciseInfo],
cargo_toml_path: &str,
exercise_path_prefix: &[u8],
) -> Result<()> {
let current_cargo_toml = fs::read_to_string(cargo_toml_path)
.with_context(|| format!("Failed to read the file `{cargo_toml_path}`"))?;
let (bins_start_ind, bins_end_ind) = bins_start_end_ind(¤t_cargo_toml)?;
let old_bins = ¤t_cargo_toml.as_bytes()[bins_start_ind..bins_end_ind];
let mut new_bins = Vec::with_capacity(BINS_BUFFER_CAPACITY);
append_bins(&mut new_bins, exercise_infos, exercise_path_prefix);
if old_bins != new_bins {
if cfg!(debug_assertions) {
bail!(
"The file `dev/Cargo.toml` is outdated. Run `cargo dev update` to update it. Then run `cargo run -- dev check` again"
);
}
bail!(
"The file `Cargo.toml` is outdated. Run `rustlings dev update` to update it. Then run `rustlings dev check` again"
);
}
Ok(())
}
// Check the info of all exercises and return their paths in a set.
fn check_info_file_exercises(info_file: &InfoFile) -> Result<HashSet<PathBuf>> {
let mut names = HashSet::with_capacity(info_file.exercises.len());
let mut paths = HashSet::with_capacity(info_file.exercises.len());
let mut file_buf = String::with_capacity(1 << 14);
for exercise_info in &info_file.exercises {
let name = exercise_info.name.as_str();
if name.is_empty() {
bail!("Found an empty exercise name in `info.toml`");
}
if name.len() > MAX_EXERCISE_NAME_LEN {
bail!(
"The length of the exercise name `{name}` is bigger than the maximum {MAX_EXERCISE_NAME_LEN}"
);
}
if let Some(c) = forbidden_char(name) {
bail!("Char `{c}` in the exercise name `{name}` is not allowed");
}
if let Some(dir) = &exercise_info.dir {
if dir.is_empty() {
bail!("The exercise `{name}` has an empty dir name in `info.toml`");
}
if let Some(c) = forbidden_char(dir) {
bail!("Char `{c}` in the exercise dir `{dir}` is not allowed");
}
}
if exercise_info.hint.trim_ascii().is_empty() {
bail!(
"The exercise `{name}` has an empty hint. Please provide a hint or at least tell the user why a hint isn't needed for this exercise"
);
}
if !names.insert(name) {
bail!("The exercise name `{name}` is duplicated. Exercise names must all be unique");
}
let path = exercise_info.path();
OpenOptions::new()
.read(true)
.open(&path)
.with_context(|| format!("Failed to open the file {path}"))?
.read_to_string(&mut file_buf)
.with_context(|| format!("Failed to read the file {path}"))?;
if !file_buf.contains("fn main()") {
bail!(
"The `main` function is missing in the file `{path}`.\n\
Create at least an empty `main` function to avoid language server errors"
);
}
if !file_buf.contains("// TODO") {
bail!(
"Didn't find any `// TODO` comment in the file `{path}`.\n\
You need to have at least one such comment to guide the user."
);
}
let contains_tests = file_buf.contains("#[test]\n");
if exercise_info.test {
if !contains_tests {
bail!(
"The file `{path}` doesn't contain any tests. If you don't want to add tests to this exercise, set `test = false` for this exercise in the `info.toml` file"
);
}
} else if contains_tests {
bail!(
"The file `{path}` contains tests annotated with `#[test]` but the exercise `{name}` has `test = false` in the `info.toml` file"
);
}
file_buf.clear();
paths.insert(PathBuf::from(path));
}
Ok(paths)
}
// Check `dir` for unexpected files.
// Only Rust files in `allowed_rust_files` and `README.md` files are allowed.
// Only one level of directory nesting is allowed.
fn check_unexpected_files(dir: &str, allowed_rust_files: &HashSet<PathBuf>) -> Result<()> {
let unexpected_file = |path: &Path| {
anyhow!(
"Found the file `{}`. Only `README.md` and Rust files related to an exercise in `info.toml` are allowed in the `{dir}` directory",
path.display()
)
};
for entry in read_dir(dir).with_context(|| format!("Failed to open the `{dir}` directory"))? {
let entry = entry.with_context(|| format!("Failed to read the `{dir}` directory"))?;
if entry.file_type().unwrap().is_file() {
let path = entry.path();
let file_name = path.file_name().unwrap();
if file_name == "README.md" {
continue;
}
if !allowed_rust_files.contains(&path) {
return Err(unexpected_file(&path));
}
continue;
}
let dir_path = entry.path();
for entry in read_dir(&dir_path)
.with_context(|| format!("Failed to open the directory {}", dir_path.display()))?
{
let entry = entry
.with_context(|| format!("Failed to read the directory {}", dir_path.display()))?;
let path = entry.path();
if !entry.file_type().unwrap().is_file() {
bail!(
"Found `{}` but expected only files. Only one level of exercise nesting is allowed",
path.display()
);
}
let file_name = path.file_name().unwrap();
if file_name == "README.md" {
continue;
}
if !allowed_rust_files.contains(&path) {
return Err(unexpected_file(&path));
}
}
}
Ok(())
}
fn check_exercises_unsolved(
info_file: &'static InfoFile,
cmd_runner: &'static CmdRunner,
) -> Result<()> {
let mut stdout = io::stdout().lock();
stdout.write_all(b"Running all exercises to check that they aren't already solved...\n")?;
let handles = info_file
.exercises
.iter()
.filter_map(|exercise_info| {
if exercise_info.skip_check_unsolved {
return None;
}
Some(
thread::Builder::new()
.spawn(|| exercise_info.run_exercise(None, cmd_runner))
.map(|handle| (exercise_info.name.as_str(), handle)),
)
})
.collect::<Result<Vec<_>, _>>()
.context("Failed to spawn a thread to check if an exercise is already solved")?;
let mut progress_counter = ProgressCounter::new(&mut stdout, handles.len())?;
for (exercise_name, handle) in handles {
let Ok(result) = handle.join() else {
bail!("Panic while trying to run the exercise {exercise_name}");
};
match result {
Ok(true) => {
bail!(
"The exercise {exercise_name} is already solved.\n\
{SKIP_CHECK_UNSOLVED_HINT}",
)
}
Ok(false) => (),
Err(e) => return Err(e),
}
progress_counter.increment()?;
}
Ok(())
}
fn check_exercises(info_file: &'static InfoFile, cmd_runner: &'static CmdRunner) -> Result<()> {
match info_file.format_version.cmp(&CURRENT_FORMAT_VERSION) {
Ordering::Less => bail!(
"`format_version` < {CURRENT_FORMAT_VERSION} (supported version)\n\
Please migrate to the latest format version"
),
Ordering::Greater => bail!(
"`format_version` > {CURRENT_FORMAT_VERSION} (supported version)\n\
Try updating the Rustlings program"
),
Ordering::Equal => (),
}
let handle = thread::Builder::new()
.spawn(move || check_exercises_unsolved(info_file, cmd_runner))
.context("Failed to spawn a thread to check if any exercise is already solved")?;
let info_file_paths = check_info_file_exercises(info_file)?;
check_unexpected_files("exercises", &info_file_paths)?;
handle.join().unwrap()
}
enum SolutionCheck {
Success { sol_path: String },
MissingOptional,
RunFailure { output: Vec<u8> },
Err(Error),
}
fn check_solutions(
require_solutions: bool,
info_file: &'static InfoFile,
cmd_runner: &'static CmdRunner,
) -> Result<()> {
let mut stdout = io::stdout().lock();
stdout.write_all(b"Running all solutions...\n")?;
let handles = info_file
.exercises
.iter()
.map(|exercise_info| {
thread::Builder::new().spawn(move || {
let sol_path = exercise_info.sol_path();
if !Path::new(&sol_path).exists() {
if require_solutions {
return SolutionCheck::Err(anyhow!(
"The solution of the exercise {} is missing",
exercise_info.name,
));
}
return SolutionCheck::MissingOptional;
}
let mut output = Vec::with_capacity(OUTPUT_CAPACITY);
match exercise_info.run_solution(Some(&mut output), cmd_runner) {
Ok(true) => SolutionCheck::Success { sol_path },
Ok(false) => SolutionCheck::RunFailure { output },
Err(e) => SolutionCheck::Err(e),
}
})
})
.collect::<Result<Vec<_>, _>>()
.context("Failed to spawn a thread to check a solution")?;
let mut sol_paths = HashSet::with_capacity(info_file.exercises.len());
let mut fmt_cmd = Command::new("rustfmt");
fmt_cmd
.arg("--check")
.arg("--edition")
.arg("2024")
.arg("--color")
.arg("always")
.stdin(Stdio::null());
let mut progress_counter = ProgressCounter::new(&mut stdout, handles.len())?;
for (exercise_info, handle) in info_file.exercises.iter().zip(handles) {
let Ok(check_result) = handle.join() else {
bail!(
"Panic while trying to run the solution of the exercise {}",
exercise_info.name,
);
};
match check_result {
SolutionCheck::Success { sol_path } => {
fmt_cmd.arg(&sol_path);
sol_paths.insert(PathBuf::from(sol_path));
}
SolutionCheck::MissingOptional => (),
SolutionCheck::RunFailure { output } => {
drop(progress_counter);
stdout.write_all(&output)?;
bail!(
"Running the solution of the exercise {} failed with the error above",
exercise_info.name,
);
}
SolutionCheck::Err(e) => return Err(e),
}
progress_counter.increment()?;
}
let n_solutions = sol_paths.len();
let handle = thread::Builder::new()
.spawn(move || check_unexpected_files("solutions", &sol_paths))
.context(
"Failed to spawn a thread to check for unexpected files in the solutions directory",
)?;
if n_solutions > 0
&& !fmt_cmd
.status()
.context("Failed to run `rustfmt` on all solution files")?
.success()
{
bail!("Some solutions aren't formatted. Run `rustfmt` on them");
}
handle.join().unwrap()
}
pub fn check(require_solutions: bool) -> Result<()> {
let info_file = InfoFile::parse()?;
if info_file.exercises.len() > MAX_N_EXERCISES {
bail!("The maximum number of exercises is {MAX_N_EXERCISES}");
}
if cfg!(debug_assertions) {
// A hack to make `cargo dev check` work when developing Rustlings.
check_cargo_toml(&info_file.exercises, "dev/Cargo.toml", b"../")?;
} else {
check_cargo_toml(&info_file.exercises, "Cargo.toml", b"")?;
}
// Leaking is fine since they are used until the end of the program.
let cmd_runner = Box::leak(Box::new(CmdRunner::build()?));
let info_file = Box::leak(Box::new(info_file));
check_exercises(info_file, cmd_runner)?;
check_solutions(require_solutions, info_file, cmd_runner)?;
println!("Everything looks fine!");
Ok(())
}
const SKIP_CHECK_UNSOLVED_HINT: &str = "If this is an introduction exercise that is intended to be already solved, add `skip_check_unsolved = true` to the exercise's metadata in the `info.toml` file";
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/src/dev/new.rs | src/dev/new.rs | use anyhow::{Context, Result, bail};
use std::{
env::set_current_dir,
fs::{self, create_dir},
path::Path,
process::Command,
};
use crate::{CURRENT_FORMAT_VERSION, init::RUST_ANALYZER_TOML};
// Create a directory relative to the current directory and print its path.
fn create_rel_dir(dir_name: &str, current_dir: &str) -> Result<()> {
create_dir(dir_name)
.with_context(|| format!("Failed to create the directory {current_dir}/{dir_name}"))?;
println!("Created the directory {current_dir}/{dir_name}");
Ok(())
}
// Write a file relative to the current directory and print its path.
fn write_rel_file<C>(file_name: &str, current_dir: &str, content: C) -> Result<()>
where
C: AsRef<[u8]>,
{
fs::write(file_name, content)
.with_context(|| format!("Failed to create the file {current_dir}/{file_name}"))?;
// Space to align with `create_rel_dir`.
println!("Created the file {current_dir}/{file_name}");
Ok(())
}
pub fn new(path: &Path, no_git: bool) -> Result<()> {
let dir_path_str = path.to_string_lossy();
create_dir(path).with_context(|| format!("Failed to create the directory {dir_path_str}"))?;
println!("Created the directory {dir_path_str}");
set_current_dir(path)
.with_context(|| format!("Failed to set {dir_path_str} as the current directory"))?;
if !no_git
&& !Command::new("git")
.arg("init")
.status()
.context("Failed to run `git init`")?
.success()
{
bail!("`git init` didn't run successfully. See the possible error message above");
}
write_rel_file(".gitignore", &dir_path_str, GITIGNORE)?;
create_rel_dir("exercises", &dir_path_str)?;
create_rel_dir("solutions", &dir_path_str)?;
write_rel_file(
"info.toml",
&dir_path_str,
format!(
"{INFO_FILE_BEFORE_FORMAT_VERSION}{CURRENT_FORMAT_VERSION}{INFO_FILE_AFTER_FORMAT_VERSION}"
),
)?;
write_rel_file("Cargo.toml", &dir_path_str, CARGO_TOML)?;
write_rel_file("README.md", &dir_path_str, README)?;
write_rel_file("rust-analyzer.toml", &dir_path_str, RUST_ANALYZER_TOML)?;
create_rel_dir(".vscode", &dir_path_str)?;
write_rel_file(
".vscode/extensions.json",
&dir_path_str,
crate::init::VS_CODE_EXTENSIONS_JSON,
)?;
println!("\nInitialization done ✓");
Ok(())
}
pub const GITIGNORE: &[u8] = b"Cargo.lock
target/
.vscode/
!.vscode/extensions.json
";
const INFO_FILE_BEFORE_FORMAT_VERSION: &str =
"# The format version is an indicator of the compatibility of community exercises with the
# Rustlings program.
# The format version is not the same as the version of the Rustlings program.
# In case Rustlings makes an unavoidable breaking change to the expected format of community
# exercises, you would need to raise this version and adapt to the new format.
# Otherwise, the newest version of the Rustlings program won't be able to run these exercises.
format_version = ";
const INFO_FILE_AFTER_FORMAT_VERSION: &str = r#"
# Optional multi-line message to be shown to users when just starting with the exercises.
welcome_message = """Welcome to these community Rustlings exercises."""
# Optional multi-line message to be shown to users after finishing all exercises.
final_message = """We hope that you found the exercises helpful :D"""
# Repeat this section for every exercise.
[[exercises]]
# Exercise name which is the exercise file name without the `.rs` extension.
name = "???"
# Optional directory name to be provided if you want to organize exercises in directories.
# If `dir` is specified, the exercise path is `exercises/DIR/NAME.rs`
# Otherwise, the path is `exercises/NAME.rs`
# dir = "???"
# Rustlings expects the exercise to contain tests and run them.
# You can optionally disable testing by setting `test` to `false` (the default is `true`).
# In that case, the exercise will be considered done when it just successfully compiles.
# test = true
# Rustlings will always run Clippy on exercises.
# You can optionally set `strict_clippy` to `true` (the default is `false`) to only consider
# the exercise as done when there are no warnings left.
# strict_clippy = false
# A multi-line hint to be shown to users on request.
hint = """???"""
"#;
const CARGO_TOML: &[u8] =
br#"# Don't edit the `bin` list manually! It is updated by `rustlings dev update`
bin = []
[package]
name = "exercises"
edition = "2024"
# Don't publish the exercises on crates.io!
publish = false
[dependencies]
"#;
const README: &str = "# Rustlings 🦀
Welcome to these community Rustlings exercises 😃
First, [install Rustlings using the official instructions](https://github.com/rust-lang/rustlings) ✅
Then, clone this repository, open a terminal in this directory and run `rustlings` to get started with the exercises 🚀
";
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/src/list/scroll_state.rs | src/list/scroll_state.rs | pub struct ScrollState {
n_rows: usize,
max_n_rows_to_display: usize,
selected: Option<usize>,
offset: usize,
scroll_padding: usize,
max_scroll_padding: usize,
}
impl ScrollState {
pub fn new(n_rows: usize, selected: Option<usize>, max_scroll_padding: usize) -> Self {
Self {
n_rows,
max_n_rows_to_display: 0,
selected,
offset: selected.map_or(0, |selected| selected.saturating_sub(max_scroll_padding)),
scroll_padding: 0,
max_scroll_padding,
}
}
#[inline]
pub fn offset(&self) -> usize {
self.offset
}
fn update_offset(&mut self) {
let Some(selected) = self.selected else {
return;
};
let min_offset = (selected + self.scroll_padding)
.saturating_sub(self.max_n_rows_to_display.saturating_sub(1));
let max_offset = selected.saturating_sub(self.scroll_padding);
let global_max_offset = self.n_rows.saturating_sub(self.max_n_rows_to_display);
self.offset = self
.offset
.max(min_offset)
.min(max_offset)
.min(global_max_offset);
}
#[inline]
pub fn selected(&self) -> Option<usize> {
self.selected
}
pub fn set_selected(&mut self, selected: usize) {
self.selected = Some(selected);
self.update_offset();
}
pub fn select_next(&mut self) {
if let Some(selected) = self.selected {
self.set_selected((selected + 1).min(self.n_rows - 1));
}
}
pub fn select_previous(&mut self) {
if let Some(selected) = self.selected {
self.set_selected(selected.saturating_sub(1));
}
}
pub fn select_first(&mut self) {
if self.n_rows > 0 {
self.set_selected(0);
}
}
pub fn select_last(&mut self) {
if self.n_rows > 0 {
self.set_selected(self.n_rows - 1);
}
}
pub fn set_n_rows(&mut self, n_rows: usize) {
self.n_rows = n_rows;
if self.n_rows == 0 {
self.selected = None;
return;
}
self.set_selected(self.selected.map_or(0, |selected| selected.min(n_rows - 1)));
}
#[inline]
fn update_scroll_padding(&mut self) {
self.scroll_padding = (self.max_n_rows_to_display / 4).min(self.max_scroll_padding);
}
#[inline]
pub fn max_n_rows_to_display(&self) -> usize {
self.max_n_rows_to_display
}
pub fn set_max_n_rows_to_display(&mut self, max_n_rows_to_display: usize) {
self.max_n_rows_to_display = max_n_rows_to_display;
self.update_scroll_padding();
self.update_offset();
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/src/list/state.rs | src/list/state.rs | use anyhow::{Context, Result};
use crossterm::{
QueueableCommand,
cursor::{MoveTo, MoveToNextLine},
style::{
Attribute, Attributes, Color, ResetColor, SetAttribute, SetAttributes, SetForegroundColor,
},
terminal::{self, BeginSynchronizedUpdate, Clear, ClearType, EndSynchronizedUpdate},
};
use std::{
fmt::Write as _,
io::{self, StdoutLock, Write},
};
use crate::{
app_state::AppState,
exercise::Exercise,
term::{CountedWrite, MaxLenWriter, progress_bar},
};
use super::scroll_state::ScrollState;
const COL_SPACING: usize = 2;
const SELECTED_ROW_ATTRIBUTES: Attributes = Attributes::none()
.with(Attribute::Reverse)
.with(Attribute::Bold);
fn next_ln(stdout: &mut StdoutLock) -> io::Result<()> {
stdout
.queue(Clear(ClearType::UntilNewLine))?
.queue(MoveToNextLine(1))?;
Ok(())
}
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum Filter {
Done,
Pending,
None,
}
pub struct ListState<'a> {
/// Footer message to be displayed if not empty.
pub message: String,
pub search_query: String,
app_state: &'a mut AppState,
scroll_state: ScrollState,
name_col_padding: Vec<u8>,
path_col_padding: Vec<u8>,
filter: Filter,
term_width: u16,
term_height: u16,
show_footer: bool,
}
impl<'a> ListState<'a> {
pub fn build(app_state: &'a mut AppState, stdout: &mut StdoutLock) -> Result<Self> {
stdout.queue(Clear(ClearType::All))?;
let name_col_title_len = 4;
let path_col_title_len = 4;
let (name_col_width, path_col_width) = app_state.exercises().iter().fold(
(name_col_title_len, path_col_title_len),
|(name_col_width, path_col_width), exercise| {
(
name_col_width.max(exercise.name.len()),
path_col_width.max(exercise.path.len()),
)
},
);
let name_col_padding = vec![b' '; name_col_width + COL_SPACING];
let path_col_padding = vec![b' '; path_col_width];
let filter = Filter::None;
let n_rows_with_filter = app_state.exercises().len();
let selected = app_state.current_exercise_ind();
let (width, height) = terminal::size().context("Failed to get the terminal size")?;
let scroll_state = ScrollState::new(n_rows_with_filter, Some(selected), 5);
let mut slf = Self {
message: String::with_capacity(128),
search_query: String::new(),
app_state,
scroll_state,
name_col_padding,
path_col_padding,
filter,
// Set by `set_term_size`
term_width: 0,
term_height: 0,
show_footer: true,
};
slf.set_term_size(width, height);
slf.draw(stdout)?;
Ok(slf)
}
pub fn set_term_size(&mut self, width: u16, height: u16) {
self.term_width = width;
self.term_height = height;
if height == 0 {
return;
}
let header_height = 1;
// 1 progress bar, 2 footer message lines.
let footer_height = 3;
self.show_footer = height > header_height + footer_height;
self.scroll_state.set_max_n_rows_to_display(
height.saturating_sub(header_height + u16::from(self.show_footer) * footer_height)
as usize,
);
}
fn draw_exercise_name(&self, writer: &mut MaxLenWriter, exercise: &Exercise) -> io::Result<()> {
if !self.search_query.is_empty()
&& let Some((pre_highlight, highlight, post_highlight)) = exercise
.name
.find(&self.search_query)
.and_then(|ind| exercise.name.split_at_checked(ind))
.and_then(|(pre_highlight, rest)| {
rest.split_at_checked(self.search_query.len())
.map(|x| (pre_highlight, x.0, x.1))
})
{
writer.write_str(pre_highlight)?;
writer.stdout.queue(SetForegroundColor(Color::Magenta))?;
writer.write_str(highlight)?;
writer.stdout.queue(SetForegroundColor(Color::Reset))?;
return writer.write_str(post_highlight);
}
writer.write_str(exercise.name)
}
fn draw_rows(
&self,
stdout: &mut StdoutLock,
filtered_exercises: impl Iterator<Item = (usize, &'a Exercise)>,
) -> io::Result<usize> {
let current_exercise_ind = self.app_state.current_exercise_ind();
let row_offset = self.scroll_state.offset();
let mut n_displayed_rows = 0;
for (exercise_ind, exercise) in filtered_exercises
.skip(row_offset)
.take(self.scroll_state.max_n_rows_to_display())
{
let mut writer = MaxLenWriter::new(stdout, self.term_width as usize);
if self.scroll_state.selected() == Some(row_offset + n_displayed_rows) {
// The crab emoji has the width of two ascii chars.
writer.add_to_len(2);
writer.stdout.write_all("🦀".as_bytes())?;
writer
.stdout
.queue(SetAttributes(SELECTED_ROW_ATTRIBUTES))?;
} else {
writer.write_ascii(b" ")?;
}
if exercise_ind == current_exercise_ind {
writer.stdout.queue(SetForegroundColor(Color::Red))?;
writer.write_ascii(b">>>>>>> ")?;
} else {
writer.write_ascii(b" ")?;
}
if exercise.done {
writer.stdout.queue(SetForegroundColor(Color::Green))?;
writer.write_ascii(b"DONE ")?;
} else {
writer.stdout.queue(SetForegroundColor(Color::Yellow))?;
writer.write_ascii(b"PENDING")?;
}
writer.stdout.queue(SetForegroundColor(Color::Reset))?;
writer.write_ascii(b" ")?;
self.draw_exercise_name(&mut writer, exercise)?;
writer.write_ascii(&self.name_col_padding[exercise.name.len()..])?;
exercise.terminal_file_link(&mut writer, self.app_state.emit_file_links())?;
writer.write_ascii(&self.path_col_padding[exercise.path.len()..])?;
next_ln(stdout)?;
stdout.queue(ResetColor)?;
n_displayed_rows += 1;
}
Ok(n_displayed_rows)
}
pub fn draw(&mut self, stdout: &mut StdoutLock) -> io::Result<()> {
if self.term_height == 0 {
return Ok(());
}
stdout.queue(BeginSynchronizedUpdate)?.queue(MoveTo(0, 0))?;
// Header
let mut writer = MaxLenWriter::new(stdout, self.term_width as usize);
writer.write_ascii(b" Current State Name")?;
writer.write_ascii(&self.name_col_padding[4..])?;
writer.write_ascii(b"Path")?;
next_ln(stdout)?;
// Rows
let iter = self.app_state.exercises().iter().enumerate();
let n_displayed_rows = match self.filter {
Filter::Done => self.draw_rows(stdout, iter.filter(|(_, exercise)| exercise.done))?,
Filter::Pending => {
self.draw_rows(stdout, iter.filter(|(_, exercise)| !exercise.done))?
}
Filter::None => self.draw_rows(stdout, iter)?,
};
for _ in 0..self.scroll_state.max_n_rows_to_display() - n_displayed_rows {
next_ln(stdout)?;
}
if self.show_footer {
progress_bar(
&mut MaxLenWriter::new(stdout, self.term_width as usize),
self.app_state.n_done(),
self.app_state.exercises().len() as u16,
self.term_width,
)?;
next_ln(stdout)?;
let mut writer = MaxLenWriter::new(stdout, self.term_width as usize);
if self.message.is_empty() {
// Help footer message
if self.scroll_state.selected().is_some() {
writer.write_str("↓/j ↑/k home/g end/G | <c>ontinue at | <r>eset exercise")?;
next_ln(stdout)?;
writer = MaxLenWriter::new(stdout, self.term_width as usize);
writer.write_ascii(b"<s>earch | filter ")?;
} else {
// Nothing selected (and nothing shown), so only display filter and quit.
writer.write_ascii(b"filter ")?;
}
match self.filter {
Filter::Done => {
writer
.stdout
.queue(SetForegroundColor(Color::Magenta))?
.queue(SetAttribute(Attribute::Underlined))?;
writer.write_ascii(b"<d>one")?;
writer.stdout.queue(ResetColor)?;
writer.write_ascii(b"/<p>ending")?;
}
Filter::Pending => {
writer.write_ascii(b"<d>one/")?;
writer
.stdout
.queue(SetForegroundColor(Color::Magenta))?
.queue(SetAttribute(Attribute::Underlined))?;
writer.write_ascii(b"<p>ending")?;
writer.stdout.queue(ResetColor)?;
}
Filter::None => writer.write_ascii(b"<d>one/<p>ending")?,
}
writer.write_ascii(b" | <q>uit list")?;
} else {
writer.stdout.queue(SetForegroundColor(Color::Magenta))?;
writer.write_str(&self.message)?;
stdout.queue(ResetColor)?;
next_ln(stdout)?;
}
next_ln(stdout)?;
}
stdout.queue(EndSynchronizedUpdate)?.flush()
}
fn update_rows(&mut self) {
let n_rows = match self.filter {
Filter::Done => self
.app_state
.exercises()
.iter()
.filter(|exercise| exercise.done)
.count(),
Filter::Pending => self
.app_state
.exercises()
.iter()
.filter(|exercise| !exercise.done)
.count(),
Filter::None => self.app_state.exercises().len(),
};
self.scroll_state.set_n_rows(n_rows);
}
#[inline]
pub fn filter(&self) -> Filter {
self.filter
}
pub fn set_filter(&mut self, filter: Filter) {
self.filter = filter;
self.update_rows();
}
#[inline]
pub fn select_next(&mut self) {
self.scroll_state.select_next();
}
#[inline]
pub fn select_previous(&mut self) {
self.scroll_state.select_previous();
}
#[inline]
pub fn select_first(&mut self) {
self.scroll_state.select_first();
}
#[inline]
pub fn select_last(&mut self) {
self.scroll_state.select_last();
}
fn selected_to_exercise_ind(&self, selected: usize) -> Result<usize> {
match self.filter {
Filter::Done => self
.app_state
.exercises()
.iter()
.enumerate()
.filter(|(_, exercise)| exercise.done)
.nth(selected)
.context("Invalid selection index")
.map(|(ind, _)| ind),
Filter::Pending => self
.app_state
.exercises()
.iter()
.enumerate()
.filter(|(_, exercise)| !exercise.done)
.nth(selected)
.context("Invalid selection index")
.map(|(ind, _)| ind),
Filter::None => Ok(selected),
}
}
pub fn reset_selected(&mut self) -> Result<()> {
let Some(selected) = self.scroll_state.selected() else {
self.message.push_str("Nothing selected to reset!");
return Ok(());
};
let exercise_ind = self.selected_to_exercise_ind(selected)?;
let exercise_name = self.app_state.reset_exercise_by_ind(exercise_ind)?;
self.update_rows();
write!(
self.message,
"The exercise `{exercise_name}` has been reset",
)?;
Ok(())
}
pub fn apply_search_query(&mut self) {
self.message.push_str("search:");
self.message.push_str(&self.search_query);
self.message.push('|');
if self.search_query.is_empty() {
return;
}
let is_search_result = |exercise: &Exercise| exercise.name.contains(&self.search_query);
let mut iter = self.app_state.exercises().iter();
let ind = match self.filter {
Filter::None => iter.position(is_search_result),
Filter::Done => iter
.filter(|exercise| exercise.done)
.position(is_search_result),
Filter::Pending => iter
.filter(|exercise| !exercise.done)
.position(is_search_result),
};
match ind {
Some(exercise_ind) => self.scroll_state.set_selected(exercise_ind),
None => self.message.push_str(" (not found)"),
}
}
// Return `true` if there was something to select.
pub fn selected_to_current_exercise(&mut self) -> Result<bool> {
let Some(selected) = self.scroll_state.selected() else {
self.message.push_str("Nothing selected to continue at!");
return Ok(false);
};
let exercise_ind = self.selected_to_exercise_ind(selected)?;
self.app_state.set_current_exercise_ind(exercise_ind)?;
Ok(true)
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/src/watch/notify_event.rs | src/watch/notify_event.rs | use anyhow::{Context, Result};
use notify::{
Event, EventKind,
event::{AccessKind, AccessMode, MetadataKind, ModifyKind, RenameMode},
};
use std::{
sync::{
atomic::Ordering::Relaxed,
mpsc::{RecvTimeoutError, Sender, SyncSender, sync_channel},
},
thread,
time::Duration,
};
use super::{EXERCISE_RUNNING, WatchEvent};
const DEBOUNCE_DURATION: Duration = Duration::from_millis(200);
pub struct NotifyEventHandler {
error_sender: Sender<WatchEvent>,
// Sends the index of the updated exercise.
update_sender: SyncSender<usize>,
// Used to report which exercise was modified.
exercise_names: &'static [&'static [u8]],
}
impl NotifyEventHandler {
pub fn build(
watch_event_sender: Sender<WatchEvent>,
exercise_names: &'static [&'static [u8]],
) -> Result<Self> {
let (update_sender, update_receiver) = sync_channel(0);
let error_sender = watch_event_sender.clone();
// Debouncer
thread::Builder::new()
.spawn(move || {
let mut exercise_updated = vec![false; exercise_names.len()];
loop {
match update_receiver.recv_timeout(DEBOUNCE_DURATION) {
Ok(exercise_ind) => exercise_updated[exercise_ind] = true,
Err(RecvTimeoutError::Timeout) => {
for (exercise_ind, updated) in exercise_updated.iter_mut().enumerate() {
if *updated {
if watch_event_sender
.send(WatchEvent::FileChange { exercise_ind })
.is_err()
{
break;
}
*updated = false;
}
}
}
Err(RecvTimeoutError::Disconnected) => break,
}
}
})
.context("Failed to spawn a thread to debounce file changes")?;
Ok(Self {
error_sender,
update_sender,
exercise_names,
})
}
}
impl notify::EventHandler for NotifyEventHandler {
fn handle_event(&mut self, input_event: notify::Result<Event>) {
if EXERCISE_RUNNING.load(Relaxed) {
return;
}
let input_event = match input_event {
Ok(v) => v,
Err(e) => {
// An error occurs when the receiver is dropped.
// After dropping the receiver, the watcher guard should also be dropped.
let _ = self.error_sender.send(WatchEvent::NotifyErr(e));
return;
}
};
match input_event.kind {
EventKind::Any => (),
EventKind::Modify(modify_kind) => match modify_kind {
ModifyKind::Any | ModifyKind::Data(_) => (),
ModifyKind::Name(rename_mode) => match rename_mode {
RenameMode::Any | RenameMode::To => (),
RenameMode::From | RenameMode::Both | RenameMode::Other => return,
},
ModifyKind::Metadata(metadata_kind) => match metadata_kind {
MetadataKind::Any | MetadataKind::WriteTime => (),
MetadataKind::AccessTime
| MetadataKind::Permissions
| MetadataKind::Ownership
| MetadataKind::Extended
| MetadataKind::Other => return,
},
ModifyKind::Other => return,
},
EventKind::Access(access_kind) => match access_kind {
AccessKind::Any => (),
AccessKind::Close(access_mode) => match access_mode {
AccessMode::Any | AccessMode::Write => (),
AccessMode::Execute | AccessMode::Read | AccessMode::Other => return,
},
AccessKind::Read | AccessKind::Open(_) | AccessKind::Other => return,
},
EventKind::Create(_) | EventKind::Remove(_) | EventKind::Other => return,
}
let _ = input_event
.paths
.into_iter()
.filter_map(|path| {
let file_name = path.file_name()?.to_str()?.as_bytes();
let [file_name_without_ext @ .., b'.', b'r', b's'] = file_name else {
return None;
};
self.exercise_names
.iter()
.position(|exercise_name| *exercise_name == file_name_without_ext)
})
.try_for_each(|exercise_ind| self.update_sender.send(exercise_ind));
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/src/watch/state.rs | src/watch/state.rs | use anyhow::{Context, Result};
use crossterm::{
QueueableCommand,
style::{
Attribute, Attributes, Color, ResetColor, SetAttribute, SetAttributes, SetForegroundColor,
},
terminal,
};
use std::{
io::{self, Read, StdoutLock, Write},
sync::mpsc::{Sender, SyncSender, sync_channel},
thread,
};
use crate::{
app_state::{AppState, ExercisesProgress},
clear_terminal,
exercise::{OUTPUT_CAPACITY, RunnableExercise, solution_link_line},
term::progress_bar,
};
use super::{InputPauseGuard, WatchEvent, terminal_event::terminal_event_handler};
const HEADING_ATTRIBUTES: Attributes = Attributes::none()
.with(Attribute::Bold)
.with(Attribute::Underlined);
#[derive(PartialEq, Eq)]
enum DoneStatus {
DoneWithSolution(String),
DoneWithoutSolution,
Pending,
}
pub struct WatchState<'a> {
app_state: &'a mut AppState,
output: Vec<u8>,
show_hint: bool,
done_status: DoneStatus,
manual_run: bool,
term_width: u16,
terminal_event_unpause_sender: SyncSender<()>,
}
impl<'a> WatchState<'a> {
pub fn build(
app_state: &'a mut AppState,
watch_event_sender: Sender<WatchEvent>,
manual_run: bool,
) -> Result<Self> {
let term_width = terminal::size()
.context("Failed to get the terminal size")?
.0;
let (terminal_event_unpause_sender, terminal_event_unpause_receiver) = sync_channel(0);
thread::Builder::new()
.spawn(move || {
terminal_event_handler(
watch_event_sender,
terminal_event_unpause_receiver,
manual_run,
)
})
.context("Failed to spawn a thread to handle terminal events")?;
Ok(Self {
app_state,
output: Vec::with_capacity(OUTPUT_CAPACITY),
show_hint: false,
done_status: DoneStatus::Pending,
manual_run,
term_width,
terminal_event_unpause_sender,
})
}
pub fn run_current_exercise(&mut self, stdout: &mut StdoutLock) -> Result<()> {
// Ignore any input until running the exercise is done.
let _input_pause_guard = InputPauseGuard::scoped_pause();
self.show_hint = false;
writeln!(
stdout,
"\nChecking the exercise `{}`. Please wait…",
self.app_state.current_exercise().name,
)?;
let success = self
.app_state
.current_exercise()
.run_exercise(Some(&mut self.output), self.app_state.cmd_runner())?;
self.output.push(b'\n');
if success {
self.done_status =
if let Some(solution_path) = self.app_state.current_solution_path()? {
DoneStatus::DoneWithSolution(solution_path)
} else {
DoneStatus::DoneWithoutSolution
};
} else {
self.app_state
.set_pending(self.app_state.current_exercise_ind())?;
self.done_status = DoneStatus::Pending;
}
self.render(stdout)?;
Ok(())
}
pub fn reset_exercise(&mut self, stdout: &mut StdoutLock) -> Result<()> {
clear_terminal(stdout)?;
stdout.write_all(b"Resetting will undo all your changes to the file ")?;
stdout.write_all(self.app_state.current_exercise().path.as_bytes())?;
stdout.write_all(b"\nReset (y/n)? ")?;
stdout.flush()?;
{
let mut stdin = io::stdin().lock();
let mut answer = [0];
loop {
stdin
.read_exact(&mut answer)
.context("Failed to read the user's input")?;
match answer[0] {
b'y' | b'Y' => {
self.app_state.reset_current_exercise()?;
// The file watcher reruns the exercise otherwise.
if self.manual_run {
self.run_current_exercise(stdout)?;
}
}
b'n' | b'N' => self.render(stdout)?,
_ => continue,
}
break;
}
}
self.terminal_event_unpause_sender.send(())?;
Ok(())
}
pub fn handle_file_change(
&mut self,
exercise_ind: usize,
stdout: &mut StdoutLock,
) -> Result<()> {
if self.app_state.current_exercise_ind() != exercise_ind {
return Ok(());
}
self.run_current_exercise(stdout)
}
/// Move on to the next exercise if the current one is done.
pub fn next_exercise(&mut self, stdout: &mut StdoutLock) -> Result<ExercisesProgress> {
match self.done_status {
DoneStatus::DoneWithSolution(_) | DoneStatus::DoneWithoutSolution => (),
DoneStatus::Pending => return Ok(ExercisesProgress::CurrentPending),
}
self.app_state.done_current_exercise::<true>(stdout)
}
fn show_prompt(&self, stdout: &mut StdoutLock) -> io::Result<()> {
if self.done_status != DoneStatus::Pending {
stdout.queue(SetAttribute(Attribute::Bold))?;
stdout.write_all(b"n")?;
stdout.queue(ResetColor)?;
stdout.write_all(b":")?;
stdout.queue(SetAttribute(Attribute::Underlined))?;
stdout.write_all(b"next")?;
stdout.queue(ResetColor)?;
stdout.write_all(b" / ")?;
}
let mut show_key = |key, postfix| {
stdout.queue(SetAttribute(Attribute::Bold))?;
stdout.write_all(&[key])?;
stdout.queue(ResetColor)?;
stdout.write_all(postfix)
};
if self.manual_run {
show_key(b'r', b":run / ")?;
}
if !self.show_hint {
show_key(b'h', b":hint / ")?;
}
show_key(b'l', b":list / ")?;
show_key(b'c', b":check all / ")?;
show_key(b'x', b":reset / ")?;
show_key(b'q', b":quit ? ")?;
stdout.flush()
}
pub fn render(&self, stdout: &mut StdoutLock) -> io::Result<()> {
// Prevent having the first line shifted if clearing wasn't successful.
stdout.write_all(b"\n")?;
clear_terminal(stdout)?;
stdout.write_all(&self.output)?;
if self.show_hint {
stdout
.queue(SetAttributes(HEADING_ATTRIBUTES))?
.queue(SetForegroundColor(Color::Cyan))?;
stdout.write_all(b"Hint")?;
stdout.queue(ResetColor)?;
stdout.write_all(b"\n")?;
stdout.write_all(self.app_state.current_exercise().hint.as_bytes())?;
stdout.write_all(b"\n\n")?;
}
if self.done_status != DoneStatus::Pending {
stdout
.queue(SetAttribute(Attribute::Bold))?
.queue(SetForegroundColor(Color::Green))?;
stdout.write_all("Exercise done ✓".as_bytes())?;
stdout.queue(ResetColor)?;
stdout.write_all(b"\n")?;
if let DoneStatus::DoneWithSolution(solution_path) = &self.done_status {
solution_link_line(stdout, solution_path, self.app_state.emit_file_links())?;
}
stdout.write_all(
"When done experimenting, enter `n` to move on to the next exercise 🦀\n\n"
.as_bytes(),
)?;
}
progress_bar(
stdout,
self.app_state.n_done(),
self.app_state.exercises().len() as u16,
self.term_width,
)?;
stdout.write_all(b"\nCurrent exercise: ")?;
self.app_state
.current_exercise()
.terminal_file_link(stdout, self.app_state.emit_file_links())?;
stdout.write_all(b"\n\n")?;
self.show_prompt(stdout)?;
Ok(())
}
pub fn show_hint(&mut self, stdout: &mut StdoutLock) -> io::Result<()> {
if !self.show_hint {
self.show_hint = true;
self.render(stdout)?;
}
Ok(())
}
pub fn check_all_exercises(&mut self, stdout: &mut StdoutLock) -> Result<ExercisesProgress> {
// Ignore any input until checking all exercises is done.
let _input_pause_guard = InputPauseGuard::scoped_pause();
if let Some(first_pending_exercise_ind) = self.app_state.check_all_exercises(stdout)? {
// Only change exercise if the current one is done.
if self.app_state.current_exercise().done {
self.app_state
.set_current_exercise_ind(first_pending_exercise_ind)?;
Ok(ExercisesProgress::NewPending)
} else {
Ok(ExercisesProgress::CurrentPending)
}
} else {
self.app_state.render_final_message(stdout)?;
Ok(ExercisesProgress::AllDone)
}
}
pub fn update_term_width(&mut self, width: u16, stdout: &mut StdoutLock) -> io::Result<()> {
if self.term_width != width {
self.term_width = width;
self.render(stdout)?;
}
Ok(())
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/src/watch/terminal_event.rs | src/watch/terminal_event.rs | use crossterm::event::{self, Event, KeyCode, KeyEventKind};
use std::sync::{
atomic::Ordering::Relaxed,
mpsc::{Receiver, Sender},
};
use super::{EXERCISE_RUNNING, WatchEvent};
pub enum InputEvent {
Next,
Run,
Hint,
List,
CheckAll,
Reset,
Quit,
}
pub fn terminal_event_handler(
sender: Sender<WatchEvent>,
unpause_receiver: Receiver<()>,
manual_run: bool,
) {
let last_watch_event = loop {
match event::read() {
Ok(Event::Key(key)) => {
match key.kind {
KeyEventKind::Release | KeyEventKind::Repeat => continue,
KeyEventKind::Press => (),
}
if EXERCISE_RUNNING.load(Relaxed) {
continue;
}
let input_event = match key.code {
KeyCode::Char('n') => InputEvent::Next,
KeyCode::Char('r') if manual_run => InputEvent::Run,
KeyCode::Char('h') => InputEvent::Hint,
KeyCode::Char('l') => break WatchEvent::Input(InputEvent::List),
KeyCode::Char('c') => InputEvent::CheckAll,
KeyCode::Char('x') => {
if sender.send(WatchEvent::Input(InputEvent::Reset)).is_err() {
return;
}
// Pause input until quitting the confirmation prompt.
if unpause_receiver.recv().is_err() {
return;
};
continue;
}
KeyCode::Char('q') => break WatchEvent::Input(InputEvent::Quit),
_ => continue,
};
if sender.send(WatchEvent::Input(input_event)).is_err() {
return;
}
}
Ok(Event::Resize(width, _)) => {
if sender.send(WatchEvent::TerminalResize { width }).is_err() {
return;
}
}
Ok(Event::FocusGained | Event::FocusLost | Event::Mouse(_)) => continue,
Err(e) => break WatchEvent::TerminalEventErr(e),
}
};
let _ = sender.send(last_watch_event);
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/tests/integration_tests.rs | tests/integration_tests.rs | use std::{
env::{self, consts::EXE_SUFFIX},
process::{Command, Stdio},
str::from_utf8,
};
enum Output<'a> {
FullStdout(&'a str),
PartialStdout(&'a str),
PartialStderr(&'a str),
}
use Output::*;
#[derive(Default)]
struct Cmd<'a> {
current_dir: Option<&'a str>,
args: &'a [&'a str],
output: Option<Output<'a>>,
}
impl<'a> Cmd<'a> {
#[inline]
fn current_dir(&mut self, current_dir: &'a str) -> &mut Self {
self.current_dir = Some(current_dir);
self
}
#[inline]
fn args(&mut self, args: &'a [&'a str]) -> &mut Self {
self.args = args;
self
}
#[inline]
fn output(&mut self, output: Output<'a>) -> &mut Self {
self.output = Some(output);
self
}
fn assert(&self, success: bool) {
let rustlings_bin = {
let mut path = env::current_exe().unwrap();
// Pop test binary name
path.pop();
// Pop `/deps`
path.pop();
path.push("rustlings");
let mut path = path.into_os_string();
path.push(EXE_SUFFIX);
path
};
let mut cmd = Command::new(rustlings_bin);
if let Some(current_dir) = self.current_dir {
cmd.current_dir(current_dir);
}
cmd.args(self.args).stdin(Stdio::null());
let status = match self.output {
None => cmd
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.unwrap(),
Some(FullStdout(stdout)) => {
let output = cmd.stderr(Stdio::null()).output().unwrap();
assert_eq!(from_utf8(&output.stdout).unwrap(), stdout);
output.status
}
Some(PartialStdout(stdout)) => {
let output = cmd.stderr(Stdio::null()).output().unwrap();
assert!(from_utf8(&output.stdout).unwrap().contains(stdout));
output.status
}
Some(PartialStderr(stderr)) => {
let output = cmd.stdout(Stdio::null()).output().unwrap();
assert!(from_utf8(&output.stderr).unwrap().contains(stderr));
output.status
}
};
assert_eq!(status.success(), success, "{cmd:?}");
}
#[inline]
fn success(&self) {
self.assert(true);
}
#[inline]
fn fail(&self) {
self.assert(false);
}
}
#[test]
fn run_compilation_success() {
Cmd::default()
.current_dir("tests/test_exercises")
.args(&["run", "compilation_success"])
.success();
}
#[test]
fn run_compilation_failure() {
Cmd::default()
.current_dir("tests/test_exercises")
.args(&["run", "compilation_failure"])
.fail();
}
#[test]
fn run_test_success() {
Cmd::default()
.current_dir("tests/test_exercises")
.args(&["run", "test_success"])
.output(PartialStdout("\nOutput from `main` function\n"))
.success();
}
#[test]
fn run_test_failure() {
Cmd::default()
.current_dir("tests/test_exercises")
.args(&["run", "test_failure"])
.fail();
}
#[test]
fn run_exercise_not_in_info() {
Cmd::default()
.current_dir("tests/test_exercises")
.args(&["run", "not_in_info"])
.fail();
}
#[test]
fn reset_without_exercise_name() {
Cmd::default().args(&["reset"]).fail();
}
#[test]
fn hint() {
Cmd::default()
.current_dir("tests/test_exercises")
.args(&["hint", "test_failure"])
.output(FullStdout("The answer to everything: 42\n"))
.success();
}
#[test]
fn init() {
let test_dir = tempfile::TempDir::new().unwrap();
let test_dir = test_dir.path().to_str().unwrap();
Cmd::default().current_dir(test_dir).fail();
Cmd::default()
.current_dir(test_dir)
.args(&["init"])
.success();
// Running `init` after a successful initialization.
Cmd::default()
.current_dir(test_dir)
.args(&["init"])
.output(PartialStderr("`cd rustlings`"))
.fail();
let initialized_dir = format!("{test_dir}/rustlings");
// Running `init` in the initialized directory.
Cmd::default()
.current_dir(&initialized_dir)
.args(&["init"])
.output(PartialStderr("already initialized"))
.fail();
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/tests/test_exercises/exercises/test_success.rs | tests/test_exercises/exercises/test_success.rs | fn main() {
println!("Output from `main` function");
}
#[cfg(test)]
mod tests {
#[test]
fn passes() {}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/tests/test_exercises/exercises/test_failure.rs | tests/test_exercises/exercises/test_failure.rs | fn main() {}
#[cfg(test)]
mod tests {
#[test]
fn fails() {
assert!(false);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/tests/test_exercises/exercises/compilation_failure.rs | tests/test_exercises/exercises/compilation_failure.rs | fn main() {
let
} | rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/tests/test_exercises/exercises/compilation_success.rs | tests/test_exercises/exercises/compilation_success.rs | fn main() {}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/tests/test_exercises/exercises/not_in_info.rs | tests/test_exercises/exercises/not_in_info.rs | fn main() {}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/19_smart_pointers/cow1.rs | exercises/19_smart_pointers/cow1.rs | // This exercise explores the `Cow` (Clone-On-Write) smart pointer. It can
// enclose and provide immutable access to borrowed data and clone the data
// lazily when mutation or ownership is required. The type is designed to work
// with general borrowed data via the `Borrow` trait.
use std::borrow::Cow;
fn abs_all(input: &mut Cow<[i32]>) {
for ind in 0..input.len() {
let value = input[ind];
if value < 0 {
// Clones into a vector if not already owned.
input.to_mut()[ind] = -value;
}
}
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reference_mutation() {
// Clone occurs because `input` needs to be mutated.
let vec = vec![-1, 0, 1];
let mut input = Cow::from(&vec);
abs_all(&mut input);
assert!(matches!(input, Cow::Owned(_)));
}
#[test]
fn reference_no_mutation() {
// No clone occurs because `input` doesn't need to be mutated.
let vec = vec![0, 1, 2];
let mut input = Cow::from(&vec);
abs_all(&mut input);
// TODO: Replace `todo!()` with `Cow::Owned(_)` or `Cow::Borrowed(_)`.
assert!(matches!(input, todo!()));
}
#[test]
fn owned_no_mutation() {
// We can also pass `vec` without `&` so `Cow` owns it directly. In this
// case, no mutation occurs (all numbers are already absolute) and thus
// also no clone. But the result is still owned because it was never
// borrowed or mutated.
let vec = vec![0, 1, 2];
let mut input = Cow::from(vec);
abs_all(&mut input);
// TODO: Replace `todo!()` with `Cow::Owned(_)` or `Cow::Borrowed(_)`.
assert!(matches!(input, todo!()));
}
#[test]
fn owned_mutation() {
// Of course this is also the case if a mutation does occur (not all
// numbers are absolute). In this case, the call to `to_mut()` in the
// `abs_all` function returns a reference to the same data as before.
let vec = vec![-1, 0, 1];
let mut input = Cow::from(vec);
abs_all(&mut input);
// TODO: Replace `todo!()` with `Cow::Owned(_)` or `Cow::Borrowed(_)`.
assert!(matches!(input, todo!()));
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/19_smart_pointers/box1.rs | exercises/19_smart_pointers/box1.rs | // At compile time, Rust needs to know how much space a type takes up. This
// becomes problematic for recursive types, where a value can have as part of
// itself another value of the same type. To get around the issue, we can use a
// `Box` - a smart pointer used to store data on the heap, which also allows us
// to wrap a recursive type.
//
// The recursive type we're implementing in this exercise is the "cons list", a
// data structure frequently found in functional programming languages. Each
// item in a cons list contains two elements: The value of the current item and
// the next item. The last item is a value called `Nil`.
// TODO: Use a `Box` in the enum definition to make the code compile.
#[derive(PartialEq, Debug)]
enum List {
Cons(i32, List),
Nil,
}
// TODO: Create an empty cons list.
fn create_empty_list() -> List {
todo!()
}
// TODO: Create a non-empty cons list.
fn create_non_empty_list() -> List {
todo!()
}
fn main() {
println!("This is an empty cons list: {:?}", create_empty_list());
println!(
"This is a non-empty cons list: {:?}",
create_non_empty_list(),
);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_empty_list() {
assert_eq!(create_empty_list(), List::Nil);
}
#[test]
fn test_create_non_empty_list() {
assert_ne!(create_empty_list(), create_non_empty_list());
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/19_smart_pointers/arc1.rs | exercises/19_smart_pointers/arc1.rs | // In this exercise, we are given a `Vec` of `u32` called `numbers` with values
// ranging from 0 to 99. We would like to use this set of numbers within 8
// different threads simultaneously. Each thread is going to get the sum of
// every eighth value with an offset.
//
// The first thread (offset 0), will sum 0, 8, 16, …
// The second thread (offset 1), will sum 1, 9, 17, …
// The third thread (offset 2), will sum 2, 10, 18, …
// …
// The eighth thread (offset 7), will sum 7, 15, 23, …
//
// Each thread should own a reference-counting pointer to the vector of
// numbers. But `Rc` isn't thread-safe. Therefore, we need to use `Arc`.
//
// Don't get distracted by how threads are spawned and joined. We will practice
// that later in the exercises about threads.
// Don't change the lines below.
#![forbid(unused_imports)]
use std::{sync::Arc, thread};
fn main() {
let numbers: Vec<_> = (0..100u32).collect();
// TODO: Define `shared_numbers` by using `Arc`.
// let shared_numbers = ???;
let mut join_handles = Vec::new();
for offset in 0..8 {
// TODO: Define `child_numbers` using `shared_numbers`.
// let child_numbers = ???;
let handle = thread::spawn(move || {
let sum: u32 = child_numbers.iter().filter(|&&n| n % 8 == offset).sum();
println!("Sum of offset {offset} is {sum}");
});
join_handles.push(handle);
}
for handle in join_handles.into_iter() {
handle.join().unwrap();
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/19_smart_pointers/rc1.rs | exercises/19_smart_pointers/rc1.rs | // In this exercise, we want to express the concept of multiple owners via the
// `Rc<T>` type. This is a model of our solar system - there is a `Sun` type and
// multiple `Planet`s. The planets take ownership of the sun, indicating that
// they revolve around the sun.
use std::rc::Rc;
#[derive(Debug)]
struct Sun;
#[derive(Debug)]
enum Planet {
Mercury(Rc<Sun>),
Venus(Rc<Sun>),
Earth(Rc<Sun>),
Mars(Rc<Sun>),
Jupiter(Rc<Sun>),
Saturn(Rc<Sun>),
Uranus(Rc<Sun>),
Neptune(Rc<Sun>),
}
impl Planet {
fn details(&self) {
println!("Hi from {self:?}!");
}
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rc1() {
let sun = Rc::new(Sun);
println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference
let mercury = Planet::Mercury(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 2 references
mercury.details();
let venus = Planet::Venus(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 3 references
venus.details();
let earth = Planet::Earth(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 4 references
earth.details();
let mars = Planet::Mars(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 5 references
mars.details();
let jupiter = Planet::Jupiter(Rc::clone(&sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 6 references
jupiter.details();
// TODO
let saturn = Planet::Saturn(Rc::new(Sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 7 references
saturn.details();
// TODO
let uranus = Planet::Uranus(Rc::new(Sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 8 references
uranus.details();
// TODO
let neptune = Planet::Neptune(Rc::new(Sun));
println!("reference count = {}", Rc::strong_count(&sun)); // 9 references
neptune.details();
assert_eq!(Rc::strong_count(&sun), 9);
drop(neptune);
println!("reference count = {}", Rc::strong_count(&sun)); // 8 references
drop(uranus);
println!("reference count = {}", Rc::strong_count(&sun)); // 7 references
drop(saturn);
println!("reference count = {}", Rc::strong_count(&sun)); // 6 references
drop(jupiter);
println!("reference count = {}", Rc::strong_count(&sun)); // 5 references
drop(mars);
println!("reference count = {}", Rc::strong_count(&sun)); // 4 references
// TODO
println!("reference count = {}", Rc::strong_count(&sun)); // 3 references
// TODO
println!("reference count = {}", Rc::strong_count(&sun)); // 2 references
// TODO
println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference
assert_eq!(Rc::strong_count(&sun), 1);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/22_clippy/clippy1.rs | exercises/22_clippy/clippy1.rs | // The Clippy tool is a collection of lints to analyze your code so you can
// catch common mistakes and improve your Rust code.
//
// For these exercises, the code will fail to compile when there are Clippy
// warnings. Check Clippy's suggestions from the output to solve the exercise.
fn main() {
// TODO: Fix the Clippy lint in this line.
let pi = 3.14;
let radius: f32 = 5.0;
let area = pi * radius.powi(2);
println!("The area of a circle with radius {radius:.2} is {area:.5}");
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/22_clippy/clippy3.rs | exercises/22_clippy/clippy3.rs | // Here are some more easy Clippy fixes so you can see its utility.
// TODO: Fix all the Clippy lints.
#[allow(unused_variables, unused_assignments)]
fn main() {
let my_option: Option<&str> = None;
// Assume that you don't know the value of `my_option`.
// In the case of `Some`, we want to print its value.
if my_option.is_none() {
println!("{}", my_option.unwrap());
}
#[rustfmt::skip]
let my_arr = &[
-1, -2, -3
-4, -5, -6
];
println!("My array! Here it is: {my_arr:?}");
let mut my_vec = vec![1, 2, 3, 4, 5];
my_vec.resize(0, 5);
println!("This Vec is empty, see? {my_vec:?}");
let mut value_a = 45;
let mut value_b = 66;
// Let's swap these two!
value_a = value_b;
value_b = value_a;
println!("value a: {value_a}; value b: {value_b}");
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/22_clippy/clippy2.rs | exercises/22_clippy/clippy2.rs | fn main() {
let mut res = 42;
let option = Some(12);
// TODO: Fix the Clippy lint.
for x in option {
res += x;
}
println!("{res}");
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/09_strings/strings1.rs | exercises/09_strings/strings1.rs | // TODO: Fix the compiler error without changing the function signature.
fn current_favorite_color() -> String {
"blue"
}
fn main() {
let answer = current_favorite_color();
println!("My current favorite color is {answer}");
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/09_strings/strings2.rs | exercises/09_strings/strings2.rs | // TODO: Fix the compiler error in the `main` function without changing this function.
fn is_a_color_word(attempt: &str) -> bool {
attempt == "green" || attempt == "blue" || attempt == "red"
}
fn main() {
let word = String::from("green"); // Don't change this line.
if is_a_color_word(word) {
println!("That is a color word I know!");
} else {
println!("That is not a color word I know.");
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/09_strings/strings3.rs | exercises/09_strings/strings3.rs | fn trim_me(input: &str) -> &str {
// TODO: Remove whitespace from both ends of a string.
}
fn compose_me(input: &str) -> String {
// TODO: Add " world!" to the string! There are multiple ways to do this.
}
fn replace_me(input: &str) -> String {
// TODO: Replace "cars" in the string with "balloons".
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn trim_a_string() {
assert_eq!(trim_me("Hello! "), "Hello!");
assert_eq!(trim_me(" What's up!"), "What's up!");
assert_eq!(trim_me(" Hola! "), "Hola!");
assert_eq!(trim_me("Hi!"), "Hi!");
}
#[test]
fn compose_a_string() {
assert_eq!(compose_me("Hello"), "Hello world!");
assert_eq!(compose_me("Goodbye"), "Goodbye world!");
}
#[test]
fn replace_a_string() {
assert_eq!(
replace_me("I think cars are cool"),
"I think balloons are cool",
);
assert_eq!(
replace_me("I love to look at cars"),
"I love to look at balloons",
);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/09_strings/strings4.rs | exercises/09_strings/strings4.rs | // Calls of this function should be replaced with calls of `string_slice` or `string`.
fn placeholder() {}
fn string_slice(arg: &str) {
println!("{arg}");
}
fn string(arg: String) {
println!("{arg}");
}
// TODO: Here are a bunch of values - some are `String`, some are `&str`.
// Your task is to replace `placeholder(…)` with either `string_slice(…)`
// or `string(…)` depending on what you think each value is.
fn main() {
placeholder("blue");
placeholder("red".to_string());
placeholder(String::from("hi"));
placeholder("rust is fun!".to_owned());
placeholder("nice weather".into());
placeholder(format!("Interpolation {}", "Station"));
// WARNING: This is byte indexing, not character indexing.
// Character indexing can be done using `s.chars().nth(INDEX)`.
placeholder(&String::from("abc")[0..1]);
placeholder(" hello there ".trim());
placeholder("Happy Monday!".replace("Mon", "Tues"));
placeholder("mY sHiFt KeY iS sTiCkY".to_lowercase());
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/20_threads/threads3.rs | exercises/20_threads/threads3.rs | use std::{sync::mpsc, thread, time::Duration};
struct Queue {
first_half: Vec<u32>,
second_half: Vec<u32>,
}
impl Queue {
fn new() -> Self {
Self {
first_half: vec![1, 2, 3, 4, 5],
second_half: vec![6, 7, 8, 9, 10],
}
}
}
fn send_tx(q: Queue, tx: mpsc::Sender<u32>) {
// TODO: We want to send `tx` to both threads. But currently, it is moved
// into the first thread. How could you solve this problem?
thread::spawn(move || {
for val in q.first_half {
println!("Sending {val:?}");
tx.send(val).unwrap();
thread::sleep(Duration::from_millis(250));
}
});
thread::spawn(move || {
for val in q.second_half {
println!("Sending {val:?}");
tx.send(val).unwrap();
thread::sleep(Duration::from_millis(250));
}
});
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn threads3() {
let (tx, rx) = mpsc::channel();
let queue = Queue::new();
send_tx(queue, tx);
let mut received = Vec::with_capacity(10);
for value in rx {
received.push(value);
}
received.sort();
assert_eq!(received, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/20_threads/threads2.rs | exercises/20_threads/threads2.rs | // Building on the last exercise, we want all of the threads to complete their
// work. But this time, the spawned threads need to be in charge of updating a
// shared value: `JobStatus.jobs_done`
use std::{sync::Arc, thread, time::Duration};
struct JobStatus {
jobs_done: u32,
}
fn main() {
// TODO: `Arc` isn't enough if you want a **mutable** shared state.
let status = Arc::new(JobStatus { jobs_done: 0 });
let mut handles = Vec::new();
for _ in 0..10 {
let status_shared = Arc::clone(&status);
let handle = thread::spawn(move || {
thread::sleep(Duration::from_millis(250));
// TODO: You must take an action before you update a shared value.
status_shared.jobs_done += 1;
});
handles.push(handle);
}
// Waiting for all jobs to complete.
for handle in handles {
handle.join().unwrap();
}
// TODO: Print the value of `JobStatus.jobs_done`.
println!("Jobs done: {}", todo!());
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/20_threads/threads1.rs | exercises/20_threads/threads1.rs | // This program spawns multiple threads that each runs for at least 250ms, and
// each thread returns how much time it took to complete. The program should
// wait until all the spawned threads have finished and should collect their
// return values into a vector.
use std::{
thread,
time::{Duration, Instant},
};
fn main() {
let mut handles = Vec::new();
for i in 0..10 {
let handle = thread::spawn(move || {
let start = Instant::now();
thread::sleep(Duration::from_millis(250));
println!("Thread {i} done");
start.elapsed().as_millis()
});
handles.push(handle);
}
let mut results = Vec::new();
for handle in handles {
// TODO: Collect the results of all threads into the `results` vector.
// Use the `JoinHandle` struct which is returned by `thread::spawn`.
}
if results.len() != 10 {
panic!("Oh no! Some thread isn't done yet!");
}
println!();
for (i, result) in results.into_iter().enumerate() {
println!("Thread {i} took {result}ms");
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/13_error_handling/errors2.rs | exercises/13_error_handling/errors2.rs | // Say we're writing a game where you can buy items with tokens. All items cost
// 5 tokens, and whenever you purchase items there is a processing fee of 1
// token. A player of the game will type in how many items they want to buy, and
// the `total_cost` function will calculate the total cost of the items. Since
// the player typed in the quantity, we get it as a string. They might have
// typed anything, not just numbers!
//
// Right now, this function isn't handling the error case at all. What we want
// to do is: If we call the `total_cost` function on a string that is not a
// number, that function will return a `ParseIntError`. In that case, we want to
// immediately return that error from our function and not try to multiply and
// add.
//
// There are at least two ways to implement this that are both correct. But one
// is a lot shorter!
use std::num::ParseIntError;
fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
let processing_fee = 1;
let cost_per_item = 5;
// TODO: Handle the error case as described above.
let qty = item_quantity.parse::<i32>();
Ok(qty * cost_per_item + processing_fee)
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
use std::num::IntErrorKind;
#[test]
fn item_quantity_is_a_valid_number() {
assert_eq!(total_cost("34"), Ok(171));
}
#[test]
fn item_quantity_is_an_invalid_number() {
assert_eq!(
total_cost("beep boop").unwrap_err().kind(),
&IntErrorKind::InvalidDigit,
);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/13_error_handling/errors6.rs | exercises/13_error_handling/errors6.rs | // Using catch-all error types like `Box<dyn Error>` isn't recommended for
// library code where callers might want to make decisions based on the error
// content instead of printing it out or propagating it further. Here, we define
// a custom error type to make it possible for callers to decide what to do next
// when our function returns an error.
use std::num::ParseIntError;
#[derive(PartialEq, Debug)]
enum CreationError {
Negative,
Zero,
}
// A custom error type that we will be using in `PositiveNonzeroInteger::parse`.
#[derive(PartialEq, Debug)]
enum ParsePosNonzeroError {
Creation(CreationError),
ParseInt(ParseIntError),
}
impl ParsePosNonzeroError {
fn from_creation(err: CreationError) -> Self {
Self::Creation(err)
}
// TODO: Add another error conversion function here.
// fn from_parse_int(???) -> Self { ??? }
}
#[derive(PartialEq, Debug)]
struct PositiveNonzeroInteger(u64);
impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<Self, CreationError> {
match value {
x if x < 0 => Err(CreationError::Negative),
0 => Err(CreationError::Zero),
x => Ok(Self(x as u64)),
}
}
fn parse(s: &str) -> Result<Self, ParsePosNonzeroError> {
// TODO: change this to return an appropriate error instead of panicking
// when `parse()` returns an error.
let x: i64 = s.parse().unwrap();
Self::new(x).map_err(ParsePosNonzeroError::from_creation)
}
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_parse_error() {
assert!(matches!(
PositiveNonzeroInteger::parse("not a number"),
Err(ParsePosNonzeroError::ParseInt(_)),
));
}
#[test]
fn test_negative() {
assert_eq!(
PositiveNonzeroInteger::parse("-555"),
Err(ParsePosNonzeroError::Creation(CreationError::Negative)),
);
}
#[test]
fn test_zero() {
assert_eq!(
PositiveNonzeroInteger::parse("0"),
Err(ParsePosNonzeroError::Creation(CreationError::Zero)),
);
}
#[test]
fn test_positive() {
let x = PositiveNonzeroInteger::new(42).unwrap();
assert_eq!(x.0, 42);
assert_eq!(PositiveNonzeroInteger::parse("42"), Ok(x));
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/13_error_handling/errors3.rs | exercises/13_error_handling/errors3.rs | // This is a program that is trying to use a completed version of the
// `total_cost` function from the previous exercise. It's not working though!
// Why not? What should we do to fix it?
use std::num::ParseIntError;
// Don't change this function.
fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
let processing_fee = 1;
let cost_per_item = 5;
let qty = item_quantity.parse::<i32>()?;
Ok(qty * cost_per_item + processing_fee)
}
// TODO: Fix the compiler error by changing the signature and body of the
// `main` function.
fn main() {
let mut tokens = 100;
let pretend_user_input = "8";
// Don't change this line.
let cost = total_cost(pretend_user_input)?;
if cost > tokens {
println!("You can't afford that many!");
} else {
tokens -= cost;
println!("You now have {tokens} tokens.");
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/13_error_handling/errors1.rs | exercises/13_error_handling/errors1.rs | // TODO: This function refuses to generate text to be printed on a nametag if
// you pass it an empty string. It'd be nicer if it explained what the problem
// was instead of just returning `None`. Thankfully, Rust has a similar
// construct to `Option` that can be used to express error conditions. Change
// the function signature and body to return `Result<String, String>` instead
// of `Option<String>`.
fn generate_nametag_text(name: String) -> Option<String> {
if name.is_empty() {
// Empty names aren't allowed
None
} else {
Some(format!("Hi! My name is {name}"))
}
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn generates_nametag_text_for_a_nonempty_name() {
assert_eq!(
generate_nametag_text("Beyoncé".to_string()).as_deref(),
Ok("Hi! My name is Beyoncé"),
);
}
#[test]
fn explains_why_generating_nametag_text_fails() {
assert_eq!(
generate_nametag_text(String::new())
.as_ref()
.map_err(|e| e.as_str()),
Err("Empty names aren't allowed"),
);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/13_error_handling/errors4.rs | exercises/13_error_handling/errors4.rs | #[derive(PartialEq, Debug)]
enum CreationError {
Negative,
Zero,
}
#[derive(PartialEq, Debug)]
struct PositiveNonzeroInteger(u64);
impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<Self, CreationError> {
// TODO: This function shouldn't always return an `Ok`.
// Read the tests below to clarify what should be returned.
Ok(Self(value as u64))
}
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_creation() {
assert_eq!(
PositiveNonzeroInteger::new(10),
Ok(PositiveNonzeroInteger(10)),
);
assert_eq!(
PositiveNonzeroInteger::new(-10),
Err(CreationError::Negative),
);
assert_eq!(PositiveNonzeroInteger::new(0), Err(CreationError::Zero));
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/13_error_handling/errors5.rs | exercises/13_error_handling/errors5.rs | // This exercise is an altered version of the `errors4` exercise. It uses some
// concepts that we won't get to until later in the course, like `Box` and the
// `From` trait. It's not important to understand them in detail right now, but
// you can read ahead if you like. For now, think of the `Box<dyn ???>` type as
// an "I want anything that does ???" type.
//
// In short, this particular use case for boxes is for when you want to own a
// value and you care only that it is a type which implements a particular
// trait. To do so, the `Box` is declared as of type `Box<dyn Trait>` where
// `Trait` is the trait the compiler looks for on any value used in that
// context. For this exercise, that context is the potential errors which
// can be returned in a `Result`.
use std::error::Error;
use std::fmt;
#[derive(PartialEq, Debug)]
enum CreationError {
Negative,
Zero,
}
// This is required so that `CreationError` can implement `Error`.
impl fmt::Display for CreationError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let description = match *self {
CreationError::Negative => "number is negative",
CreationError::Zero => "number is zero",
};
f.write_str(description)
}
}
impl Error for CreationError {}
#[derive(PartialEq, Debug)]
struct PositiveNonzeroInteger(u64);
impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
match value {
x if x < 0 => Err(CreationError::Negative),
0 => Err(CreationError::Zero),
x => Ok(PositiveNonzeroInteger(x as u64)),
}
}
}
// TODO: Add the correct return type `Result<(), Box<dyn ???>>`. What can we
// use to describe both errors? Is there a trait which both errors implement?
fn main() {
let pretend_user_input = "42";
let x: i64 = pretend_user_input.parse()?;
println!("output={:?}", PositiveNonzeroInteger::new(x)?);
Ok(())
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/23_conversions/from_str.rs | exercises/23_conversions/from_str.rs | // This is similar to the previous `from_into` exercise. But this time, we'll
// implement `FromStr` and return errors instead of falling back to a default
// value. Additionally, upon implementing `FromStr`, you can use the `parse`
// method on strings to generate an object of the implementor type. You can read
// more about it in the documentation:
// https://doc.rust-lang.org/std/str/trait.FromStr.html
use std::num::ParseIntError;
use std::str::FromStr;
#[derive(Debug, PartialEq)]
struct Person {
name: String,
age: u8,
}
// We will use this error type for the `FromStr` implementation.
#[derive(Debug, PartialEq)]
enum ParsePersonError {
// Incorrect number of fields
BadLen,
// Empty name field
NoName,
// Wrapped error from parse::<u8>()
ParseInt(ParseIntError),
}
// TODO: Complete this `FromStr` implementation to be able to parse a `Person`
// out of a string in the form of "Mark,20".
// Note that you'll need to parse the age component into a `u8` with something
// like `"4".parse::<u8>()`.
//
// Steps:
// 1. Split the given string on the commas present in it.
// 2. If the split operation returns less or more than 2 elements, return the
// error `ParsePersonError::BadLen`.
// 3. Use the first element from the split operation as the name.
// 4. If the name is empty, return the error `ParsePersonError::NoName`.
// 5. Parse the second element from the split operation into a `u8` as the age.
// 6. If parsing the age fails, return the error `ParsePersonError::ParseInt`.
impl FromStr for Person {
type Err = ParsePersonError;
fn from_str(s: &str) -> Result<Self, Self::Err> {}
}
fn main() {
let p = "Mark,20".parse::<Person>();
println!("{p:?}");
}
#[cfg(test)]
mod tests {
use super::*;
use ParsePersonError::*;
#[test]
fn empty_input() {
assert_eq!("".parse::<Person>(), Err(BadLen));
}
#[test]
fn good_input() {
let p = "John,32".parse::<Person>();
assert!(p.is_ok());
let p = p.unwrap();
assert_eq!(p.name, "John");
assert_eq!(p.age, 32);
}
#[test]
fn missing_age() {
assert!(matches!("John,".parse::<Person>(), Err(ParseInt(_))));
}
#[test]
fn invalid_age() {
assert!(matches!("John,twenty".parse::<Person>(), Err(ParseInt(_))));
}
#[test]
fn missing_comma_and_age() {
assert_eq!("John".parse::<Person>(), Err(BadLen));
}
#[test]
fn missing_name() {
assert_eq!(",1".parse::<Person>(), Err(NoName));
}
#[test]
fn missing_name_and_age() {
assert!(matches!(",".parse::<Person>(), Err(NoName | ParseInt(_))));
}
#[test]
fn missing_name_and_invalid_age() {
assert!(matches!(
",one".parse::<Person>(),
Err(NoName | ParseInt(_)),
));
}
#[test]
fn trailing_comma() {
assert_eq!("John,32,".parse::<Person>(), Err(BadLen));
}
#[test]
fn trailing_comma_and_some_string() {
assert_eq!("John,32,man".parse::<Person>(), Err(BadLen));
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/23_conversions/try_from_into.rs | exercises/23_conversions/try_from_into.rs | // `TryFrom` is a simple and safe type conversion that may fail in a controlled
// way under some circumstances. Basically, this is the same as `From`. The main
// difference is that this should return a `Result` type instead of the target
// type itself. You can read more about it in the documentation:
// https://doc.rust-lang.org/std/convert/trait.TryFrom.html
#![allow(clippy::useless_vec)]
use std::convert::{TryFrom, TryInto};
#[derive(Debug, PartialEq)]
struct Color {
red: u8,
green: u8,
blue: u8,
}
// We will use this error type for the `TryFrom` conversions.
#[derive(Debug, PartialEq)]
enum IntoColorError {
// Incorrect length of slice
BadLen,
// Integer conversion error
IntConversion,
}
// TODO: Tuple implementation.
// Correct RGB color values must be integers in the 0..=255 range.
impl TryFrom<(i16, i16, i16)> for Color {
type Error = IntoColorError;
fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {}
}
// TODO: Array implementation.
impl TryFrom<[i16; 3]> for Color {
type Error = IntoColorError;
fn try_from(arr: [i16; 3]) -> Result<Self, Self::Error> {}
}
// TODO: Slice implementation.
// This implementation needs to check the slice length.
impl TryFrom<&[i16]> for Color {
type Error = IntoColorError;
fn try_from(slice: &[i16]) -> Result<Self, Self::Error> {}
}
fn main() {
// Using the `try_from` function.
let c1 = Color::try_from((183, 65, 14));
println!("{c1:?}");
// Since `TryFrom` is implemented for `Color`, we can use `TryInto`.
let c2: Result<Color, _> = [183, 65, 14].try_into();
println!("{c2:?}");
let v = vec![183, 65, 14];
// With slice we should use the `try_from` function
let c3 = Color::try_from(&v[..]);
println!("{c3:?}");
// or put the slice within round brackets and use `try_into`.
let c4: Result<Color, _> = (&v[..]).try_into();
println!("{c4:?}");
}
#[cfg(test)]
mod tests {
use super::*;
use IntoColorError::*;
#[test]
fn test_tuple_out_of_range_positive() {
assert_eq!(Color::try_from((256, 1000, 10000)), Err(IntConversion));
}
#[test]
fn test_tuple_out_of_range_negative() {
assert_eq!(Color::try_from((-1, -10, -256)), Err(IntConversion));
}
#[test]
fn test_tuple_sum() {
assert_eq!(Color::try_from((-1, 255, 255)), Err(IntConversion));
}
#[test]
fn test_tuple_correct() {
let c: Result<Color, _> = (183, 65, 14).try_into();
assert!(c.is_ok());
assert_eq!(
c.unwrap(),
Color {
red: 183,
green: 65,
blue: 14,
}
);
}
#[test]
fn test_array_out_of_range_positive() {
let c: Result<Color, _> = [1000, 10000, 256].try_into();
assert_eq!(c, Err(IntConversion));
}
#[test]
fn test_array_out_of_range_negative() {
let c: Result<Color, _> = [-10, -256, -1].try_into();
assert_eq!(c, Err(IntConversion));
}
#[test]
fn test_array_sum() {
let c: Result<Color, _> = [-1, 255, 255].try_into();
assert_eq!(c, Err(IntConversion));
}
#[test]
fn test_array_correct() {
let c: Result<Color, _> = [183, 65, 14].try_into();
assert!(c.is_ok());
assert_eq!(
c.unwrap(),
Color {
red: 183,
green: 65,
blue: 14
}
);
}
#[test]
fn test_slice_out_of_range_positive() {
let arr = [10000, 256, 1000];
assert_eq!(Color::try_from(&arr[..]), Err(IntConversion));
}
#[test]
fn test_slice_out_of_range_negative() {
let arr = [-256, -1, -10];
assert_eq!(Color::try_from(&arr[..]), Err(IntConversion));
}
#[test]
fn test_slice_sum() {
let arr = [-1, 255, 255];
assert_eq!(Color::try_from(&arr[..]), Err(IntConversion));
}
#[test]
fn test_slice_correct() {
let v = vec![183, 65, 14];
let c: Result<Color, _> = Color::try_from(&v[..]);
assert!(c.is_ok());
assert_eq!(
c.unwrap(),
Color {
red: 183,
green: 65,
blue: 14,
}
);
}
#[test]
fn test_slice_excess_length() {
let v = vec![0, 0, 0, 0];
assert_eq!(Color::try_from(&v[..]), Err(BadLen));
}
#[test]
fn test_slice_insufficient_length() {
let v = vec![0, 0];
assert_eq!(Color::try_from(&v[..]), Err(BadLen));
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/23_conversions/using_as.rs | exercises/23_conversions/using_as.rs | // Type casting in Rust is done via the usage of the `as` operator.
// Note that the `as` operator is not only used when type casting. It also helps
// with renaming imports.
fn average(values: &[f64]) -> f64 {
let total = values.iter().sum::<f64>();
// TODO: Make a conversion before dividing.
total / values.len()
}
fn main() {
let values = [3.5, 0.3, 13.0, 11.7];
println!("{}", average(&values));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn returns_proper_type_and_value() {
assert_eq!(average(&[3.5, 0.3, 13.0, 11.7]), 7.125);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/23_conversions/from_into.rs | exercises/23_conversions/from_into.rs | // The `From` trait is used for value-to-value conversions. If `From` is
// implemented, an implementation of `Into` is automatically provided.
// You can read more about it in the documentation:
// https://doc.rust-lang.org/std/convert/trait.From.html
#[derive(Debug)]
struct Person {
name: String,
age: u8,
}
// We implement the Default trait to use it as a fallback when the provided
// string is not convertible into a `Person` object.
impl Default for Person {
fn default() -> Self {
Self {
name: String::from("John"),
age: 30,
}
}
}
// TODO: Complete this `From` implementation to be able to parse a `Person`
// out of a string in the form of "Mark,20".
// Note that you'll need to parse the age component into a `u8` with something
// like `"4".parse::<u8>()`.
//
// Steps:
// 1. Split the given string on the commas present in it.
// 2. If the split operation returns less or more than 2 elements, return the
// default of `Person`.
// 3. Use the first element from the split operation as the name.
// 4. If the name is empty, return the default of `Person`.
// 5. Parse the second element from the split operation into a `u8` as the age.
// 6. If parsing the age fails, return the default of `Person`.
impl From<&str> for Person {
fn from(s: &str) -> Self {}
}
fn main() {
// Use the `from` function.
let p1 = Person::from("Mark,20");
println!("{p1:?}");
// Since `From` is implemented for Person, we are able to use `Into`.
let p2: Person = "Gerald,70".into();
println!("{p2:?}");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default() {
let dp = Person::default();
assert_eq!(dp.name, "John");
assert_eq!(dp.age, 30);
}
#[test]
fn test_bad_convert() {
let p = Person::from("");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_good_convert() {
let p = Person::from("Mark,20");
assert_eq!(p.name, "Mark");
assert_eq!(p.age, 20);
}
#[test]
fn test_bad_age() {
let p = Person::from("Mark,twenty");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_comma_and_age() {
let p: Person = Person::from("Mark");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_age() {
let p: Person = Person::from("Mark,");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_name() {
let p: Person = Person::from(",1");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_name_and_age() {
let p: Person = Person::from(",");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_name_and_invalid_age() {
let p: Person = Person::from(",one");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_trailing_comma() {
let p: Person = Person::from("Mike,32,");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_trailing_comma_and_some_string() {
let p: Person = Person::from("Mike,32,dog");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/23_conversions/as_ref_mut.rs | exercises/23_conversions/as_ref_mut.rs | // AsRef and AsMut allow for cheap reference-to-reference conversions. Read more
// about them at https://doc.rust-lang.org/std/convert/trait.AsRef.html and
// https://doc.rust-lang.org/std/convert/trait.AsMut.html, respectively.
// Obtain the number of bytes (not characters) in the given argument
// (`.len()` returns the number of bytes in a string).
// TODO: Add the `AsRef` trait appropriately as a trait bound.
fn byte_counter<T>(arg: T) -> usize {
arg.as_ref().len()
}
// Obtain the number of characters (not bytes) in the given argument.
// TODO: Add the `AsRef` trait appropriately as a trait bound.
fn char_counter<T>(arg: T) -> usize {
arg.as_ref().chars().count()
}
// Squares a number using `as_mut()`.
// TODO: Add the appropriate trait bound.
fn num_sq<T>(arg: &mut T) {
// TODO: Implement the function body.
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn different_counts() {
let s = "Café au lait";
assert_ne!(char_counter(s), byte_counter(s));
}
#[test]
fn same_counts() {
let s = "Cafe au lait";
assert_eq!(char_counter(s), byte_counter(s));
}
#[test]
fn different_counts_using_string() {
let s = String::from("Café au lait");
assert_ne!(char_counter(s.clone()), byte_counter(s));
}
#[test]
fn same_counts_using_string() {
let s = String::from("Cafe au lait");
assert_eq!(char_counter(s.clone()), byte_counter(s));
}
#[test]
fn mut_box() {
let mut num: Box<u32> = Box::new(3);
num_sq(&mut num);
assert_eq!(*num, 9);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/07_structs/structs1.rs | exercises/07_structs/structs1.rs | struct ColorRegularStruct {
// TODO: Add the fields that the test `regular_structs` expects.
// What types should the fields have? What are the minimum and maximum values for RGB colors?
}
struct ColorTupleStruct(/* TODO: Add the fields that the test `tuple_structs` expects */);
#[derive(Debug)]
struct UnitStruct;
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn regular_structs() {
// TODO: Instantiate a regular struct.
// let green =
assert_eq!(green.red, 0);
assert_eq!(green.green, 255);
assert_eq!(green.blue, 0);
}
#[test]
fn tuple_structs() {
// TODO: Instantiate a tuple struct.
// let green =
assert_eq!(green.0, 0);
assert_eq!(green.1, 255);
assert_eq!(green.2, 0);
}
#[test]
fn unit_structs() {
// TODO: Instantiate a unit struct.
// let unit_struct =
let message = format!("{unit_struct:?}s are fun!");
assert_eq!(message, "UnitStructs are fun!");
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/07_structs/structs2.rs | exercises/07_structs/structs2.rs | #[derive(Debug)]
struct Order {
name: String,
year: u32,
made_by_phone: bool,
made_by_mobile: bool,
made_by_email: bool,
item_number: u32,
count: u32,
}
fn create_order_template() -> Order {
Order {
name: String::from("Bob"),
year: 2019,
made_by_phone: false,
made_by_mobile: false,
made_by_email: true,
item_number: 123,
count: 0,
}
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn your_order() {
let order_template = create_order_template();
// TODO: Create your own order using the update syntax and template above!
// let your_order =
assert_eq!(your_order.name, "Hacker in Rust");
assert_eq!(your_order.year, order_template.year);
assert_eq!(your_order.made_by_phone, order_template.made_by_phone);
assert_eq!(your_order.made_by_mobile, order_template.made_by_mobile);
assert_eq!(your_order.made_by_email, order_template.made_by_email);
assert_eq!(your_order.item_number, order_template.item_number);
assert_eq!(your_order.count, 1);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/07_structs/structs3.rs | exercises/07_structs/structs3.rs | // Structs contain data, but can also have logic. In this exercise, we have
// defined the `Package` struct, and we want to test some logic attached to it.
#[derive(Debug)]
struct Package {
sender_country: String,
recipient_country: String,
weight_in_grams: u32,
}
impl Package {
fn new(sender_country: String, recipient_country: String, weight_in_grams: u32) -> Self {
if weight_in_grams < 10 {
// This isn't how you should handle errors in Rust, but we will
// learn about error handling later.
panic!("Can't ship a package with weight below 10 grams");
}
Self {
sender_country,
recipient_country,
weight_in_grams,
}
}
// TODO: Add the correct return type to the function signature.
fn is_international(&self) {
// TODO: Read the tests that use this method to find out when a package
// is considered international.
}
// TODO: Add the correct return type to the function signature.
fn get_fees(&self, cents_per_gram: u32) {
// TODO: Calculate the package's fees.
}
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic]
fn fail_creating_weightless_package() {
let sender_country = String::from("Spain");
let recipient_country = String::from("Austria");
Package::new(sender_country, recipient_country, 5);
}
#[test]
fn create_international_package() {
let sender_country = String::from("Spain");
let recipient_country = String::from("Russia");
let package = Package::new(sender_country, recipient_country, 1200);
assert!(package.is_international());
}
#[test]
fn create_local_package() {
let sender_country = String::from("Canada");
let recipient_country = sender_country.clone();
let package = Package::new(sender_country, recipient_country, 1200);
assert!(!package.is_international());
}
#[test]
fn calculate_transport_fees() {
let sender_country = String::from("Spain");
let recipient_country = String::from("Spain");
let cents_per_gram = 3;
let package = Package::new(sender_country, recipient_country, 1500);
assert_eq!(package.get_fees(cents_per_gram), 4500);
assert_eq!(package.get_fees(cents_per_gram * 2), 9000);
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
rust-lang/rustlings | https://github.com/rust-lang/rustlings/blob/7850a73d95c02840f4ab3bf8d9571b08410e5467/exercises/17_tests/tests1.rs | exercises/17_tests/tests1.rs | // Tests are important to ensure that your code does what you think it should
// do.
fn is_even(n: i64) -> bool {
n % 2 == 0
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
// TODO: Import `is_even`. You can use a wildcard to import everything in
// the outer module.
#[test]
fn you_can_assert() {
// TODO: Test the function `is_even` with some values.
assert!();
assert!();
}
}
| rust | MIT | 7850a73d95c02840f4ab3bf8d9571b08410e5467 | 2026-01-04T15:31:58.719144Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.