use alloc::string::String;
use alloc::vec::Vec;
#[derive(Clone)]
pub enum GradeStatus {
Pass,
Fail,
}
#[derive(Clone)]
pub struct GradeDetail {
pub status: GradeStatus,
pub prefix: &'static str, pub message: String,
}
#[derive(Clone)]
pub struct TaskResult {
pub task_id: usize,
pub name: &'static str,
pub points: u32,
pub details: Vec<GradeDetail>,
}
impl TaskResult {
pub fn passed(&self) -> bool {
self.details
.iter()
.all(|d| matches!(d.status, GradeStatus::Pass))
}
pub fn score(&self) -> u32 {
if self.passed() {
self.points
} else {
0
}
}
}
pub trait Grade {
fn chapter_number(&self) -> u32;
fn chapter_name(&self) -> &'static str;
fn total_tasks(&self) -> usize;
fn total_points(&self) -> u32;
fn check_all(&mut self);
fn results(&self) -> &[TaskResult];
fn show_report(&self) {
use crate::serial_println;
serial_println!();
serial_println!("========================================");
serial_println!(
" Chapter {} {} - Grading Report",
self.chapter_number(),
self.chapter_name()
);
serial_println!("========================================");
for r in self.results() {
for d in &r.details {
let mark = match d.status {
GradeStatus::Pass => "[PASS]",
GradeStatus::Fail => "[FAIL]",
};
serial_println!(
"{} Task {}: {} ({} points)",
mark,
r.task_id,
r.name,
r.points
);
serial_println!(" {} {}", d.prefix, d.message);
}
}
let completed = self.results().iter().filter(|r| r.passed()).count();
let total = self.total_tasks();
let score: u32 = self.results().iter().map(|r| r.score()).sum();
serial_println!();
serial_println!("========================================");
serial_println!("Completed: {}/{} tasks", completed, total);
serial_println!("Score: {}/{}", score, self.total_points());
serial_println!("========================================");
serial_println!();
}
}
pub fn run_all_graders(graders: &mut [&mut dyn Grade]) {
for grader in graders.iter_mut() {
grader.check_all();
grader.show_report();
}
}
pub fn pass(msg: impl Into<String>) -> GradeDetail {
GradeDetail {
status: GradeStatus::Pass,
prefix: "+",
message: msg.into(),
}
}
pub fn fail(msg: impl Into<String>) -> GradeDetail {
GradeDetail {
status: GradeStatus::Fail,
prefix: "x",
message: msg.into(),
}
}
pub fn check_condition(
cond: bool,
pass_msg: impl Into<String>,
fail_msg: impl Into<String>,
) -> GradeDetail {
if cond {
pass(pass_msg)
} else {
fail(fail_msg)
}
}
pub mod chapter5_syscall;
pub mod chapter6_process;
pub mod chapter8_elf;
pub mod chapter9_shell;