More work on the serialisation and the entry datatypes

This commit is contained in:
Dandaedre 2025-02-21 03:48:50 +01:00
parent a2269ccb87
commit 22b46f6c07
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
10 changed files with 309 additions and 251 deletions

Binary file not shown.

View File

@ -1,200 +1,215 @@
// Workspace: weaponry
// File: examples/typical_wl_recipe.rs
//! Example of a typical workload
//!
//! Example of a first initialisation
//! All this work is cursed and rushed
use logos::Logos;
use more_fields::FieldsAsSlice;
use serde::Serialize;
use serde_rusqlite::to_params_named;
// use logos::Logos;
// use more_fields::FieldsAsSlice;
// use serde::Serialize;
// use serde_rusqlite::to_params_named;
use weaponry::interfaces::RecipeDatabase;
use weaponry::weaponry_structs::equipement_impl_database::EquipementDatabase;
// use weaponry::weaponry_structs::{DamageMod, DamageType, WeaponMetaCategory};
// use weaponry::weaponry_structs::PhysicalDamageType;
use weaponry::weaponry_structs::equipement_structs::{DatabaseEquipementStats, InnerEquipementStats};
use weaponry::weaponry_structs::{DamageMod, DamageType, PhysicalDamageType, WeaponMetaCategory};
#[derive(Logos, Debug, PartialEq)]
enum ModeParser {
#[regex(r"\[\[\w+\]\]", |lex| std::convert::TryInto::<PhysicalDamageType>::try_into(&lex.slice()[2..lex.slice().len()-2]).unwrap())]
Tertiary(PhysicalDamageType),
#[regex(r"\[\w+\]", |lex| std::convert::TryInto::<PhysicalDamageType>::try_into(&lex.slice()[1..lex.slice().len()-1]).unwrap())]
Secondary(PhysicalDamageType),
#[regex(r"\w+", |lex| std::convert::TryInto::<PhysicalDamageType>::try_into(lex.slice()).unwrap())]
Primary(PhysicalDamageType),
}
// #[derive(Logos, Debug, PartialEq)]
// enum ModeParser {
// #[regex(r"\[\[\w+\]\]", |lex| std::convert::TryInto::<PhysicalDamageType>::try_into(&lex.slice()[2..lex.slice().len()-2]).unwrap())]
// Tertiary(PhysicalDamageType),
// #[regex(r"\[\w+\]", |lex| std::convert::TryInto::<PhysicalDamageType>::try_into(&lex.slice()[1..lex.slice().len()-1]).unwrap())]
// Secondary(PhysicalDamageType),
// #[regex(r"\w+", |lex| std::convert::TryInto::<PhysicalDamageType>::try_into(lex.slice()).unwrap())]
// Primary(PhysicalDamageType),
// }
// let b = DamageMod::Primary()
const BASE_FORME: &[&str] = &[
// "% Nom & Type & Dé & + & RM & AB & Pr & In & T2 & T1 & Md & Esq. & Par. & Vit. & Disc. & Spc. & Diff ",
// "Name & Type & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & mode & 9 & 10 & 11 & 12 & 3reload, & ddlvl{13} ",
"Griffes & Tranchantes & 2 & 1 & 4 & 1 & 1 & 2 & 3 & 6 & slash & 2 & 0 & 3 & 1 & - & ddlvl{1} ",
"Hast & Hast & 4 & 1 & 2 & 1 & 4 & 3 & 10 & 18 & pierce, [slash] & -1 & -3 & 1 & 0 & - & ddlvl{1} ",
"Épée & Tranchantes & 3 & 1 & 3 & 1 & 3 & 4 & 12 & 15 & slash, [pierce] & 0 & 1 & 0 & 0 & - & ddlvl{1} ",
"Marteau & Contondantes & 5 & 1 & 1 & 1 & 4 & 3 & 11 & 18 & blunt & -1 & -1 & 0 & -2 & - & ddlvl{1} ",
"Hache & Tranchantes & 4 & 2 & 1 & 3 & 4 & 3 & 9 & 14 & slash & 0 & -1 & 1 & 0 & - & ddlvl{1} ",
"Arbalète & Distance & 4 & 1 & 3 & 0 & 3 & 1 & 8 & 16 & pierce & -1 & -1 & 0 & -1 & 2reload, Gls{parmure} 2, 80m & ddlvl{1} ",
"Arc & Distance & 3 & 1 & 4 & 0 & 2 & 1 & - & 7 & pierce & 0 & 0 & 0 & 0 & 1reload, Gls{parmure} 2, 120m & ddlvl{1} ",
"Boucliers & Boucliers & 1 & 1 & 2 & 0 & 3 & 2 & 6 & 8 & blunt & -2 & 0 & -1 & -2 & - & ddlvl{1} ",
"Armures & Armures & & & & & 3 & 2 & 10 & - & blunt & -1 & 0 & 0 & -1 & - & ddlvl{1} ",
// "% Explosive & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{5} ",
// "% Flexible & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{2} ",
// "% Exotique & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{3} ",
];
fn main() {
let mut global_index = 0;
let b = load_base(&mut global_index);
// println!("{b:?}"); // Equipements
let db = EquipementDatabase::new("./databases/weapons.db").unwrap();
db.initialize_empty_table::<DatabaseEquipementStats>("Equipements").unwrap();
db.conn.execute("DELETE FROM Equipements", []).unwrap();
println!("Added {global_index} ids to the new database");
b.iter().for_each(|v| database_shnn(&db, v));
let v = db.serialize_vec_from_table::<DatabaseEquipementStats>("Equipements", None);
// println!("Initial deserialisation in DatabaseEquipementStats: {:?}", v);
println!("First entry: {:?}", v.as_ref().unwrap()[0]);
// Final deserialisation
let final_s = v.unwrap().into_iter().map(InnerEquipementStats::try_from).collect::<Vec<_>>();
let v = final_s
.iter()
.scan(0, |status, eq| {
if eq.is_ok() {
*status = 1;
} else {
*status = 0;
}
Some(*status)
})
.sum::<i32>();
println!("Final data {:#?}", final_s);
println!("Succeded in parsing {:#?} over {}", v, global_index);
// init_db(&db);
let initial_deserialisation = db.serialize_vec_from_table::<DatabaseEquipementStats>("Equipements", None);
// println!("Initial deserialisation in DatabaseEquipementStats: {:?}", initial_deserialisation);
// println!("First entry: {:?}", initial_deserialisation.as_ref().unwrap()[0]);
let intermediate_deserialisation = initial_deserialisation.unwrap().into_iter().map(InnerEquipementStats::try_from).collect::<Vec<_>>();
// let v = intermediate_deserialisation
// .iter()
// .scan(0, |status, eq| {
// if eq.is_ok() {
// *status = 1;
// } else {
// *status = 0;
// }
// Some(*status)
// })
// .sum::<i32>();
let f = intermediate_deserialisation.iter().fold((0, 0), |val, res| (val.0 + res.is_ok() as usize, val.1 + 1_usize));
println!("Final data {:#?}", intermediate_deserialisation);
println!("Succeded in parsing {}/{}", f.0, f.1);
}
#[allow(dead_code)]
#[derive(Default)]
struct FoundFields {
reload: Option<u8>,
range: Option<u8>,
parmor: Option<u8>,
}
fn parse_special_field(fields: &str) -> FoundFields {
// "Arbalète & Distance & 4 & 1 & 3 0 & 3 & 1 & 8 & 16 & pierce & -1 & -1 & 0 & -1 & 2reload, Gls{parmure} 2, 80m & ddlvl{1} ",
let re = regex::Regex::new(r"((?<reload>\d)reload)?(, )?(Gls\{parmure\} (?<parmure>\d))?(, )?((?<range>\d+)m)?").unwrap();
re.captures(fields).map_or(FoundFields::default(), |f| FoundFields {
reload: f.name("reload").map(|n| n.as_str().parse().unwrap()),
range: f.name("range").map(|v| v.as_str().parse().unwrap()),
parmor: f.name("parmor").map(|v| v.as_str().parse().unwrap()),
})
}
// #[derive(Default)]
// struct FoundFields {
// reload: Option<u8>,
// range: Option<u8>,
// parmor: Option<u8>,
// }
// fn init_db(db: &EquipementDatabase) {
// let mut global_index = 0;
// let b = load_base(&mut global_index);
// db.initialize_empty_table::<DatabaseEquipementStats>("Equipements").unwrap();
#[allow(dead_code)]
fn database_shnn<T: Serialize>(db: &EquipementDatabase, row: T) {
// let mut row = DatabaseEquipementStats::random_new();
// db.conn.execute("DELETE FROM Equipements", []).unwrap();
// println!("Added {global_index} ids to the new database");
let sql = &format!(
"INSERT INTO Equipements ({}) VALUES ({})",
DatabaseEquipementStats::attributes_slice()
.iter()
// .filter_map(|(k, _v)| (*k != "id").then_some(*k))
.map(|(k, _v)| *k)
.collect::<Vec<_>>()
.join(", "),
DatabaseEquipementStats::attributes_slice()
.iter()
// .filter_map(|(k, _v)| (*k != "id").then_some(":".to_string() + *k))
.map(|(k, _v)| ":".to_string() + *k)
.collect::<Vec<_>>()
.join(", ")
);
// println!("Database Request {}", sql);
let r = db.conn.execute(sql, to_params_named(&row).unwrap().to_slice().as_slice());
match r {
Ok(_r) => {
// println!("Loaded {:?} entries into the database", _r);
}
Err(e) => println!("Error: {} while processing entry", e),
};
}
// b.iter().for_each(|v| insert_into_db(db, v));
// }
// fn parse_special_field(fields: &str) -> FoundFields {
// // "Arbalète & Distance & 4 & 1 & 3 0 & 3 & 1 & 8 & 16 & pierce & -1 & -1 & 0 & -1 & 2reload, Gls{parmure} 2, 80m & ddlvl{1} ",
// let re = regex::Regex::new(r"((?<reload>\d)reload)?(, )?(Gls\{parmure\} (?<parmure>\d))?(, )?((?<range>\d+)m)?").unwrap();
// re.captures(fields).map_or(FoundFields::default(), |f| FoundFields {
// reload: f.name("reload").map(|n| n.as_str().parse().unwrap()),
// range: f.name("range").map(|v| v.as_str().parse().unwrap()),
// parmor: f.name("parmor").map(|v| v.as_str().parse().unwrap()),
// })
// }
fn load_base(index: &mut u8) -> Vec<DatabaseEquipementStats> {
// data_eg.id = fastrand::u8(1..u8::MAX);
// data_eg.damage_type = serde_json::to_string(&Some(DamageType(vec![DamageMod::Primary(
// PhysicalDamageType::Blunt,
// )])))
// .unwrap();
// data_eg.category = serde_json::to_string(&Some(WeaponCategory::Dagger)).unwrap();
// data_eg.target = serde_json::to_string(&Some(WeaponCategory::Dagger)).unwrap();
// data_eg.special =
// serde_json::to_string(&SpecialCategory(vec!["noo".to_string(), "boo".to_string()]))
// .unwrap();
// data_eg.reload_cost = serde_json::to_string(&Some(12)).unwrap();
BASE_FORME
.iter()
.map(|row| {
let fields = row.split("&").map(|field| field.trim()).collect::<Vec<_>>();
let FoundFields { reload, range, parmor } = parse_special_field(fields[15]);
*index += 1;
// "% Nom & Type & Dé & + & RM & AB & Pr & In & T2 & T1 & Md & Esq. & Par. & Vit. & Disc. & Spc. & Diff ",
// 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15
DatabaseEquipementStats {
id: *index,
meta_category: "Forme".into(),
name: fields[0].to_string(),
category: serde_json::to_string(&parse_to_type(fields[1]).unwrap()).unwrap(),
rarity: 0,
cost: 0,
precision: 0,
difficulty: fields[16].parse().unwrap_or_default(), // NOT PARSED YET
// tier: ,
damage: fields[2].parse().unwrap_or_default(),
p_damage: fields[3].parse().unwrap_or_default(),
rmax: fields[4].parse().unwrap_or_default(),
armor_break: fields[5].parse().unwrap_or_default(),
protection: fields[6].parse().unwrap_or_default(),
integrity: fields[7].parse().unwrap_or_default(),
// #[allow(dead_code)]
// fn insert_into_db<T: Serialize>(db: &EquipementDatabase, row: T) {
// let sql = &format!(
// "INSERT INTO Equipements ({}) VALUES ({})",
// DatabaseEquipementStats::attributes_slice()
// .iter()
// // .filter_map(|(k, _v)| (*k != "id").then_some(*k))
// .map(|(k, _v)| *k)
// .collect::<Vec<_>>()
// .join(", "),
// DatabaseEquipementStats::attributes_slice()
// .iter()
// // .filter_map(|(k, _v)| (*k != "id").then_some(":".to_string() + *k))
// .map(|(k, _v)| ":".to_string() + *k)
// .collect::<Vec<_>>()
// .join(", ")
// );
// // println!("Database Request {}", sql);
// let r = db.conn.execute(sql, to_params_named(&row).unwrap().to_slice().as_slice());
// match r {
// Ok(_r) => {
// // println!("Loaded {:?} entries into the database", _r);
// }
// Err(e) => println!("Error: {} while processing entry", e),
// };
// }
torque_two_handed: fields[8].parse().unwrap_or_default(),
torque_one_handed: fields[9].parse().unwrap_or_default(), // The or default is a problem
damage_type: serde_json::to_string(&parse_to_damagetype(fields[10])).unwrap(),
// // fn load_base(index: &mut u8) -> Vec<DatabaseEquipementStats> {
// // BASE_FORME
// // .iter()
// // .map(|row| {
// // let fields = row.split("&").map(|field| field.trim()).collect::<Vec<_>>();
// // let FoundFields { reload, range, parmor } = parse_special_field(fields[15]);
// // *index += 1;
// // // "% Nom & Type & Dé & + & RM & AB & Pr & In & T2 & T1 & Md & Esq. & Par. & Vit. & Disc. & Spc. & Diff ",
// // // 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15
// // DatabaseEquipementStats {
// // id: *index,
// // meta_category: "Forme".into(),
// // name: fields[0].to_string(),
// // category: serde_json::to_string(&parse_to_type(fields[1]).unwrap()).unwrap(),
// // rarity: 0,
// // cost: 0,
// // precision: 0,
// // difficulty: fields[16].parse().unwrap_or_default(), // NOT PARSED YET
// // // tier: ,
// // damage: fields[2].parse().unwrap_or_default(),
// // p_damage: fields[3].parse().unwrap_or_default(),
// // rmax: fields[4].parse().unwrap_or_default(),
// // armor_break: fields[5].parse().unwrap_or_default(),
// // protection: fields[6].parse().unwrap_or_default(),
// // integrity: fields[7].parse().unwrap_or_default(),
dodge: fields[11].parse().unwrap_or_default(),
parry: fields[12].parse().unwrap_or_default(),
speed: fields[13].parse().unwrap_or_default(),
stealth: fields[14].parse().unwrap_or_default(),
reload_cost: serde_json::to_string(&reload).unwrap(),
range: range.unwrap_or_default(),
armor_pierce: parmor.unwrap_or_default(),
// meta_category: parse_to_type(fields[1]),
// // torque_two_handed: serde_json::to_string(&match fields[8] {
// // "-" => None,
// // v => Some(v.parse::<u8>().unwrap()),
// // })
// // .unwrap(),
// // torque_one_handed: serde_json::to_string(&match fields[9] {
// // "-" => None,
// // v => Some(v.parse::<u8>().unwrap()),
// // })
// // .unwrap(), // The or default is a problem
// // damage_type: serde_json::to_string(&parse_to_damagetype(fields[10])).unwrap(),
// target: fields[5].parse().unwrap(), // Armors ?
..Default::default()
}
})
.collect::<Vec<_>>()
}
// // dodge: fields[11].parse().unwrap_or_default(),
// // parry: fields[12].parse().unwrap_or_default(),
// // speed: fields[13].parse().unwrap_or_default(),
// // stealth: fields[14].parse().unwrap_or_default(),
// // reload_cost: serde_json::to_string(&reload).unwrap(),
// // range: range.unwrap_or_default(),
// // armor_pierce: parmor.unwrap_or_default(),
// // // meta_category: parse_to_type(fields[1]),
fn parse_to_damagetype(fields: &str) -> DamageType {
DamageType(fields.split(",").map(|v| ModeParser::lexer(v.trim()).next().unwrap().unwrap().into()).collect::<Vec<_>>())
}
// // // target: fields[5].parse().unwrap(), // Armors ?
// // ..Default::default()
// // }
// // })
// // .collect::<Vec<_>>()
// // }
impl From<ModeParser> for DamageMod {
fn from(value: ModeParser) -> Self {
match value {
ModeParser::Primary(v) => DamageMod::Primary(v),
ModeParser::Secondary(v) => DamageMod::Secondary(v),
ModeParser::Tertiary(v) => DamageMod::Tertiary(v),
}
}
}
// fn parse_to_damagetype(fields: &str) -> DamageType {
// DamageType(fields.split(",").map(|v| ModeParser::lexer(v.trim()).next().unwrap().unwrap().into()).collect::<Vec<_>>())
// }
fn parse_to_type(text: &str) -> Option<WeaponMetaCategory> {
match text {
"Hast" => Some(WeaponMetaCategory::Staves),
"Tranchantes" => Some(WeaponMetaCategory::Slash),
"Contondantes" => Some(WeaponMetaCategory::Blunt),
"Distance" => Some(WeaponMetaCategory::Ranged),
"Boucliers" => Some(WeaponMetaCategory::Shields),
"Armures" => Some(WeaponMetaCategory::Armor),
"Exotiques" => Some(WeaponMetaCategory::Exotic),
_ => None,
}
}
// impl From<ModeParser> for DamageMod {
// fn from(value: ModeParser) -> Self {
// match value {
// ModeParser::Primary(v) => DamageMod::Primary(v),
// ModeParser::Secondary(v) => DamageMod::Secondary(v),
// ModeParser::Tertiary(v) => DamageMod::Tertiary(v),
// }
// }
// }
// fn parse_to_type(text: &str) -> Option<WeaponMetaCategory> {
// match text {
// "Hast" => Some(WeaponMetaCategory::Staves),
// "Tranchantes" => Some(WeaponMetaCategory::Slash),
// "Contondantes" => Some(WeaponMetaCategory::Blunt),
// "Distance" => Some(WeaponMetaCategory::Ranged),
// "Boucliers" => Some(WeaponMetaCategory::Shields),
// "Armures" => Some(WeaponMetaCategory::Armor),
// "Exotiques" => Some(WeaponMetaCategory::Exotic),
// _ => None,
// }
// }
// const BASE_FORME: &[&str] = &[
// // "% Nom & Type & Dé & + & RM & AB & Pr & In & T2 & T1 & Md & Esq. & Par. & Vit. & Disc. & Spc. & Diff ",
// // "Name & Type & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & mode & 9 & 10 & 11 & 12 & 3reload, & ddlvl{13} ",
// "Griffes & Tranchantes & 2 & 1 & 4 & 1 & 1 & 2 & 3 & 6 & slash & 2 & 0 & 3 & 1 & - & ddlvl{1} ",
// "Hast & Hast & 4 & 1 & 2 & 1 & 4 & 3 & 10 & 18 & pierce, [slash] & -1 & -3 & 1 & 0 & - & ddlvl{1} ",
// "Épée & Tranchantes & 3 & 1 & 3 & 1 & 3 & 4 & 12 & 15 & slash, [pierce] & 0 & 1 & 0 & 0 & - & ddlvl{1} ",
// "Marteau & Contondantes & 5 & 1 & 1 & 1 & 4 & 3 & 11 & 18 & blunt & -1 & -1 & 0 & -2 & - & ddlvl{1} ",
// "Hache & Tranchantes & 4 & 2 & 1 & 3 & 4 & 3 & 9 & 14 & slash & 0 & -1 & 1 & 0 & - & ddlvl{1} ",
// "Arbalète & Distance & 4 & 1 & 3 & 0 & 3 & 1 & 8 & 16 & pierce & -1 & -1 & 0 & -1 & 2reload, Gls{parmure} 2, 80m & ddlvl{1} ",
// "Arc & Distance & 3 & 1 & 4 & 0 & 2 & 1 & - & 7 & pierce & 0 & 0 & 0 & 0 & 1reload, Gls{parmure} 2, 120m & ddlvl{1} ",
// "Boucliers & Boucliers & 1 & 1 & 2 & 0 & 3 & 2 & 6 & 8 & blunt & -2 & 0 & -1 & -2 & - & ddlvl{1} ",
// "Armures & Armures & & & & & 3 & 2 & 10 & - & blunt & -1 & 0 & 0 & -1 & - & ddlvl{1} ",
// // "% Explosive & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{5} ",
// // "% Flexible & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{2} ",
// // "% Exotique & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{3} ",
// ];
// #[allow(dead_code)]
// const BASE_SHAPE: &[&str] = &[
// // " Maniement & damagew & + & rmax & arbreakw & faShield* & faShieldVirus & $mathbb{T}2$ & $mathbb{T}$1 & Esq. & Par. & Vit. & Disc. & Spécial & Diff. "
// // " % Nom & Dg & + & RM & AB & Pr & In & T2 & T1 & Esq. & Par. & Vit. & Disc. & Sp & Diff",
// " Arme Légère & -1 & 0 & 2 & -1 & -1 & -1 & -5 & -6 & 2 & 2 & 0 & 0 & Ag+half, Esq.+half & ddlvl{1}",
// " Arme Moyenne & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & - & ddzero",
// " Arme Lourde & 2 & 1 & 1 & 0 & 1 & 0 & 8 & 11 & -2 & -2 & -1 & -1 & - & ddlvl{1}",
// " Arme Super-lourde & 3 & 2 & 1 & 1 & 2 & 1 & 23 & 23 & -3 & -3 & -3 & -3 & 2A, Ag-1, [[blunt]], Précision-1 & ddlvl{2}",
// // " Arme Combinée & - & - & - & - & - & -2 & - & - & - & - & - & - & - & ddlvl{3}", // We'll have to think about this one
// // " Arme Escamotable & - & - & - & - & - & - & - & - & - & - & - & - & - & ddlvl{3}", // We'll have to think about this one
// " Armure Légère & - & - & - & - & -1 & -1 & -1 & - & 1 & 0 & 0 & 1 & Ag+1 & ddlvl{1}",
// " Armure Moyenne & - & - & - & - & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & - & ddzero",
// " Armure Lourde & - & - & - & - & 1 & 1 & 13 & - & -3 & -3 & -2 & -3 & Ag-1, Précision -1 & ddlvl{1}",
// " Armure Super-lourde & - & - & - & - & 3 & 3 & 25 & - & -5 & -4 & -4 & -6 & Ag-1, Précision -1 & ddlvl{2}",
// ];

