Switch the macro to be const instead of dynamic

This commit is contained in:
Dandaedre 2025-02-18 22:05:53 +01:00 committed by Dandaedre
parent 84564a9199
commit 65502297b7
7 changed files with 53 additions and 31 deletions

View File

@ -7,3 +7,5 @@ version.workspace = true
more_fields_macro = {path ="../more_fields_macro"}
pretty_assertions = "1.4.1"
[features]
expand_macro = []

View File

@ -4,21 +4,37 @@
//! Note that this map is implemented without self, allowing us to use it only as a generic,
//! however this limitation is completely artificial
pub use more_fields_macro::FieldsAsMap;
pub use more_fields_macro::FieldsAsSlice;
pub trait FieldsAsMap {
fn attributes_map() -> Vec<(&'static str, &'static str)>;
pub trait FieldsAsSlice {
fn attributes_slice() -> &'static [(&'static str, &'static str)];
}
// fn iter(&self) -> std::vec::IntoIter<(&'static str, &'static str)>;
// #[cfg(feature = "expand_macro")]
// #[derive(FieldsAsSlice, Default)]
// struct Bob {
// #[TEXT]
// field_ouane: u16,
// #[INTEGER]
// field_2: u16,
// #[BLOB]
// field_3: u16,
// #[NULL]
// field_4: u16,
// #[REAL]
// field_5: u16,
// field_6: u16,
// }
#[cfg(test)]
mod test {
use crate::FieldsAsMap;
use crate::FieldsAsSlice;
use pretty_assertions::assert_eq;
#[allow(dead_code)]
#[derive(FieldsAsMap, Default)]
#[derive(FieldsAsSlice, Default)]
struct Bob {
#[TEXT]
field_ouane: u16,
@ -34,7 +50,7 @@ mod test {
}
#[test]
fn test_derive_impl() {
println!("{:?}", Bob::attributes_map());
println!("{:?}", Bob::attributes_slice());
// assert!(
let b_hash = vec![
("field_ouane", "TEXT"),
@ -45,6 +61,6 @@ mod test {
("field_6", "TEXT"),
];
assert_eq!(Bob::attributes_map(), b_hash);
assert_eq!(Bob::attributes_slice(), b_hash);
}
}

View File

@ -17,10 +17,11 @@ extern crate proc_macro;
use proc_macro::{Span, TokenStream};
use quote::quote;
use syn::DeriveInput;
use syn::Ident;
use syn::parse_macro_input;
use syn::{Data, Fields};
#[proc_macro_derive(FieldsAsMap, attributes(INTEGER, NULL, REAL, TEXT, BLOB))]
#[proc_macro_derive(FieldsAsSlice, attributes(INTEGER, NULL, REAL, TEXT, BLOB))]
pub fn derive_iterable(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
@ -53,17 +54,20 @@ pub fn derive_iterable(input: TokenStream) -> TokenStream {
}
});
let name_of_static_str = struct_name.to_string().to_ascii_uppercase() + "_ATTR_SLICE";
let name_of_static = Ident::new(&name_of_static_str, Span::call_site().into());
// static STATIC_FIELDS_OF_STRUCT_#struct_name: std::sync::LazyLock<Vec<(&'static str, &'static str)>> =
// std::sync::LazyLock::new(|| vec![]);
// const FIELD_NAMES_AS_SLICE: &'static [&'static str] = &[#(#fields_iter),*];
// and add Self::FIELD_NAMES_AS_SLICE
//
let expanded = quote! {
impl FieldsAsMap for #struct_name {
fn attributes_map<'a>() -> Vec<(&'static str, &'static str)> {
vec![
#(#fields_iter),*
]
const #name_of_static: &[(&str, &str)] = &[
#(#fields_iter),*
];
impl FieldsAsSlice for #struct_name {
fn attributes_slice<'a>() -> &'static [(&'static str, &'static str)] {
#name_of_static
}
}
};

View File

