summaryrefslogtreecommitdiffstats
path: root/bins/count/src/main.rs
blob: 6fd6f179fa5b6bad843fc805ef40705ada288f18 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//! count — stream-input consumer (ADR 0006 Phase 3 gate).
//!
//! Reads lines through `get_line` until EOF or Abort, then reports how
//! many it saw via `put_line`.  Proves: USE pre-drain, TIL truncation,
//! interactive pumping, and ^C abort across the task boundary.

#![no_std]
#![no_main]

use rsapi::{Exports, StreamResult};

#[panic_handler]
fn panic(_info: &core::panic::PanicInfo) -> ! {
    loop {
        core::hint::spin_loop();
    }
}

fn put_u32(exports: &Exports, mut v: u32) {
    // Small fixed buffer; u32 max is 10 digits.
    let mut buf = [0u8; 10];
    let mut i = buf.len();
    if v == 0 {
        i -= 1;
        buf[i] = b'0';
    }
    while v > 0 {
        i -= 1;
        buf[i] = b'0' + (v % 10) as u8;
        v /= 10;
    }
    let suffix = b" line(s)";
    let mut msg = [0u8; 18];
    let n = buf.len() - i;
    msg[..n].copy_from_slice(&buf[i..]);
    msg[n..n + suffix.len()].copy_from_slice(suffix);
    (exports.put_line)(rsapi::Line {
        ptr: msg.as_ptr(),
        len: n + suffix.len(),
    });
}

/// The image entry point — the loader jumps here with the ABI arguments.
#[unsafe(no_mangle)]
pub extern "C" fn efi_main(
    exports: &'static Exports,
    _argc: usize,
    _argv: *const rsapi::Arg,
) -> i32 {
    let mut count: u32 = 0;
    loop {
        let mut line = rsapi::Line {
            ptr: core::ptr::null(),
            len: 0,
        };
        match (exports.get_line)(&mut line) {
            StreamResult::Line => count += 1,
            StreamResult::Eof => break,
            StreamResult::Abort => return 130, // 128+SIGINT convention
        }
    }
    put_u32(exports, count);
    0
}