embassy_pico_mouse/build.rs

126 lines
3 KiB
Rust

use std::fmt;
enum Num<'a> {
Hex(&'a str),
Dec(i32),
}
impl<'a> fmt::Display for Num<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Num::Hex(h) => write!(f, "{h}"),
Num::Dec(d) => write!(f, "{d}"),
}
}
}
enum Variable<'a> {
Int(&'a str, Num<'a>),
String(&'a str, &'a str),
}
fn contains_string(variables: &[Variable]) -> bool {
variables.iter().any(|variable| match variable {
Variable::Int(_, _) => false,
Variable::String(_, _) => true,
})
}
fn create_config_struct(content: &str, path: &str, struct_name: &str) {
let variables: Vec<Variable<'_>> = content
.lines()
.map(|line| {
let mut split = line.split(':');
let name = split
.next()
.unwrap()
.trim()
.trim_start_matches('"')
.trim_end_matches('"');
let value = split.next().unwrap().trim();
if value.starts_with('"') {
let trimmed_string = value.trim_start_matches('"').trim_end_matches('"');
Variable::String(name, trimmed_string)
} else {
Variable::Int(
name,
if value.starts_with("0x") {
Num::Hex(value)
} else {
Num::Dec(str::parse(value).unwrap())
},
)
}
})
.collect();
let needs_lifetime = contains_string(&variables);
let mut file_string = String::new();
file_string += &format!("pub struct {struct_name}");
if needs_lifetime {
file_string += "<'a> ";
}
file_string += "{\n";
for variable in variables.iter() {
match variable {
Variable::Int(name, _value) => {
file_string += &format!("\tpub {name}: i32,\n");
}
Variable::String(name, _value) => {
file_string += &format!("\tpub {name}: &'a str,\n");
}
}
}
file_string += "}\n\n";
file_string += "impl";
if needs_lifetime {
file_string += "<'a> ";
}
file_string += struct_name;
if needs_lifetime {
file_string += "<'a> ";
}
file_string += "{\n";
file_string += "\tpub const fn new() -> Self {\n";
file_string += "\t\tSelf {\n";
for variable in variables.iter() {
match variable {
Variable::Int(name, value) => {
file_string += &format!("\t\t\t{name}: {value},\n");
}
Variable::String(name, value) => {
file_string += &format!("\t\t\t{name}: \"{value}\",\n");
}
}
}
file_string += "\t\t}\n";
file_string += "\t}\n";
file_string += "}\n";
std::fs::write(path, file_string).unwrap();
}
fn main() {
create_config_struct(
include_str!("mouse.conf"),
"src/mouse_hid/mouse_config.rs",
"MouseConfig",
);
}