use crate::types::{FuzzyLimits, NumEdits};
#[derive(Debug, Clone, PartialEq)]
pub struct Pattern {
pub pattern: String,
pub grapheme_len: usize,
pub custom_unique_id: Option<usize>,
pub weight: f32,
pub limits: Option<FuzzyLimits>,
}
impl Pattern {
#[must_use]
pub fn as_str(&self) -> &str {
&self.pattern
}
#[must_use]
pub fn len(&self) -> usize {
self.pattern.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.pattern.is_empty()
}
#[must_use]
pub fn weight(mut self, weight: f32) -> Self {
self.weight = weight;
self
}
#[must_use]
pub fn fuzzy(mut self, limits: FuzzyLimits) -> Self {
self.limits = Some(limits);
self
}
#[must_use]
pub fn custom_unique_id(mut self, id: usize) -> Self {
self.custom_unique_id = Some(id);
self
}
}
fn count_graphemes(s: &str) -> usize {
unicode_segmentation::UnicodeSegmentation::graphemes(s, true).count()
}
impl From<&str> for Pattern {
fn from(s: &str) -> Self {
Pattern {
pattern: s.to_owned(),
grapheme_len: count_graphemes(s),
weight: 1.0,
limits: None,
custom_unique_id: None,
}
}
}
impl From<String> for Pattern {
fn from(s: String) -> Self {
let grapheme_len = count_graphemes(&s);
Pattern {
pattern: s,
grapheme_len,
weight: 1.0,
limits: None,
custom_unique_id: None,
}
}
}
impl From<&String> for Pattern {
fn from(s: &String) -> Self {
Pattern {
pattern: s.clone(),
grapheme_len: count_graphemes(s),
weight: 1.0,
limits: None,
custom_unique_id: None,
}
}
}
impl From<(&str, f32)> for Pattern {
fn from((s, w): (&str, f32)) -> Self {
Pattern {
pattern: s.to_owned(),
grapheme_len: count_graphemes(s),
weight: w,
limits: None,
custom_unique_id: None,
}
}
}
impl From<(String, f32)> for Pattern {
fn from((s, w): (String, f32)) -> Self {
let grapheme_len = count_graphemes(&s);
Pattern {
pattern: s,
grapheme_len,
weight: w,
limits: None,
custom_unique_id: None,
}
}
}
impl From<(&String, f32)> for Pattern {
fn from((s, w): (&String, f32)) -> Self {
Pattern {
pattern: s.clone(),
grapheme_len: count_graphemes(s),
weight: w,
limits: None,
custom_unique_id: None,
}
}
}
impl From<(&str, f32, NumEdits)> for Pattern {
fn from((s, w, max_edits): (&str, f32, NumEdits)) -> Self {
Pattern {
pattern: s.to_owned(),
grapheme_len: count_graphemes(s),
weight: w,
limits: Some(FuzzyLimits::new().edits(max_edits)),
custom_unique_id: None,
}
}
}
impl From<(String, f32, NumEdits)> for Pattern {
fn from((s, w, max_edits): (String, f32, NumEdits)) -> Self {
let grapheme_len = count_graphemes(&s);
Pattern {
pattern: s,
grapheme_len,
weight: w,
limits: Some(FuzzyLimits::new().edits(max_edits)),
custom_unique_id: None,
}
}
}