sprintf not happenin we go prefix/postfix now with templating

This commit is contained in:
Bel LaPointe
2023-03-23 11:25:07 -06:00
parent 3f0648dc3d
commit b3aa36b257
4 changed files with 63 additions and 2 deletions

View File

@@ -77,7 +77,7 @@ fn build_config_std() -> Config {
},
},
output: Stream {
format: None,
format: Some(String::from("%s")),
engine: Engine{
name: String::from("stdout"),
kafka: None,

View File

@@ -3,6 +3,8 @@ use crate::config::Stream;
use hidapi::HidApi;
use rusb::UsbContext;
use gilrs::{Gilrs, Button, Event};
use printf;
use std::os::raw::c_void;
pub trait InputStream {
fn get(&mut self) -> Vec<char>;
@@ -192,7 +194,37 @@ pub trait OutputStream {
}
pub fn build_output_stream(cfg: &Stream) -> Box<dyn OutputStream> {
return _build_output_stream(cfg)
return build_formatted_output_stream(cfg, _build_output_stream(cfg))
}
pub struct OutputStreamFormatted {
format: Option<String>,
stream: Box<dyn OutputStream>,
}
pub fn build_formatted_output_stream(cfg: &Stream, stream: Box<dyn OutputStream>) -> Box<dyn OutputStream> {
return Box::new(OutputStreamFormatted{
format: cfg.format.clone(),
stream: stream,
});
}
impl OutputStream for OutputStreamFormatted {
fn put(&mut self, v: Vec<char>) {
match self.format.as_ref() {
Some(x) => self.stream.put(sprintf(x, v)),
None => self.stream.put(v),
};
}
}
fn sprintf(format: &String, arg: Vec<char>) -> Vec<char> {
unsafe {
return printf::printf(
format.as_bytes().as_ptr() as *const i8,
arg.iter().cloned().collect::<String>().as_bytes().as_ptr() as *mut c_void,
).chars().collect();
}
}
pub fn _build_output_stream(cfg: &Stream) -> Box<dyn OutputStream> {
@@ -232,6 +264,17 @@ mod test_output {
fn _test_output_stream_impl(engine: &mut dyn OutputStream) {
engine.put("teehee".to_string().chars().collect());
}
#[test]
fn test_sprintf() {
assert_eq!(
"hello world".to_string().chars().collect::<Vec<char>>(),
sprintf(
&String::from("hello %s"),
String::from("world").chars().collect(),
),
);
}
}
pub struct OutputStreamUDP {