|
| 1 | +#![no_std] |
| 2 | +#![cfg_attr(test, no_main)] |
| 3 | + |
| 4 | +#![feature(custom_test_frameworks)] |
| 5 | +#![test_runner(crate::test_runner)] |
| 6 | +#![reexport_test_harness_main = "test_main"] |
| 7 | + |
| 8 | +/// add two numbers |
| 9 | +/// |
| 10 | +/// ``` |
| 11 | +/// #![no_std] |
| 12 | +/// #![no_main] |
| 13 | +/// use runner_doctest::{add, exit_qemu, ExitCode}; |
| 14 | +/// #[export_name = "_start"] |
| 15 | +/// extern "C" fn main() { |
| 16 | +/// assert_eq!(add(1, 2), 3); |
| 17 | +/// unsafe { exit_qemu(ExitCode::Success); } |
| 18 | +/// } |
| 19 | +/// ``` |
| 20 | +pub fn add(a: u32, b: u32) -> u32 { |
| 21 | + a + b |
| 22 | +} |
| 23 | + |
| 24 | +/// multiply two numbers |
| 25 | +/// |
| 26 | +/// ``` |
| 27 | +/// #![no_std] |
| 28 | +/// #![no_main] |
| 29 | +/// use runner_doctest::{mul, exit_qemu, ExitCode}; |
| 30 | +/// #[export_name = "_start"] |
| 31 | +/// extern "C" fn main() { |
| 32 | +/// assert_eq!(mul(2, 3), 6); |
| 33 | +/// unsafe { exit_qemu(ExitCode::Success); } |
| 34 | +/// } |
| 35 | +/// ``` |
| 36 | +pub fn mul(a: u32, b: u32) -> u32 { |
| 37 | + a * b |
| 38 | +} |
| 39 | + |
| 40 | +fn test_runner(tests: &[&dyn Fn()]) { |
| 41 | + for test in tests.iter() { |
| 42 | + test(); |
| 43 | + } |
| 44 | + |
| 45 | + unsafe { exit_qemu(ExitCode::Success); } |
| 46 | +} |
| 47 | + |
| 48 | +pub enum ExitCode { |
| 49 | + Success, |
| 50 | + Failed |
| 51 | +} |
| 52 | + |
| 53 | +impl ExitCode { |
| 54 | + fn code(&self) -> u32 { |
| 55 | + match self { |
| 56 | + ExitCode::Success => 0x10, |
| 57 | + ExitCode::Failed => 0x11, |
| 58 | + } |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +/// exit QEMU (see https://os.phil-opp.com/integration-tests/#shutting-down-qemu) |
| 63 | +pub unsafe fn exit_qemu(exit_code: ExitCode) { |
| 64 | + use x86_64::instructions::port::Port; |
| 65 | + |
| 66 | + let mut port = Port::<u32>::new(0xf4); |
| 67 | + port.write(exit_code.code()); |
| 68 | +} |
| 69 | + |
| 70 | +#[cfg(test)] |
| 71 | +#[no_mangle] |
| 72 | +pub extern "C" fn _start() -> ! { |
| 73 | + test_main(); |
| 74 | + |
| 75 | + unsafe { exit_qemu(ExitCode::Failed); } |
| 76 | + |
| 77 | + loop {} |
| 78 | +} |
| 79 | + |
| 80 | +#[panic_handler] |
| 81 | +fn panic(_info: &core::panic::PanicInfo) -> ! { |
| 82 | + unsafe { exit_qemu(ExitCode::Failed); } |
| 83 | + loop {} |
| 84 | +} |
0 commit comments