View File

@ -0,0 +1,31 @@
// Workspace: weaponry
// File: examples/test_serialisation_wl.rs
//! Test of an initial serialisation and scenario wl
//! Doing this work on an example will help writing it as an integration test afterwards
use weaponry::interfaces::RecipeDatabase;
use weaponry::weaponry_structs::equipement_impl_database::EquipementDatabase;
use weaponry::weaponry_structs::equipement_structs::{DatabaseEquipementStats, InnerEquipementStats};
fn main() {
let db = EquipementDatabase::new("./databases/weapons.db").unwrap();
let initial_deserialisation = db.serialize_vec_from_table::<DatabaseEquipementStats>("Equipements", None);
// println!("Initial deserialisation in DatabaseEquipementStats: {:?}", initial_deserialisation);
// println!("First entry: {:?}", initial_deserialisation.as_ref().unwrap()[0]);
let intermediate_deserialisation = initial_deserialisation.unwrap().into_iter().map(InnerEquipementStats::try_from).collect::<Vec<_>>();
// let v = intermediate_deserialisation
// .iter()
// .scan(0, |status, eq| {
// if eq.is_ok() {
// *status = 1;
// } else {
// *status = 0;
// }
// Some(*status)
// })
// .sum::<i32>();
let f = intermediate_deserialisation.iter().fold((0, 0), |val, res| (val.0 + res.is_ok() as usize, val.1 + 1_usize));
println!("Final data {:#?}", intermediate_deserialisation);
println!("Succeded in parsing {}/{}", f.0, f.1);
}

