364 lines
14 KiB
Rust
364 lines
14 KiB
Rust
// Workspace: weaponry
|
|
// File: weaponry/src/interfaces.rs
|
|
//! Interface module holding all necesary traits
|
|
//! A good amount of effort is made to keep the code polymorphic enough to allow
|
|
//! handling of the whole crafting process when the times comes
|
|
#![allow(dead_code)]
|
|
|
|
use std::{path::Path, rc::Rc};
|
|
|
|
use more_fields::FieldsAsSlice;
|
|
use rusqlite::Connection;
|
|
use serde::{Serialize, de::DeserializeOwned};
|
|
|
|
use crate::error::FatalEquipementError;
|
|
|
|
/// Trait representing a view table
|
|
///
|
|
/// These table exist to allow to link several point of interest to a RecipeCollection
|
|
/// Please note that while FinalRepresentations and ViewTable are two separate traits,
|
|
/// they are always tied together as a view table will alway take specific assumptions
|
|
/// on the data present inside therefore not allowing many variations on the underlying
|
|
/// implementation of the representation
|
|
pub trait ViewTable {
|
|
/// The inner type of element that one would be peeking into
|
|
///
|
|
/// Usually the final representation of an Item
|
|
type InterestElementList: RefinedList;
|
|
|
|
/// Give a list of interesting element indicises to further analyse
|
|
fn index_of_interest_points(&self) -> Vec<usize>;
|
|
|
|
/// Interrogate the FinalRepresentation to find interesting elements
|
|
fn find_points_of_interest(representation: &Self::InterestElementList) -> Self;
|
|
// An alternative, non Self::Typed way of doing since there is only one usage for now
|
|
// fn find_points_of_interest(&self, representation: &impl FinalRepresentation);
|
|
}
|
|
|
|
/// Trait implemented by any struct holding the final representation of a RecipeCollection
|
|
///
|
|
/// This trait is rather placeholder, reminding the user to give only objects that are indeed
|
|
/// final representations and contains all important fields calculated
|
|
///
|
|
/// While it is possible to enforce from_recipe_collection, doing so would require the viewtable
|
|
/// lock itseld to a particular recipe.
|
|
/// While it is the case as of now, matters are not yet set in stone
|
|
pub trait RefinedList: ToTex + ToCSV + ToAnalysis {
|
|
// Must implement From<RecipeCollection>, is it worth adding as a prerequite type ?
|
|
// type OriginCollection: Into<Self>;
|
|
}
|
|
|
|
/// Trait implemented for the final collection of a recipe, allowing it to be combined with parts
|
|
///
|
|
/// A recipe list will be combined with a part list to be updated and generate all combinaisons, so on and so forth
|
|
pub trait RecipeCollection
|
|
where
|
|
for<'a> &'a <<Self as RecipeCollection>::Recipes as Combinable>::Inner: std::ops::Add,
|
|
{
|
|
/// The type of the inner recipes, this type must be combinable
|
|
type Recipes: Combinable;
|
|
|
|
/// A blanket implementation giving all combinaisons of recipes with another RecipeCollection
|
|
///
|
|
/// This method doesn't make use of parallel iterators as the workload is way faster than would be the memory dispatch
|
|
#[coverage(off)] // Tarpaulin cannot deal with iter and long lines
|
|
fn combine_all<G>(&mut self, other: &G)
|
|
where
|
|
G: RecipeCollection<Recipes = Self::Recipes>,
|
|
{
|
|
self.assign_inner(
|
|
self.ref_inner()
|
|
.iter() // Iterate over every recipe
|
|
.flat_map(|inner_recipes| {
|
|
other
|
|
.ref_inner() // Take a reference of <other> recipe
|
|
.iter() // Iterate overe every recipe
|
|
.filter(|&external_recipes| external_recipes.backward_filter(inner_recipes))
|
|
.map(|external_recipes: &Self::Recipes| {
|
|
inner_recipes.add_ref_to_self(external_recipes)
|
|
})
|
|
.collect::<Vec<_>>() // Collect all a vector of recipe
|
|
}) // Flatten all the vector of recipes into a big vector
|
|
.collect::<Vec<Self::Recipes>>(), // Updates the inner collection to the collected recipes
|
|
);
|
|
}
|
|
|
|
/// Assign the inner value from an owned value, used for blanket implementations
|
|
fn assign_inner(&mut self, inner: Vec<Self::Recipes>);
|
|
|
|
/// Gives access to a reference of the inner list
|
|
///
|
|
/// This allows to only clone when needed
|
|
fn ref_inner(&self) -> &Vec<Self::Recipes>;
|
|
|
|
/// Create a collection from a vector
|
|
fn from_vectored(list: Vec<Self::Recipes>) -> Self;
|
|
|
|
/// Create a collection from an iterator of intermediate values T
|
|
#[coverage(off)] // INCORRECT: Error with line report
|
|
fn from_iter_intermediate<T>(
|
|
iter_inter: impl Iterator<Item = Result<T, FatalEquipementError>>,
|
|
) -> Result<Self, FatalEquipementError>
|
|
where
|
|
Self: std::marker::Sized,
|
|
T: Into<Self::Recipes>,
|
|
{
|
|
Ok(Self::from_vectored(
|
|
iter_inter
|
|
.map(|r| r.map(|eq_inter| Into::<Self::Recipes>::into(eq_inter)))
|
|
.collect::<Result<Vec<Self::Recipes>, FatalEquipementError>>()?,
|
|
))
|
|
}
|
|
}
|
|
|
|
/// Trait that ensure that two elements of a recipe are combinable,
|
|
///
|
|
/// Being combinable means it can be coerced into elements that implement add
|
|
pub trait Combinable
|
|
where
|
|
for<'a> &'a <Self as Combinable>::Inner: std::ops::Add,
|
|
{
|
|
/// The inner type of the combined elements, this type must implement Add<&Inner>
|
|
type Inner;
|
|
|
|
/// Give access to a reference of the underlying data to be combined
|
|
///
|
|
/// The designed combinaison method is std::ops::Add
|
|
fn combinable_part(&self) -> &Self::Inner;
|
|
|
|
/// Add an element to self and generate a new Self
|
|
///
|
|
/// As the signature implies, it will not mutate self not rhs and will generate a new value from the operation
|
|
/// This pushes the actual requirement to &Inner : Add<&Inner>
|
|
fn add_ref_to_self<T>(&self, rhs: &T) -> Self
|
|
where
|
|
T: Combinable<Inner = Self::Inner>;
|
|
|
|
/// Filter to decide if the addition should be done
|
|
///
|
|
///
|
|
/// Please note that this comparison is done from the new element perspective,
|
|
/// asking it if it will allow itself to be added as There is as of now no forward filtering
|
|
/// Most filters will defer an internal FilterFunction into the Inner to do all inner working,
|
|
/// but the implementation specifics are left open
|
|
fn backward_filter<T>(&self, lhs: &T) -> bool
|
|
where
|
|
T: Combinable<Inner = Self::Inner>;
|
|
}
|
|
|
|
/// Type alias represinting the inner function parameter
|
|
// #![feature(trait_alias)]
|
|
pub(super) type FilterFunctionType<T> = dyn Fn(&T, &T) -> bool;
|
|
/// Type alias representing a filter
|
|
pub(super) type FilterType<T> = Box<Rc<FilterFunctionType<T>>>;
|
|
|
|
#[derive(Clone)]
|
|
/// A generic Filtering function
|
|
// DONE: Not implementing deref and allowing for a super pub allows
|
|
// implementation to be a little more flexible, however this might
|
|
// also be an oversight
|
|
pub(crate) struct FilterFunction<T>(pub(super) FilterType<T>);
|
|
|
|
/// This element can be converted to tex
|
|
pub trait ToTex {
|
|
/// Export the object to a Tex string
|
|
fn to_tex(&self) -> String;
|
|
}
|
|
|
|
/// This element can be converted to a csv for further analysis
|
|
pub trait ToCSV {
|
|
/// Convert this object into a csv
|
|
fn write_csv(&self, path: &Path) -> csv::Result<()>;
|
|
}
|
|
|
|
/// This element can be converted to an interactive .html
|
|
pub trait ToAnalysis {
|
|
/// The explicit type of the underlying data
|
|
type InnerData;
|
|
|
|
/// Sort the inner data with a given closure
|
|
fn inner_sort<T>(&mut self, closure: T)
|
|
where
|
|
T: FnMut(&Self::InnerData, &Self::InnerData) -> std::cmp::Ordering;
|
|
|
|
/// Apply a filter to the inner data
|
|
///
|
|
/// Careful this filter will consume the original data to avoir reallocating
|
|
fn inner_filter<T>(self, closure: T) -> Self
|
|
where
|
|
T: FnMut(&Self::InnerData) -> bool;
|
|
|
|
/// Write as html
|
|
fn write_html(&self, path: &str) -> Result<(), FatalEquipementError>;
|
|
}
|
|
|
|
/// A generic database+connection, handling all the deserialization of the inner types
|
|
pub trait RecipeDatabase {
|
|
/// The initial Deserialisation struct, SQL will be deserialized into this
|
|
type DeserialisationType: DeserializeOwned;
|
|
/// The used type that Deserialisation type will be converted into
|
|
type InnerType: TryFrom<Self::DeserialisationType>;
|
|
|
|
/// Create the database from a file
|
|
fn new(origin: &str) -> Result<Self, FatalEquipementError>
|
|
where
|
|
Self: std::marker::Sized;
|
|
|
|
/// Serialize a vector of objects of the given type in the specified table with an optional filter of the underlying database
|
|
/// The FROM type is the original data, directly deserialized from the table
|
|
// POI: This element is partly responsible for the difficulty simplifying and generalizing deserialisation
|
|
fn serialize_vec_from_table<FROM: DeserializeOwned + more_fields::FieldsAsSlice>(
|
|
&self,
|
|
table: &str,
|
|
filter: Option<&str>,
|
|
) -> Result<Vec<FROM>, crate::error::FatalEquipementError> {
|
|
crate::database::get_data(self.get_connection(), table, filter)
|
|
}
|
|
|
|
/// Get a reference to the underlying database connection
|
|
fn get_connection(&self) -> &Connection;
|
|
|
|
/// Initialize an empty database & table
|
|
fn initialize_empty_table<T: more_fields::FieldsAsSlice>(
|
|
&self,
|
|
table: &str,
|
|
) -> Result<(), crate::error::FatalEquipementError> {
|
|
// A vector of <attribute, type>
|
|
self.get_connection().execute(
|
|
crate::database::generate_create_table_query(table, T::attributes_slice()).as_str(),
|
|
(),
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Insert a row inside the database, while mostly unused this function is needed to initialize the empty table with an empty row if needed
|
|
#[coverage(off)] // INCORRECT: Error with line report
|
|
fn insert_row<T: FieldsAsSlice + Serialize>(
|
|
&self,
|
|
table_name: &str,
|
|
row: T,
|
|
) -> Result<(), FatalEquipementError> {
|
|
let query = format!(
|
|
"INSERT INTO {} ({}) VALUES ({});",
|
|
table_name,
|
|
T::attributes_slice()
|
|
.iter()
|
|
.map(|(k, _v)| *k)
|
|
.collect::<Vec<_>>()
|
|
.join(","),
|
|
T::attributes_slice()
|
|
.iter()
|
|
.map(|(k, _v)| ":".to_owned() + *k)
|
|
.collect::<Vec<_>>()
|
|
.join(","),
|
|
);
|
|
self.get_connection().execute(
|
|
&query,
|
|
serde_rusqlite::to_params_named(row)?.to_slice().as_slice(),
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Serialize a request into an intermediate T representation,
|
|
/// T having all the implementation specifics of the part in details
|
|
/// eg. EqShape, EqPart etc..
|
|
fn serialize_into_intermediate<T>(
|
|
&self,
|
|
table: &str,
|
|
filter: Option<&str>,
|
|
) -> Result<impl Iterator<Item = Result<T, FatalEquipementError>> + '_, FatalEquipementError>
|
|
where
|
|
T: From<Self::InnerType>;
|
|
}
|
|
|
|
/// Trait implemented by any struct aiming to be a public recipe
|
|
pub trait FixedRecipe {
|
|
// /// Struct representing the database type, most likely a string
|
|
// type Database;
|
|
/// Struct representing the keylist type, most likely a usize
|
|
type KeyList; // TODO: Add the restriction &traits to use the result afterwards
|
|
|
|
/// Get the list of elements corresponding to the recipe
|
|
///
|
|
/// These elements will either be iteratively fetched from the database or scoured through in the data depending on the scenario
|
|
fn get_elements_from_table(
|
|
&self,
|
|
table: &str,
|
|
) -> Result<Vec<Self::KeyList>, FatalEquipementError>;
|
|
}
|
|
|
|
/// Trait ensuring a status report can be inferred from the structure
|
|
pub trait Reportable {
|
|
/// Get a detailled inner status report with as many useful informations as possible
|
|
///
|
|
/// This report should give detailled information about the inner data, without showing the actual inner data
|
|
fn get_report(&self, title: Option<&str>) -> String;
|
|
}
|
|
|
|
/// A recipe full stack scenario, from loading database through view table generation
|
|
///
|
|
/// The inner working while somehow abstracted are very tied together and tied to the impl
|
|
pub trait Scenario where for<'a> &'a <<<Self as Scenario>::InitialEquipementListType as RecipeCollection>::Recipes as Combinable>::Inner: std::ops::Add
|
|
// where
|
|
// for<'a> &'a <<Self as Scenario>::Recipe as Combinable>::Inner: std::ops::Add, for<'a> &'a <<<Self as Scenario>::InitialEquipementListType as RecipeCollection>::Recipes as Combinable>::Inner: std::ops::Add
|
|
{
|
|
/// The inner database type
|
|
type DatabaseType: RecipeDatabase;
|
|
/// The type of the final recipe list
|
|
type FinalListType: RefinedList + ToTex + ToCSV + ToAnalysis;
|
|
/// Inner configuration
|
|
type Config;
|
|
/// The initial equipement type, the database serialisation will be to be converted into this type
|
|
// TODO[!]: Try to remove as it is present in Database
|
|
type InitialEquipementType;
|
|
/// The initial equipement list, about to be converted into a refined list
|
|
type InitialEquipementListType: RecipeCollection; //: Into<impl RecipeCollection<Recipes = Self::Recipe>>;
|
|
|
|
// /// The inner element that all serialised data will be serialized into after the intermediate step
|
|
// type Recipe;
|
|
|
|
// for<'a> &'a <<Self as RecipeCollection>::Recipes as Combinable>::Inner: std::ops::Add,
|
|
|
|
/// Create a Scenario from a given config
|
|
fn new_with_config(config: Self::Config) -> Result<Self, FatalEquipementError>
|
|
where
|
|
Self: Sized;
|
|
|
|
/// Generate the final list type
|
|
fn generate_refined_recipes(&self) -> Result<Self::FinalListType, FatalEquipementError>;
|
|
|
|
/// Retrieve a reference to the inner database
|
|
fn get_database(&self) -> &Self::DatabaseType;
|
|
|
|
/// Retrieve A config
|
|
fn get_tablename(&self) -> &str;
|
|
|
|
|
|
/// Automatically deserialize into an equipement
|
|
fn deserde_into_processed_representation<T>(
|
|
&self,
|
|
filter: Option<&str>,
|
|
) -> Result<Self::InitialEquipementListType, FatalEquipementError>
|
|
where
|
|
T: From<<<Self as Scenario>::DatabaseType as RecipeDatabase>::InnerType>
|
|
+ Into<<<Self as Scenario>::InitialEquipementListType as RecipeCollection>::Recipes>,
|
|
{
|
|
RecipeCollection::from_iter_intermediate::<T>(
|
|
self.get_database()
|
|
.serialize_into_intermediate::<T>(self.get_tablename(), filter)?,
|
|
)
|
|
}
|
|
}
|
|
#[cfg(test)]
|
|
mod test {
|
|
use super::RecipeCollection;
|
|
use crate::weaponry_structs::{InitialEquipementList, equipement_structs::EqShape};
|
|
|
|
#[test]
|
|
fn test_from_iter_intermediate() {
|
|
let _b = <InitialEquipementList as RecipeCollection>::from_iter_intermediate::<EqShape>(
|
|
[Ok(EqShape::default()), Ok(EqShape::default())].into_iter(),
|
|
);
|
|
}
|
|
}
|