use std::{cmp::Ordering, fmt};
use crate::detection::{
license::LicenseType,
license::TextData,
{LicenseEntry, Store},
};
#[derive(Clone)]
pub struct Match<'a> {
pub score: f32,
pub name: &'a str,
pub license_type: LicenseType,
pub data: &'a TextData,
}
struct PartialMatch<'a> {
pub name: &'a str,
pub score: f32,
pub license_type: LicenseType,
pub data: &'a TextData,
}
impl<'a> PartialOrd for PartialMatch<'a> {
fn partial_cmp(&self, other: &PartialMatch<'_>) -> Option<Ordering> {
self.score.partial_cmp(&other.score)
}
}
impl<'a> PartialEq for PartialMatch<'a> {
fn eq(&self, other: &PartialMatch<'_>) -> bool {
self.score.eq(&other.score)
&& self.name == other.name
&& self.license_type == other.license_type
}
}
impl<'a> fmt::Debug for Match<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"Match {{ score: {}, name: {}, license_type: {:?} }}",
self.score, self.name, self.license_type
)
}
}
impl Store {
pub fn analyze<'a>(&'a self, text: &TextData) -> Match<'a> {
let mut res: Vec<PartialMatch<'a>>;
let analyze_fold =
|mut acc: Vec<PartialMatch<'a>>, (name, data): (&'a String, &'a LicenseEntry)| {
acc.push(PartialMatch {
score: data.original.match_score(text),
name,
license_type: LicenseType::Original,
data: &data.original,
});
data.alternates.iter().for_each(|alt| {
acc.push(PartialMatch {
score: alt.match_score(text),
name,
license_type: LicenseType::Alternate,
data: alt,
});
});
data.headers.iter().for_each(|head| {
acc.push(PartialMatch {
score: head.match_score(text),
name,
license_type: LicenseType::Header,
data: head,
});
});
acc
};
#[cfg(feature = "detection-parallel")]
{
use rayon::prelude::*;
res = self
.licenses
.par_iter()
.fold(Vec::new, analyze_fold)
.reduce(
Vec::new,
|mut a: Vec<PartialMatch<'a>>, b: Vec<PartialMatch<'a>>| {
a.extend(b);
a
},
);
res.par_sort_unstable_by(|a, b| b.partial_cmp(a).unwrap());
}
#[cfg(not(feature = "detection-parallel"))]
{
res = self
.licenses
.iter()
.fold(Vec::with_capacity(self.licenses.len()), analyze_fold);
res.sort_unstable_by(|a, b| b.partial_cmp(a).unwrap());
}
let m = &res[0];
Match {
score: m.score,
name: m.name,
license_type: m.license_type,
data: m.data,
}
}
}