View File

@ -7,20 +7,25 @@
use rusqlite::{self};
use serde::de::DeserializeOwned;
use crate::error::FatalEquipementError;
/// Public function to get data from db. Returns the result as a vec with structs
pub fn get_data<T>(
conn: &rusqlite::Connection,
table_name: &str,
filter: Option<&str>,
) -> Result<Vec<T>, serde_rusqlite::Error>
) -> Result<Vec<T>, FatalEquipementError>
where
T: DeserializeOwned + more_fields::FieldsAsSlice,
{
serde_rusqlite::from_rows::<T>(
conn.prepare(&generate_select_query::<T>(table_name, filter))?
.query([])?,
)
.collect()
let mut binding = conn.prepare(&generate_select_query::<T>(table_name, filter))?;
let rows = binding.query([])?;
serde_rusqlite::from_rows::<T>(rows)
.enumerate()
.map(|(row_id, result)| {
result.map_err(|error| FatalEquipementError::SerdeRusqlite { error, row_id })
})
.collect()
}
/// Generate a SELECT query with fields generated from a struct. Returns a SQL request as a String

View File

@ -11,17 +11,23 @@ pub enum FatalEquipementError {
#[error("Rusqlite failed to connect to the given path {0}")]
RusqliteConnection(#[from] rusqlite::Error),
#[error("Deserialization from object failed : {0}")]
SerdeRusqlite(#[from] serde_rusqlite::Error),
#[error("Deserialization from object failed : rowid {row_id} \n{error}")]
SerdeRusqlite {
error: serde_rusqlite::Error,
row_id: usize,
},
#[error("Deserialisation from json failed : {0}")]
SerdeJSON(#[from] serde_json::Error),
#[error("Deserialisation from json failed at line {0} : {1}]")]
SerdeJSONAt(String, serde_json::Error),
#[error("Deserialisation from json failed at line {line} : {error}]")]
SerdeJSONAt {
line: String,
error: serde_json::Error,
},
#[error("Couldn't convert into type {0} with data {1}")]
Conversion(String, String),
#[error("Couldn't convert into type {origin_type} with data {data}")]
Conversion { origin_type: String, data: String },
}
#[derive(Error, Debug)]

View File

@ -44,10 +44,10 @@ impl TryFrom<&str> for PhysicalDamageType {
"blunt" => Ok(Self::Blunt),
"slash" => Ok(Self::Slash),
"pierce" => Ok(Self::Pierce),
_ => Err(FatalEquipementError::Conversion(
std::any::type_name::<Self>().to_owned(),
value.to_string(),
)),
_ => Err(FatalEquipementError::Conversion {
origin_type: std::any::type_name::<Self>().to_owned(),
data: value.to_string(),
}),
}
}
}

View File

@ -27,7 +27,7 @@ impl RecipeDatabase for EquipementDatabase {
table: &str,
filter: Option<&str>,
) -> Result<Vec<T>, crate::error::FatalEquipementError> {
Ok(get_data(&self.conn, table, filter)?)
get_data(&self.conn, table, filter)
}
/// Checks if database exists, and returns a rusqlite::Connection. If not, opens database in memory.
@ -76,8 +76,9 @@ impl FixedRecipe for EquipementFixedRecipe {
/// Macro converting a value using serde and mapping an in house error
macro_rules! from_serde {
($value: expr) => {
serde_json::from_str(&$value).map_err(|e| {
FatalEquipementError::SerdeJSONAt(format!("{} line {}", file!(), line!()), e)
serde_json::from_str(&$value).map_err(|error| FatalEquipementError::SerdeJSONAt {
line: format!("{} line {}", file!(), line!()),
error,
})
};
}

View File

@ -172,7 +172,7 @@ mod test {
fn test_basic_logic() {}
impl Equipement {
fn newish(name: &[&str], i: u8) -> Self {
fn newish(name: &[&str], i: i8) -> Self {
Equipement {
stats: InnerEquipementStats {
name: name.iter().map(|s| s.to_string()).collect(),

View File

@ -49,7 +49,7 @@ impl std::ops::Add for &InnerEquipementStats {
damage_type: add_two_options!(self.damage_type, rhs.damage_type),
protection: self.protection + rhs.protection,
integrity: self.integrity + rhs.integrity,
torque_two_handed: self.torque_two_handed + rhs.torque_two_handed,
torque_two_handed: add_two_options!(self.torque_two_handed, rhs.torque_two_handed),
torque_one_handed: add_two_options!(self.torque_one_handed, rhs.torque_one_handed),
dodge: self.dodge + rhs.dodge,
parry: self.parry + rhs.parry,

View File

@ -59,33 +59,33 @@ impl<T> FilterFunction<T> {
pub struct InnerEquipementStats {
pub id: Vec<u8>,
pub name: Vec<String>,
pub(super) rarity: u8,
pub(super) cost: u8,
pub(super) difficulty: u8,
pub(super) tier: u8,
pub(super) damage: u8,
pub(super) p_damage: u8,
pub(super) rarity: i8,
pub(super) cost: i8,
pub(super) difficulty: i8,
pub(super) tier: i8,
pub(super) damage: i8,
pub(super) p_damage: i8,
pub(super) precision: i8,
pub(super) rmax: u8,
pub(super) armor_break: u8,
pub(super) armor_pierce: u8,
pub(super) antimaterial: u8,
pub(super) rmax: i8,
pub(super) armor_break: i8,
pub(super) armor_pierce: i8,
pub(super) antimaterial: i8,
pub(super) damage_type: Option<DamageType>,
pub(super) protection: u8,
pub(super) integrity: u8,
pub(super) torque_two_handed: u8, // Might be option (single claw)
pub(super) torque_one_handed: Option<u8>, // Should be option (bows)
pub(super) dodge: u8,
pub(super) parry: u8,
pub(super) speed: u8,
pub(super) stealth: u8,
pub(super) protection: i8,
pub(super) integrity: i8,
pub(super) torque_two_handed: Option<i8>, // Might be option (single claw)
pub(super) torque_one_handed: Option<i8>, // Should be option (bows)
pub(super) dodge: i8,
pub(super) parry: i8,
pub(super) speed: i8,
pub(super) stealth: i8,
pub(super) category: Option<WeaponMetaCategory>,
pub(super) target: Option<WeaponMetaCategory>, // TODO: This might be incorrect, to check
pub(super) special: SpecialCategory,
pub(super) action_cost: u8,
pub(super) reload_cost: Option<u8>, // Shouldn't it be Option ?
pub(super) range: u8, // Shoudln't it be Option ?
pub(super) agility_bonus: u8,
pub(super) action_cost: i8,
pub(super) reload_cost: Option<i8>, // Shouldn't it be Option ?
pub(super) range: i8, // Shoudln't it be Option ?
pub(super) agility_bonus: i8,
}
// TODO: This implementation of default is painfull
@ -101,52 +101,52 @@ pub struct DatabaseEquipementStats {
pub meta_category: String,
pub name: String,
#[INTEGER]
pub rarity: u8,
pub rarity: i8,
#[INTEGER]
pub cost: u8,
pub cost: i8,
#[INTEGER]
pub difficulty: u8,
pub difficulty: i8,
#[INTEGER]
pub tier: u8,
pub tier: i8,
#[INTEGER]
pub damage: u8,
pub damage: i8,
#[INTEGER]
pub p_damage: u8,
pub p_damage: i8,
#[INTEGER]
pub precision: i8,
#[INTEGER]
pub rmax: u8,
pub rmax: i8,
#[INTEGER]
pub armor_break: u8,
pub armor_break: i8,
#[INTEGER]
pub armor_pierce: u8,
pub armor_pierce: i8,
#[INTEGER]
pub antimaterial: u8,
pub antimaterial: i8,
pub damage_type: String,
#[INTEGER]
pub protection: u8,
pub protection: i8,
#[INTEGER]
pub integrity: u8,
pub integrity: i8,
pub torque_two_handed: String,
pub torque_one_handed: String,
#[INTEGER]
pub dodge: u8,
pub dodge: i8,
#[INTEGER]
pub parry: u8,
pub parry: i8,
#[INTEGER]
pub speed: u8,
pub speed: i8,
#[INTEGER]
pub stealth: u8,
pub stealth: i8,
pub category: String,
pub target: String,
pub special: String,
#[INTEGER]
pub action_cost: u8,
pub action_cost: i8,
pub reload_cost: String,
#[INTEGER]
pub range: u8,
pub range: i8,
#[INTEGER]
pub agility_bonus: u8,
pub agility_bonus: i8,
}
impl Default for DatabaseEquipementStats {
@ -191,7 +191,7 @@ impl Default for DatabaseEquipementStats {
#[doc(hidden)]
macro_rules! r {
() => {
fastrand::u8(1..u8::MAX)
fastrand::i8(1..i8::MAX)
};
}
// TODO: Make this a test requirement or hide it behind a profile
@ -199,11 +199,11 @@ impl InnerEquipementStats {
/// Testing function to fuzz data
pub fn random_new() -> Self {
Self {
id: vec![r!()],
range: r!(),
damage: r!(),
p_damage: r!(),
protection: r!(),
id: vec![r!() as u8],
range: r!() - 10,
damage: r!() - 10,
p_damage: r!() - 10,
protection: r!() - 10,
..Default::default()
}
}
@ -213,11 +213,11 @@ impl DatabaseEquipementStats {
/// Testing function to fuzz data
pub fn random_new() -> Self {
Self {
id: r!(),
range: r!(),
damage: r!(),
p_damage: r!(),
protection: r!(),
id: r!() as u8,
range: r!() - 19,
damage: r!() - 10,
p_damage: r!() - 10,
protection: r!() - 10,
..Default::default()
}
}