Adds a little more serialization and coverage #40

Merged
Dandaedre merged 1 commits from weapons into project_weaponry 2025-02-15 02:27:39 +01:00
10 changed files with 123 additions and 58 deletions

View File

@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="118" height="18" role="img" aria-label="test-coverage: N/A"><title>test-coverage: N/A</title><linearGradient id="bms-b5474c43532a9abd" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-b5474c43532a9abd"><rect width="118" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-b5474c43532a9abd)"><rect width="87" height="18" fill="#555"/><rect x="87" width="31" height="18" fill="#e05d44"/><rect width="118" height="18" fill="url(#bms-b5474c43532a9abd)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1015" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="210">N/A</text><text x="1015" y="130" transform="scale(.1)" fill="#fff" textLength="210">N/A</text></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="122" height="18" role="img" aria-label="test-coverage: 16%"><title>test-coverage: 16%</title><linearGradient id="bms-e68af986cf1a8ea6" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-e68af986cf1a8ea6"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-e68af986cf1a8ea6)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#e05d44"/><rect width="122" height="18" fill="url(#bms-e68af986cf1a8ea6)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1035" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">16%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">16%</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="74" height="18" role="img" aria-label="test: failing"><title>test: failing</title><linearGradient id="bms-a16a196477035f4f" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-a16a196477035f4f"><rect width="74" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-a16a196477035f4f)"><rect width="31" height="18" fill="#555"/><rect x="31" width="43" height="18" fill="#e05d44"/><rect width="74" height="18" fill="url(#bms-a16a196477035f4f)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="165" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="210">test</text><text x="165" y="130" transform="scale(.1)" fill="#fff" textLength="210">test</text><text aria-hidden="true" x="515" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="330">failing</text><text x="515" y="130" transform="scale(.1)" fill="#fff" textLength="330">failing</text></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="82" height="18" role="img" aria-label="test: passing"><title>test: passing</title><linearGradient id="bms-5402c39dce014bd3" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-5402c39dce014bd3"><rect width="82" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-5402c39dce014bd3)"><rect width="31" height="18" fill="#555"/><rect x="31" width="51" height="18" fill="#97ca00"/><rect width="82" height="18" fill="url(#bms-5402c39dce014bd3)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="165" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="210">test</text><text x="165" y="130" transform="scale(.1)" fill="#fff" textLength="210">test</text><text aria-hidden="true" x="555" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="410">passing</text><text x="555" y="130" transform="scale(.1)" fill="#fff" textLength="410">passing</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -5,14 +5,15 @@ edition = "2024"
[dependencies]
comfy-table = "7.1.4"
csv = "1.3.1"
fastrand = "2.3.0"
# iter-enum = "1.2.0"
pretty_assertions = "1.4.1"
probability = "0.20.3"
rayon = "1.10.0"
# rayon = "1.10.0"
rusqlite = { version = "0.33.0", features = ["bundled"] }
serde = { version = "1.0.217", features = ["derive"] }
serde_rusqlite = "0.37.0"
serde_json = { version = "1.0.138", features = ["alloc"] }
struct-field-names-as-array = "0.3.0"
strum = { version = "0.27.0", features = ["derive"] }

View File

@ -9,40 +9,43 @@
use rusqlite::{self, Connection, Result};
use serde::de::DeserializeOwned;
use serde_rusqlite::*;
use struct_field_names_as_array::FieldNamesAsArray;
/// Generate a SELECT query with fields generated from a struct. Returns a String
fn generate_query(fields: &[&str], table_name: &str) -> String {
let mut query = String::new();
query.push_str("SELECT");
for item in fields.iter() {
query.push(' ');
query.push_str(item);
query.push(',');
}
query.pop();
query.push_str(format!(" FROM {};", table_name).as_str());
query
// let mut query = String::new();
// query.push_str("SELECT");
// for item in fields.iter() {
// query.push(' ');
// query.push_str(item);
// query.push(',');
// }
// query.pop();
// query.push_str(format!(" FROM {};", table_name).as_str());
// query
format!("SELECT {} FROM {};", fields.join(", "), table_name)
}
/// Checks if database exists, and returns a rusqlite::Connection. If not, opens database in memory.
// TODO: Remove this cursed function
fn initialize_database_conn(filename: Option<String>) -> Result<Connection> {
if let Some(text) = filename {
let conn = Connection::open(text)?;
Ok(conn)
} else {
let conn = Connection::open_in_memory()?;
Ok(conn)
}
// if let Some(text) = filename {
// let conn = Connection::open(text)?;
// Ok(conn)
// } else {
// let conn = Connection::open_in_memory()?;
// Ok(conn)
// }
filename.map_or_else(Connection::open_in_memory, Connection::open)
}
/// Public function to get data from db
pub fn get_data<T>() -> Result<Vec<T>>
// TODO: Remove this cursed generic manual behaviour
pub fn get_data_from_fields<T>(fields: &[&str]) -> Result<Vec<T>>
where
T: FieldNamesAsArray<2> + DeserializeOwned,
T: DeserializeOwned,
{
let gen_query = generate_query(&(T::FIELD_NAMES_AS_ARRAY), "InnerEquipementStats");
let db_conn = initialize_database_conn(None)?;
let gen_query = generate_query(fields, "InnerEquipementStats");
let db_conn = initialize_database_conn(None)?; // TODO: Add an actual connection
let mut query_result = db_conn.prepare(&gen_query)?;
let res = from_rows::<T>(query_result.query([])?)
.filter_map(|s| s.ok())
@ -93,11 +96,11 @@ mod test {
todo!()
}
//#[ignore]
#[ignore]
#[test]
fn test_get_data() {
let _conn = set_up();
let result = get_data::<TestStruct>();
let result = get_data_from_fields::<TestStruct>(&TestStruct::FIELD_NAMES_AS_ARRAY);
assert!(result.unwrap().is_empty())
}
}

