binary_mirror_derive/lib.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, Data, DeriveInput, Fields, LitStr};
#[proc_macro_derive(BinaryMirror, attributes(bm))]
pub fn binary_mirror_derive(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
impl_binary_mirror(&input)
}
#[proc_macro_derive(BinaryEnum, attributes(bv))]
pub fn binary_enum_derive(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
impl_binary_enum(&input)
}
#[derive(Debug)]
struct FieldAttrs {
type_name: String,
alias: Option<String>,
format: Option<String>,
datetime_with: Option<String>,
skip: bool,
enum_type: Option<String>,
}
fn impl_binary_mirror(input: &DeriveInput) -> TokenStream {
let name = &input.ident;
let fields = match &input.data {
Data::Struct(data) => match &data.fields {
Fields::Named(fields) => &fields.named,
_ => panic!("Only named fields are supported"),
},
_ => panic!("Only structs are supported"),
};
let field_debugs: Vec<_> = fields
.iter()
.filter_map(|f| {
let field_name = &f.ident;
Some(quote! {
.field(
stringify!(#field_name),
&format_args!("hex: [{}], bytes: \"{}\"",
self.#field_name
.iter()
.map(|b| format!("0x{:02x}", b))
.collect::<Vec<_>>()
.join(", "),
self.#field_name
.iter()
.map(|&b| {
match b {
0x0A => "\\n".to_string(),
0x0D => "\\r".to_string(),
0x09 => "\\t".to_string(),
0x20..=0x7E => (b as char).to_string(),
_ => format!("\\x{:02x}", b),
}
})
.collect::<Vec<String>>()
.join("")
)
)
})
})
.collect();
let methods: Vec<_> = fields
.iter()
.filter_map(|field| {
let field_name = &field.ident;
get_field_attrs(&field.attrs).map(|attrs| {
let method_name = if let Some(alias) = &attrs.alias {
if attrs.type_name != "date" || attrs.datetime_with.is_none() {
quote::format_ident!("{}", alias)
} else {
field_name.clone().unwrap()
}
} else {
field_name.clone().unwrap()
};
let base_method = match attrs.type_name.as_str() {
"str" => quote! {
pub fn #method_name(&self) -> String {
String::from_utf8_lossy(&self.#field_name).trim().to_string()
}
},
"i32" | "i64" | "u32" | "u64" | "f32" | "f64" => {
let type_ident = quote::format_ident!("{}", attrs.type_name);
quote! {
pub fn #method_name(&self) -> Option<#type_ident> {
String::from_utf8_lossy(&self.#field_name)
.trim()
.parse::<#type_ident>()
.ok()
}
}
},
"decimal" => quote! {
pub fn #method_name(&self) -> Option<rust_decimal::Decimal> {
String::from_utf8_lossy(&self.#field_name)
.trim()
.parse::<rust_decimal::Decimal>()
.ok()
}
},
"date" => {
let format = attrs.format.unwrap_or_else(|| "%Y%m%d".to_string());
let date_method = quote! {
pub fn #method_name(&self) -> Option<chrono::NaiveDate> {
chrono::NaiveDate::parse_from_str(
String::from_utf8_lossy(&self.#field_name).trim(),
#format
).ok()
}
};
if let Some(time_field) = &attrs.datetime_with {
let datetime_name = if let Some(datetime_alias) = attrs.alias {
quote::format_ident!("{}", datetime_alias)
} else {
quote::format_ident!("datetime")
};
let time_ident = quote::format_ident!("{}", time_field);
quote! {
#date_method
pub fn #datetime_name(&self) -> Option<chrono::NaiveDateTime> {
let date = chrono::NaiveDate::parse_from_str(
String::from_utf8_lossy(&self.#field_name).trim(),
#format
).ok()?;
let time = self.#time_ident()?;
Some(chrono::NaiveDateTime::new(date, time))
}
}
} else {
date_method
}
},
"time" => {
let format = attrs.format.unwrap_or_else(|| "%H%M%S".to_string());
quote! {
pub fn #method_name(&self) -> Option<chrono::NaiveTime> {
chrono::NaiveTime::parse_from_str(
String::from_utf8_lossy(&self.#field_name).trim(),
#format
).ok()
}
}
},
"enum" => {
let enum_type = attrs.enum_type.as_ref()
.expect("enum_type attribute is required for enum type");
let enum_ident = quote::format_ident!("{}", enum_type);
quote! {
pub fn #method_name(&self) -> Option<#enum_ident> {
#enum_ident::from_bytes(&self.#field_name)
}
}
},
_ => panic!("Unsupported type: {}", attrs.type_name),
};
base_method
})
})
.collect();
let display_fields: Vec<_> = fields
.iter()
.filter_map(|field| {
let field_name = &field.ident;
get_field_attrs(&field.attrs).and_then(|attrs| {
if attrs.skip && (attrs.type_name != "date" || attrs.datetime_with.is_none()) {
return None;
}
let method_name = if let Some(alias) = &attrs.alias {
if attrs.type_name != "date" || attrs.datetime_with.is_none() {
quote::format_ident!("{}", alias)
} else {
field_name.clone().unwrap()
}
} else {
field_name.clone().unwrap()
};
let tokens = match attrs.type_name.as_str() {
"str" => quote! {
write!(f, "{}: {}", stringify!(#method_name), self.#method_name())?;
},
"i32" | "i64" | "u32" | "u64" | "f32" | "f64" => quote! {
match self.#method_name() {
Some(val) => write!(f, "{}: {}", stringify!(#method_name), val)?,
None => write!(f, "{}: <invalid>", stringify!(#method_name))?,
}
},
"decimal" => quote! {
match self.#method_name() {
Some(val) => write!(f, "{}: {}", stringify!(#method_name), val.normalize())?,
None => write!(f, "{}: <invalid>", stringify!(#method_name))?,
}
},
"date" => {
if attrs.skip {
if let Some(_) = &attrs.datetime_with {
let datetime_name = if let Some(datetime_alias) = attrs.alias {
quote::format_ident!("{}", datetime_alias)
} else {
quote::format_ident!("datetime")
};
quote! {
match self.#datetime_name() {
Some(val) => write!(f, "{}: {}", stringify!(#datetime_name), val.format("%Y-%m-%dT%H:%M:%S"))?,
None => write!(f, "{}: <invalid>", stringify!(#datetime_name))?,
}
}
} else {
return None;
}
} else {
let mut tokens = quote! {
match self.#method_name() {
Some(val) => write!(f, "{}: {}", stringify!(#method_name), val)?,
None => write!(f, "{}: <invalid>", stringify!(#method_name))?,
}
};
if let Some(_) = &attrs.datetime_with {
let datetime_name = if let Some(datetime_alias) = attrs.alias {
quote::format_ident!("{}", datetime_alias)
} else {
quote::format_ident!("datetime")
};
tokens = quote! {
#tokens
write!(f, ", ")?;
match self.#datetime_name() {
Some(val) => write!(f, "{}: {}", stringify!(#datetime_name), val.format("%Y-%m-%dT%H:%M:%S"))?,
None => write!(f, "{}: <invalid>", stringify!(#datetime_name))?,
}
};
}
tokens
}
},
"time" => quote! {
match self.#method_name() {
Some(val) => write!(f, "{}: {}", stringify!(#method_name), val)?,
None => write!(f, "{}: <invalid>", stringify!(#method_name))?,
}
},
"enum" => quote! {
match self.#method_name() {
Some(val) => write!(f, "{}: {:?}", stringify!(#method_name), val)?,
None => write!(f, "{}: <invalid>", stringify!(#method_name))?,
}
},
_ => quote! {},
};
Some(tokens)
})
})
.collect();
let gen = quote! {
impl #name {
#(#methods)*
/// Create a new instance from bytes
/// Returns Err if the bytes length doesn't match the struct size
pub fn from_bytes(bytes: &[u8]) -> Result<&Self, binary_mirror::BytesSizeError> {
let expected = Self::size();
let actual = bytes.len();
if actual != expected {
return Err(binary_mirror::BytesSizeError::new(
expected,
actual,
bytes.iter()
.map(|&b| {
match b {
0x0A => "\\n".to_string(),
0x0D => "\\r".to_string(),
0x09 => "\\t".to_string(),
0x20..=0x7E => (b as char).to_string(),
_ => format!("\\x{:02x}", b),
}
})
.collect::<Vec<String>>()
.join("")
));
}
// Safety:
// 1. We've verified the size matches
// 2. The struct is #[repr(C)]
// 3. The alignment is handled by the compiler
Ok(unsafe { &*(bytes.as_ptr() as *const Self) })
}
/// Get the size of the struct in bytes
pub fn size() -> usize {
std::mem::size_of::<Self>()
}
}
impl std::fmt::Debug for #name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct(stringify!(#name))
#(#field_debugs)*
.finish()
}
}
impl std::fmt::Display for #name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} {{ ", stringify!(#name))?;
let mut first = true;
#(
if first {
first = false;
} else {
write!(f, ", ")?;
}
#display_fields
)*
write!(f, " }}")
}
}
};
gen.into()
}
fn get_field_attrs(attrs: &[syn::Attribute]) -> Option<FieldAttrs> {
for attr in attrs {
if attr.path().is_ident("bm") {
let mut field_attrs = FieldAttrs {
type_name: String::new(),
alias: None,
format: None,
datetime_with: None,
skip: false,
enum_type: None,
};
let _ = attr.parse_nested_meta(|meta| {
if meta.path.is_ident("type") {
let lit = meta.value()?.parse::<LitStr>()?;
field_attrs.type_name = lit.value();
} else if meta.path.is_ident("alias") {
let lit = meta.value()?.parse::<LitStr>()?;
field_attrs.alias = Some(lit.value());
} else if meta.path.is_ident("format") {
let lit = meta.value()?.parse::<LitStr>()?;
field_attrs.format = Some(lit.value());
} else if meta.path.is_ident("datetime_with") {
let lit = meta.value()?.parse::<LitStr>()?;
field_attrs.datetime_with = Some(lit.value());
} else if meta.path.is_ident("skip") {
field_attrs.skip = meta.value()?.parse::<syn::LitBool>()?.value();
} else if meta.path.is_ident("enum_type") {
let lit = meta.value()?.parse::<LitStr>()?;
field_attrs.enum_type = Some(lit.value());
}
Ok(())
});
if !field_attrs.type_name.is_empty() {
return Some(field_attrs);
}
}
}
None
}
fn get_variant_value(attrs: &[syn::Attribute]) -> Option<u8> {
for attr in attrs {
if attr.path().is_ident("bv") {
let mut byte_value = None;
let _ = attr.parse_nested_meta(|meta| {
if meta.path.is_ident("value") {
let lit = meta.value()?.parse::<syn::LitByteStr>()?;
if let Some(&value) = lit.value().first() {
byte_value = Some(value);
}
}
Ok(())
});
return byte_value;
}
}
None
}
fn impl_binary_enum(input: &DeriveInput) -> TokenStream {
let name = &input.ident;
let variants = match &input.data {
Data::Enum(data) => &data.variants,
_ => panic!("BinaryEnum can only be derived for enums"),
};
let match_arms = variants.iter().map(|variant| {
let variant_ident = &variant.ident;
let byte_value = get_variant_value(&variant.attrs)
.unwrap_or_else(|| {
let variant_str = variant_ident.to_string().to_uppercase();
variant_str.chars().next().unwrap() as u8
});
quote! {
Some(#byte_value) => Some(Self::#variant_ident),
}
});
let gen = quote! {
impl #name {
pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
match bytes.get(0) {
#(#match_arms)*
_ => None,
}
}
}
};
gen.into()
}
#[cfg(test)]
mod tests {
#[test]
fn test_basic_derive() {
// Tests will go here
}
}