Skip to content
Myr

token.rs

This file

Path

src/exec/token.rs

98 lines · 3.2 KiB · Rust

Last changed by

Merge pull request #1510 from garlic-hub/clippyTavian Barnesbefore adoption4efc05e

History of this file

Take it

1use aho_corasick::AhoCorasick;2use std::fmt::{self, Display, Formatter};3use std::sync::OnceLock;45use super::ArgumentTemplate;67/// Designates what should be written to a buffer8///9/// Each `Token` contains either text, or a placeholder variant, which will be used to generate10/// commands after all tokens for a given command template have been collected.11#[derive(Clone, Debug, PartialEq, Eq)]12pub enum Token {13    Placeholder,14    Basename,15    Parent,16    NoExt,17    BasenameNoExt,18    Text(String),19}2021impl Display for Token {22    fn fmt(&self, f: &mut Formatter) -> fmt::Result {23        match *self {24            Token::Placeholder => f.write_str("{}")?,25            Token::Basename => f.write_str("{/}")?,26            Token::Parent => f.write_str("{//}")?,27            Token::NoExt => f.write_str("{.}")?,28            Token::BasenameNoExt => f.write_str("{/.}")?,29            Token::Text(ref string) => f.write_str(string)?,30        }31        Ok(())32    }33}3435static PLACEHOLDERS: OnceLock<AhoCorasick> = OnceLock::new();3637pub(super) fn tokenize(input: &str) -> ArgumentTemplate {38    // NOTE: we assume that { and } have the same length39    const BRACE_LEN: usize = '{'.len_utf8();40    let mut tokens = Vec::new();41    let mut remaining = input;42    let mut buf = String::new();43    let placeholders = PLACEHOLDERS.get_or_init(|| {44        AhoCorasick::new(["{{", "}}", "{}", "{/}", "{//}", "{.}", "{/.}"]).unwrap()45    });46    while let Some(m) = placeholders.find(remaining) {47        match m.pattern().as_u32() {48            0 | 1 => {49                // we found an escaped {{ or }}, so add50                // everything up to the first char to the buffer51                // then skip the second one.52                buf += &remaining[..m.start() + BRACE_LEN];53                remaining = &remaining[m.end()..];54            }55            id if !remaining[m.end()..].starts_with('}') => {56                buf += &remaining[..m.start()];57                if !buf.is_empty() {58                    tokens.push(Token::Text(std::mem::take(&mut buf)));59                }60                tokens.push(token_from_pattern_id(id));61                remaining = &remaining[m.end()..];62            }63            _ => {64                // We got a normal pattern, but the final "}"65                // is escaped, so add up to that to the buffer, then66                // skip the final }67                buf += &remaining[..m.end()];68                remaining = &remaining[m.end() + BRACE_LEN..];69            }70        }71    }72    // Add the rest of the string to the buffer, and add the final buffer to the tokens73    if !remaining.is_empty() {74        buf += remaining;75    }76    if tokens.is_empty() {77        // No placeholders were found, so just return the text78        return ArgumentTemplate::Text(buf);79    }80    // Add final text segment81    if !buf.is_empty() {82        tokens.push(Token::Text(buf));83    }84    debug_assert!(!tokens.is_empty());85    ArgumentTemplate::Tokens(tokens)86}8788fn token_from_pattern_id(id: u32) -> Token {89    use Token::*;90    match id {91        2 => Placeholder,92        3 => Basename,93        4 => Parent,94        5 => NoExt,95        6 => BasenameNoExt,96        _ => unreachable!(),97    }98}