@ -14,7 +14,7 @@ pub fn get_data<T>(
table_name: &str,
) -> Result<Vec<T>, serde_rusqlite::Error>
where
T: DeserializeOwned + more_fields::FieldsAsMap,
T: DeserializeOwned + more_fields::FieldsAsSlice,
{
let mut query_result = conn.prepare(&generate_select_query::<T>(table_name, None))?;
Ok(serde_rusqlite::from_rows::<T>(query_result.query([])?)
@ -25,15 +25,15 @@ where
/// Generate a SELECT query with fields generated from a struct. Returns a String
/// filter MUST contain "WHERE" else the query will fail
#[inline]
fn generate_select_query<T: more_fields::FieldsAsMap>(
fn generate_select_query<T: more_fields::FieldsAsSlice>(
table_name: &str,
filter: Option<&str>,
) -> String {
format!(
"SELECT {} FROM {}{};",
T::attributes_map()
.into_iter()
.map(|(k, _v)| k)
T::attributes_slice()
.iter()
.map(|(k, _v)| k.to_owned())
.collect::<Vec<_>>()
.join(","),
table_name,
@ -61,11 +61,11 @@ mod test {
use crate::{
interfaces::RecipeDatabase, weaponry_structs::equipement_impl_database::EquipementDatabase,
};
use more_fields::FieldsAsMap;
use more_fields::FieldsAsSlice;
use pretty_assertions::assert_eq;
use serde::Deserialize;
#[derive(FieldsAsMap, Deserialize, Debug, PartialEq)]
#[derive(FieldsAsSlice, Deserialize, Debug, PartialEq)]
struct TestStruct {
id: usize,
name: String,

View File

@ -7,7 +7,7 @@
use std::{path::Path, rc::Rc};
use more_fields::FieldsAsMap;
use more_fields::FieldsAsSlice;
use serde::de::DeserializeOwned;
use crate::error::{EquipementError, FatalEquipementError};
@ -165,7 +165,7 @@ pub trait RecipeDatabase {
Self: std::marker::Sized;
/// Serialize a vector of objects of the given type in the specified table of the underlying database
fn serialize_vec_from_table<T: DeserializeOwned + more_fields::FieldsAsMap>(
fn serialize_vec_from_table<T: DeserializeOwned + more_fields::FieldsAsSlice>(
&self,
table: &str,
) -> std::result::Result<Vec<T>, FatalEquipementError>;
@ -178,7 +178,7 @@ pub trait RecipeDatabase {
) -> std::result::Result<Vec<T>, FatalEquipementError>;
/// Initialize an empty database & table
fn initialize_empty_table<T: FieldsAsMap>(table: &str) -> Result<(), EquipementError>;
fn initialize_empty_table<T: FieldsAsSlice>(table: &str) -> Result<(), EquipementError>;
}
/// Trait implemented by any struct aiming to be a public recipe

View File

@ -19,7 +19,7 @@ pub struct EquipementDatabase {
}
impl RecipeDatabase for EquipementDatabase {
fn serialize_vec_from_table<T: DeserializeOwned + more_fields::FieldsAsMap>(
fn serialize_vec_from_table<T: DeserializeOwned + more_fields::FieldsAsSlice>(
&self,
table: &str,
) -> Result<Vec<T>, crate::error::FatalEquipementError> {
@ -43,11 +43,11 @@ impl RecipeDatabase for EquipementDatabase {
})
}
fn initialize_empty_table<T: more_fields::FieldsAsMap>(
fn initialize_empty_table<T: more_fields::FieldsAsSlice>(
table: &str,
) -> Result<(), crate::error::EquipementError> {
// A vector of <attribute, type>
let _attr_map = T::attributes_map();
let _attr_map = T::attributes_slice();
let _ = table;
todo!()

View File

@ -5,7 +5,7 @@
use std::rc::Rc;
use crate::interfaces::{FilterFunction, FilterFunctionType};
use more_fields::FieldsAsMap;
use more_fields::FieldsAsSlice;
use serde::{Deserialize, Serialize};
use super::{DamageType, SpecialCategory, WeaponCategory};
@ -55,7 +55,7 @@ impl<T> FilterFunction<T> {
/// The inner statistics of the equipement, used across all parts and final weapon
#[allow(clippy::missing_docs_in_private_items, missing_docs)]
#[derive(Clone, Default, FieldsAsMap, Debug, Deserialize, Serialize)]
#[derive(Clone, Default, FieldsAsSlice, Debug, Deserialize, Serialize)]
#[cfg_attr(test, derive(PartialEq))]
pub struct InnerEquipementStats {
#[INTEGER]