const SPACE: u16 = b' ' as u16;
const TAB: u16 = b'\t' as u16;
const QUOTE: u16 = b'"' as u16;
const BACKSLASH: u16 = b'\\' as u16;
fn needs_quotes(arg: &[u16]) -> bool {
arg.is_empty() || arg.iter().any(|&c| c == SPACE || c == TAB)
}
pub fn join_wide(args: &[&[u16]]) -> Vec<u16> {
let mut cmd: Vec<u16> = Vec::new();
for (idx, arg) in args.iter().enumerate() {
if idx > 0 {
cmd.push(SPACE);
}
append_arg(&mut cmd, arg);
}
cmd
}
fn append_arg(cmd: &mut Vec<u16>, arg: &[u16]) {
let quote = needs_quotes(arg);
if quote {
cmd.push(QUOTE);
}
let mut backslashes: usize = 0;
for &x in arg {
if x == BACKSLASH {
backslashes += 1;
} else {
if x == QUOTE {
cmd.extend(std::iter::repeat_n(BACKSLASH, backslashes + 1));
}
backslashes = 0;
}
cmd.push(x);
}
if quote {
cmd.extend(std::iter::repeat_n(BACKSLASH, backslashes));
cmd.push(QUOTE);
}
}
pub fn first_token_and_rest_wide(cmd: &[u16]) -> Option<(Vec<u16>, Vec<u16>)> {
let mut i = 0usize;
while i < cmd.len() && (cmd[i] == SPACE || cmd[i] == TAB) {
i += 1;
}
if i >= cmd.len() {
return None;
}
let mut first = Vec::new();
if cmd[i] == QUOTE {
i += 1;
while i < cmd.len() && cmd[i] != QUOTE {
first.push(cmd[i]);
i += 1;
}
if i < cmd.len() {
i += 1; }
} else {
while i < cmd.len() && cmd[i] != SPACE && cmd[i] != TAB {
first.push(cmd[i]);
i += 1;
}
}
while i < cmd.len() && (cmd[i] == SPACE || cmd[i] == TAB) {
i += 1;
}
Some((first, cmd[i..].to_vec()))
}
pub fn first_token_wide(cmd: &[u16]) -> Option<Vec<u16>> {
first_token_and_rest_wide(cmd).map(|(first, _)| first)
}
#[cfg(test)]
#[path = "windows_tests.rs"]
mod windows_tests;