garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /records/src/start.rs

raw

//! The start message a command is given: what Rust's std on Pinnacle reads
//! at entry when a program is started with `abi::STD_START` (its
//! `sys/pal/pinnacle/start.rs`), so the terminal starts a std program and a
//! record-speaking one the same way.
//!
//! - the arguments: a u32 count, then each as a u32 length and its bytes;
//! - the environment: a u32 count, then each as a key and a value, each a
//!   u32 length and its bytes;
//! - stdin, stdout, stderr: a byte each, [`CONSOLE`], [`NULL`] or
//!   [`CHANNEL`]; the channels among them are the message's handles, in
//!   that order.

use alloc::string::String;
use alloc::vec::Vec;

use crate::{Reader, put_bytes, put_str};

pub const CONSOLE: u8 = 0;
pub const NULL: u8 = 1;
pub const CHANNEL: u8 = 2;

/// What a program was started with. The streams say only how each goes;
/// the channels among them are the message's handles, in order.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Start {
    pub args: Vec<String>,
    pub env: Vec<(String, String)>,
    /// stdin, stdout, stderr: [`CONSOLE`], [`NULL`] or [`CHANNEL`].
    pub streams: [u8; 3],
}

impl Start {
    pub fn encode(&self) -> Vec<u8> {
        let mut out = Vec::new();
        out.extend_from_slice(&(self.args.len() as u32).to_le_bytes());
        for arg in &self.args {
            put_str(&mut out, arg);
        }
        out.extend_from_slice(&(self.env.len() as u32).to_le_bytes());
        for (key, value) in &self.env {
            put_bytes(&mut out, key.as_bytes());
            put_bytes(&mut out, value.as_bytes());
        }
        out.extend_from_slice(&self.streams);
        out
    }

    pub fn decode(message: &[u8]) -> Option<Start> {
        let r = &mut Reader(message);
        let mut start = Start::default();
        for _ in 0..r.u32()? {
            start.args.push(r.string()?);
        }
        for _ in 0..r.u32()? {
            let key = r.string()?;
            start.env.push((key, r.string()?));
        }
        start.streams = r.take(3)?.try_into().ok()?;
        if start.streams.iter().any(|&s| s > CHANNEL) {
            return None;
        }
        Some(start)
    }

    /// Where stream `n` (0 stdin, 1 stdout, 2 stderr) is among the
    /// message's handles, if it is a channel.
    pub fn handle_index(&self, n: usize) -> Option<usize> {
        (self.streams[n] == CHANNEL).then(|| self.streams[..n].iter().filter(|&&s| s == CHANNEL).count())
    }
}

/// The environment variable a command's working folder comes in, as
/// `disk:/path` (`data:/notes`).
pub const PWD: &str = "PWD";

/// `path` as seen from the folder `cwd` (`disk:/path`, see [`PWD`]): a
/// whole path (`system:/fonts`), one from the root of `cwd`'s disk
/// (`/fonts`), from `home` (`~/x`), or from `cwd`, with `.` and `..`
/// worked out (`..` stops at the disk's root). Always `disk:/path`, with
/// no `/` at the end but the root's.
pub fn resolve(cwd: &str, home: &str, path: &str) -> String {
    let (disk, rest) = match path.split_once(":/").filter(|(d, _)| !d.contains('/')) {
        Some((disk, rest)) => (disk, String::from(rest)),
        None => {
            let (base, rel) = match path.strip_prefix('~') {
                Some(rel) if rel.is_empty() || rel.starts_with('/') => (home, rel),
                _ => (cwd, path),
            };
            let (disk, folder) = base.split_once(":/").unwrap_or(("data", base));
            match rel.starts_with('/') {
                true => (disk, String::from(rel)),
                false => (disk, alloc::format!("{folder}/{rel}")),
            }
        }
    };
    let mut parts: Vec<&str> = Vec::new();
    for part in rest.split('/') {
        match part {
            "" | "." => {}
            ".." => {
                parts.pop();
            }
            p => parts.push(p),
        }
    }
    alloc::format!("{disk}:/{}", parts.join("/"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;

    #[test]
    fn paths_resolve_from_the_working_folder() {
        let r = |cwd, path| resolve(cwd, "data:/", path);
        assert_eq!(r("data:/", "notes"), "data:/notes");
        assert_eq!(r("data:/notes", "a/../b/./c"), "data:/notes/b/c");
        assert_eq!(r("data:/notes", ".."), "data:/");
        assert_eq!(r("data:/", "../.."), "data:/", "no higher than the root");
        assert_eq!(r("data:/notes", "/fonts"), "data:/fonts");
        assert_eq!(r("data:/notes", "system:/fonts/"), "system:/fonts");
        assert_eq!(r("system:/apps", "~"), "data:/");
        assert_eq!(r("system:/apps", "~/notes"), "data:/notes");
        assert_eq!(r("system:/apps", "~x"), "system:/apps/~x");
        assert_eq!(r("system:/", "."), "system:/");
    }

    #[test]
    fn round_trips() {
        let start = Start {
            args: vec!["devices".into(), "--all".into()],
            env: vec![("LANG".into(), "nl".into())],
            streams: [NULL, CHANNEL, CHANNEL],
        };
        let bytes = start.encode();
        assert_eq!(Start::decode(&bytes), Some(start.clone()));
        assert_eq!(start.handle_index(0), None);
        assert_eq!(start.handle_index(1), Some(0));
        assert_eq!(start.handle_index(2), Some(1));
    }

    /// The bytes std's own `start::message` writes for one argument, no
    /// environment, stdout a channel: the format is std's, not ours.
    #[test]
    fn matches_std() {
        let start = Start {
            args: vec!["x".into()],
            env: vec![],
            streams: [CONSOLE, CHANNEL, NULL],
        };
        assert_eq!(
            start.encode(),
            [1, 0, 0, 0, 1, 0, 0, 0, b'x', 0, 0, 0, 0, 0, 2, 1]
        );
        assert_eq!(Start::decode(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3]), None);
    }
}