View File

@ -5,7 +5,7 @@
//! handling of the whole crafting process when the times comes
#![allow(dead_code)]
use std::rc::Rc;
use std::{path::Path, rc::Rc};
/// Trait representing a view table
///
@ -140,9 +140,9 @@ pub trait ToTex {
}
/// This element can be converted to a csv for further analysis
pub trait ToAnalysis {
pub trait ToCSV {
/// Convert this object into a csv
fn write_csv(&self) -> String;
fn write_csv(&self, path: &Path) -> csv::Result<()>;
}
/// Garanties that a struct can be generated from a database

View File

@ -15,6 +15,7 @@ use std::fmt::Display;
use crate::interfaces::RefinedList;
use comfy_table::{Table, modifiers::UTF8_ROUND_CORNERS};
use probability::prelude::{Binomial, Discrete};
use serde::Serialize;
use strum::{Display, EnumIter, IntoEnumIterator};
use super::{Equipement, InitialEquipementList, equipement_structs::InnerEquipementStats};
@ -24,12 +25,23 @@ pub struct RefinedEquipement {
/// The original inner stats
///
/// This structs takes ownership of the inner data
// #[serde(skip_deserializing)]
inner: InnerEquipementStats,
/// Advanced stats
// #[serde(flatten)]
advanced: AdvancedStats,
}
impl Serialize for RefinedEquipement {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.advanced.serialize(serializer)
}
}
impl From<Equipement> for RefinedEquipement {
fn from(value: Equipement) -> Self {
Self {
@ -60,8 +72,20 @@ impl From<InitialEquipementList> for RefinedEquipementList {
}
}
#[cfg(test)]
use crate::interfaces::RecipeCollection;
#[cfg(test)]
impl Default for RefinedEquipementList {
fn default() -> Self {
let eq = InitialEquipementList::from_vectored(vec![Equipement::default(); 10]);
RefinedEquipementList::from(eq)
}
}
/// The list of advanced stats infered from an Equipement
#[allow(missing_docs, clippy::missing_docs_in_private_items)]
#[derive(Serialize)]
pub struct AdvancedStats {
damage_per_attack: f64,
damage_per_turn: f64,
@ -110,6 +134,14 @@ impl DamageMatrix {
self.damage_matrix[precision as usize + 3 * dices as usize]
}
}
impl Serialize for DamageMatrix {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&format!("[{:?}]", self.damage_matrix))
}
}
impl Display for DamageMatrix {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {

View File

@ -4,10 +4,10 @@
use std::fmt::Display;
use serde::Deserialize;
use serde::{Deserialize, Serialize};
use strum::Display;
#[derive(Clone, Default, Debug, Deserialize)]
#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[cfg_attr(test, derive(PartialEq))]
/// The special category, a vec of string, for display purposes only
pub struct SpecialCategory(pub(super) Vec<String>);
@ -25,7 +25,7 @@ pub enum NatureTarget {
/// Enum of all different physical weapon damage types
#[allow(clippy::missing_docs_in_private_items)]
#[derive(Clone, Debug, Deserialize)]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(test, derive(PartialEq))]
pub enum PhysicalDamageType {
Blunt,
@ -44,7 +44,7 @@ impl From<&str> for PhysicalDamageType {
///
/// Signifying wether the damage is pure or [secondary] or [[tertiary]]
#[allow(clippy::missing_docs_in_private_items, missing_docs)]
#[derive(Clone, Debug, Display, Deserialize)]
#[derive(Clone, Debug, Display, Deserialize, Serialize)]
#[cfg_attr(test, derive(PartialEq))]
pub enum DamageMod {
Primary(PhysicalDamageType),
@ -63,7 +63,7 @@ impl From<&str> for DamageMod {
/// Combined damage type, as a vector of all damage types
///
/// Meant to be serialised to tex and deserialized directly from the table
#[derive(Clone, Debug, Deserialize)]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(test, derive(PartialEq))]
pub struct DamageType(pub(super) Vec<DamageMod>);
@ -89,7 +89,7 @@ impl Display for DamageType {
/// List all weapon categories
#[allow(clippy::missing_docs_in_private_items, missing_docs)]
#[derive(Clone, Debug, PartialEq, Display, Deserialize)]
#[derive(Clone, Debug, PartialEq, Display, Deserialize, Serialize)]
// #[cfg_attr(test, derive(PartialEq))]
pub enum WeaponCategory {
Exotic,

View File

@ -22,3 +22,15 @@ impl<T> PartialEq for FilterFunction<T> {
true
}
}
#[cfg(test)]
mod test {
use crate::{interfaces::FilterFunction, weaponry_structs::Equipement};
#[test]
fn test_filter_weapons() {
let _ = format!("{:?}", FilterFunction::<Equipement>::default());
let r = FilterFunction::<Equipement>::new(&|_, _| false) == FilterFunction::default();
assert!(r);
}
}

View File

@ -2,26 +2,47 @@
// File: weaponry/src/weaponry_structs/equipement_impl_io.rs
//! All implementation IO specific (mainly export and serde)
// impl ToAnalysis for RefinedEquipementList{
// fn write_csv(&self) -> String {
// let mut wtr = csv::Writer::from_writer();
// }
// }
use std::path::Path;
// impl ToAnalysis for RefinedEquipement {
// fn write_csv(&self) -> String {
use crate::interfaces::ToCSV;
// }
// }
use super::equipement_advanced_repr::RefinedEquipementList;
impl ToCSV for RefinedEquipementList {
fn write_csv(&self, path: &Path) -> csv::Result<()> {
let mut wtr = csv::Writer::from_path(path)?; // wtr.serialize
for record in self.inner.iter() {
wtr.serialize(record)?;
}
Ok(())
}
}
#[cfg(test)]
mod test {
// use super::*;
#[ignore]
use std::path::Path;
use crate::{
interfaces::ToCSV,
weaponry_structs::{
equipement_advanced_repr::{AdvancedStats, RefinedEquipementList},
equipement_structs::InnerEquipementStats,
},
};
#[test]
fn test_structs_serialisation() {
unimplemented!()
let adv = AdvancedStats::from(&InnerEquipementStats::default());
// let mut wtr = csv::Writer::from_path("bob.csv").unwrap(); // wtr.serialize
let mut wtr = csv::Writer::from_writer(Vec::new());
wtr.serialize(adv).unwrap();
wtr.flush().unwrap();
RefinedEquipementList::default()
.write_csv(Path::new("/dev/null"))
.unwrap();
}
#[ignore]

View File

@ -4,7 +4,7 @@
use std::rc::Rc;
use serde::Deserialize;
use serde::{Deserialize, Serialize};
use struct_field_names_as_array::FieldNamesAsArray;
use crate::interfaces::{FilterFunction, FilterFunctionType};
@ -56,7 +56,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, FieldNamesAsArray, Debug, Deserialize)]
#[derive(Clone, Default, FieldNamesAsArray, Debug, Deserialize, Serialize)]
#[cfg_attr(test, derive(PartialEq))]
pub struct InnerEquipementStats {
pub id: Vec<u8>,
@ -143,15 +143,11 @@ pub struct EqFinishing {
#[cfg(test)]
mod test {
// use super::*;
use crate::interfaces::RecipeCollection;
use super::{
EqMaterial, EqNature, EqShape, Equipement, InitialEquipementList, InnerEquipementStats,
EqFinishing, EqMaterial, EqNature, EqShape, Equipement, InitialEquipementList,
InnerEquipementStats,
};
// use pretty_assertions::assert_eq;
use crate::interfaces::RecipeCollection;
fn list_equip() -> Vec<Equipement> {
(0..10)
@ -176,7 +172,7 @@ mod test {
let shape = vec![EqShape::default().into(), EqShape::default().into()];
let nature = vec![EqNature::default().into(), EqNature::default().into()];
let material = vec![EqMaterial::default().into(), EqMaterial::default().into()];
let finishing = vec![EqMaterial::default().into(), EqMaterial::default().into()];
let finishing = vec![EqFinishing::default().into(), EqMaterial::default().into()];
let mut leq = InitialEquipementList::from_vectored(shape);
leq.combine_all(&InitialEquipementList::from_vectored(nature));