use crate::{Error, Result};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginOptions {
name: String,
arguments: Vec<String>,
}
impl PluginOptions {
pub fn new(
name: impl Into<String>,
arguments: impl IntoIterator<Item = impl Into<String>>,
) -> Self {
Self {
name: name.into(),
arguments: arguments.into_iter().map(Into::into).collect(),
}
}
pub fn without_arguments(name: impl Into<String>) -> Self {
Self::new(name, std::iter::empty::<String>())
}
pub(crate) fn append_to(&self, values: &mut Vec<String>) {
values.push(self.name.clone());
values.extend(self.arguments.iter().cloned());
}
pub(crate) fn validate_not_memory(&self, field: &'static str) -> Result<()> {
if self.name.eq_ignore_ascii_case("memory") {
return Err(Error::InvalidArgument {
field,
message: "use the typed memory endpoint variant for the memory plugin".to_owned(),
});
}
Ok(())
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PluginChain(Vec<PluginOptions>);
impl PluginChain {
pub fn new() -> Self {
Self::default()
}
pub fn push(&mut self, plugin: PluginOptions) {
self.0.push(plugin);
}
pub fn iter(&self) -> impl ExactSizeIterator<Item = &PluginOptions> {
self.0.iter()
}
}
impl From<Vec<PluginOptions>> for PluginChain {
fn from(value: Vec<PluginOptions>) -> Self {
Self(value)
}
}
pub(crate) fn processor_plugins(
application: &str,
input: Option<&PluginOptions>,
processors: &PluginChain,
output: Option<&PluginOptions>,
) -> Vec<u8> {
let mut values = vec![application.to_owned()];
if let Some(input) = input {
values.push("-I".to_owned());
input.append_to(&mut values);
}
for plugin in processors.iter() {
values.push("-P".to_owned());
plugin.append_to(&mut values);
}
if let Some(output) = output {
values.push("-O".to_owned());
output.append_to(&mut values);
}
encode_multistring(&values)
}
pub(crate) fn encode_multistring(values: &[String]) -> Vec<u8> {
let mut units = Vec::new();
for (index, value) in values.iter().enumerate() {
if index != 0 {
units.push(0xffff);
}
units.push(0xfeff);
units.extend(value.encode_utf16());
}
units.into_iter().flat_map(u16::to_ne_bytes).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn serializer_preserves_plugin_order() {
let bytes = processor_plugins(
"rustduck",
Some(&PluginOptions::new("file", ["input.ts"])),
&PluginChain::from(vec![PluginOptions::new("filter", ["--service", "1"])]),
Some(&PluginOptions::without_arguments("drop")),
);
let units = bytes
.chunks_exact(2)
.map(|bytes| u16::from_ne_bytes([bytes[0], bytes[1]]))
.collect::<Vec<_>>();
assert_eq!(units[0], 0xfeff);
assert!(units.contains(&0xffff));
assert!(units.iter().filter(|&&unit| unit == 0xfeff).count() > 1);
}
}