grippo 0.3.0

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
// Project:   grippo
// File:      src/windows/mod.rs
// Purpose:   A Windows command line split into arguments as the C runtime reads it
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A Windows command line split into arguments as the Microsoft C runtime
//! reads it, each argument a span of the line.
//!
//! [`argv`] gives the spans. [`normalised`] gives each span with its value,
//! the text the program receives, so a rule keyed on the value can't be
//! dodged by quoting: `-Pass"word"` reads as `-Password`. The rules are the
//! ones the C runtime has used since Visual C++ 2008, written up in
//! [Parsing C command-line arguments](https://learn.microsoft.com/en-us/cpp/c-language/parsing-c-command-line-arguments).
//!
//! The first argument is the program name and has its own rule. Only a
//! program that reads its line this way sees these values: cmd.exe, its
//! `^` escapes and `&` included, reads its own, and PowerShell reads command
//! text through [`powershell`].
//!
//! ```
//! use grippo::windows::normalised;
//!
//! let mut line = String::from(r#""C:\Tools\db.exe" -Pass"word" "hunter 2" --verbose"#);
//! let args: Vec<_> = normalised(&line).collect();
//! let secret = args
//!     .windows(2)
//!     .find(|pair| pair[0].value.eq_ignore_ascii_case("-password"))
//!     .map(|pair| pair[1].span.clone());
//! line.replace_range(secret.unwrap(), "[REDACTED]");
//! assert_eq!(line, r#""C:\Tools\db.exe" -Pass"word" [REDACTED] --verbose"#);
//! ```

use std::borrow::Cow;
use std::iter::{FusedIterator, repeat_n};
use std::ops::Range;

pub mod powershell;

/// One argument: where it sits in the line, and the text the program gets.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Arg<'a> {
    /// The argument as written, quotes and backslashes included, without the
    /// white space around it. The program name's span is empty when the line
    /// starts with white space.
    pub span: Range<usize>,
    /// The normalised form: the argument with its quoting read away. It
    /// borrows the line when the argument holds no `"`.
    pub value: Cow<'a, str>,
}

/// The arguments of a line as spans, the program name first. See [`argv`].
#[derive(Debug, Clone)]
pub struct Argv<'a> {
    line: &'a str,
    pos: usize,
    program_done: bool,
}

/// The arguments of a line with their values. See [`normalised`].
#[derive(Debug, Clone)]
pub struct Normalised<'a> {
    spans: Argv<'a>,
}

/// The spans of `line`'s arguments, read as the Microsoft C runtime reads them.
///
/// The first span is always the program name, and is empty for an empty line
/// or one that starts with a space or tab. Arguments are separated by spaces
/// and tabs only. A `"` opens and closes a quoted run, `\"` is a literal quote
/// and `""` inside a quoted run is one literal quote. A quoted run left open
/// at the end of the line takes the rest of it. Nothing is allocated.
#[must_use]
pub const fn argv(line: &str) -> Argv<'_> {
    Argv {
        line,
        pos: 0,
        program_done: false,
    }
}

/// The arguments of `line` with the values the program receives.
///
/// The spans are those of [`argv`]. Case isn't folded, so a rule that wants
/// `-PASSWORD` as well as `-Password` folds it.
#[must_use]
pub const fn normalised(line: &str) -> Normalised<'_> {
    Normalised { spans: argv(line) }
}

impl Iterator for Argv<'_> {
    type Item = Range<usize>;

    fn next(&mut self) -> Option<Range<usize>> {
        let bytes = self.line.as_bytes();
        if !self.program_done {
            self.program_done = true;
            self.pos = program_end(bytes);
            return Some(0..self.pos);
        }
        let mut start = self.pos;
        while matches!(bytes.get(start), Some(b' ' | b'\t')) {
            start += 1;
        }
        if start >= bytes.len() {
            self.pos = start;
            return None;
        }
        self.pos = arg_end(bytes, start);
        Some(start..self.pos)
    }
}

impl FusedIterator for Argv<'_> {}

impl<'a> Iterator for Normalised<'a> {
    type Item = Arg<'a>;

    fn next(&mut self) -> Option<Arg<'a>> {
        let program = !self.spans.program_done;
        let span = self.spans.next()?;
        let raw = self.spans.line.get(span.clone())?;
        let value = if program {
            strip_quotes(raw)
        } else {
            decode_arg(raw)
        };
        Some(Arg { span, value })
    }
}

impl FusedIterator for Normalised<'_> {}

/// The end of the program name: the first space or tab outside quotes.
/// A backslash is never an escape here.
fn program_end(bytes: &[u8]) -> usize {
    let mut in_quotes = false;
    for (i, &b) in bytes.iter().enumerate() {
        match b {
            b'"' => in_quotes = !in_quotes,
            b' ' | b'\t' if !in_quotes => return i,
            _ => {}
        }
    }
    bytes.len()
}

/// The end of the argument starting at `start`, a byte that isn't white space.
fn arg_end(bytes: &[u8], start: usize) -> usize {
    let mut i = start;
    let mut in_quotes = false;
    loop {
        let mut slashes = 0_usize;
        while bytes.get(i) == Some(&b'\\') {
            i += 1;
            slashes += 1;
        }
        if bytes.get(i) == Some(&b'"') && slashes.is_multiple_of(2) {
            if in_quotes && bytes.get(i + 1) == Some(&b'"') {
                i += 1;
            } else {
                in_quotes = !in_quotes;
            }
        }
        match bytes.get(i) {
            None => return i,
            Some(b' ' | b'\t') if !in_quotes => return i,
            Some(_) => i += 1,
        }
    }
}

fn strip_quotes(raw: &str) -> Cow<'_, str> {
    if raw.contains('"') {
        Cow::Owned(raw.replace('"', ""))
    } else {
        Cow::Borrowed(raw)
    }
}

/// An argument's value. Backslashes count only in front of a `"`: 2n of them
/// make n and a quote that toggles, 2n + 1 make n and a literal `"`.
fn decode_arg(raw: &str) -> Cow<'_, str> {
    if !raw.contains('"') {
        return Cow::Borrowed(raw);
    }
    let mut out = String::with_capacity(raw.len());
    let mut in_quotes = false;
    let mut chars = raw.chars().peekable();
    loop {
        let mut slashes = 0_usize;
        while chars.next_if_eq(&'\\').is_some() {
            slashes += 1;
        }
        if chars.next_if_eq(&'"').is_some() {
            out.extend(repeat_n('\\', slashes / 2));
            if slashes % 2 == 1 || (in_quotes && chars.next_if_eq(&'"').is_some()) {
                out.push('"');
            } else {
                in_quotes = !in_quotes;
            }
        } else {
            out.extend(repeat_n('\\', slashes));
            let Some(c) = chars.next() else {
                return Cow::Owned(out);
            };
            out.push(c);
        }
    }
}

#[cfg(test)]
mod tests;