use dom_query::NodeId;
use hashbrown::HashMap;
#[derive(Debug, Clone, Default)]
pub struct ReadabilityData {
pub content_score: f64,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct NodeStats {
pub text_length: usize,
pub comma_count: usize,
pub has_sentence_end: bool,
}
impl ReadabilityData {
pub fn with_score(score: f64) -> Self {
Self {
content_score: score,
}
}
}
#[derive(Debug, Default)]
pub struct NodeDataStore {
data: HashMap<NodeId, ReadabilityData>,
data_tables: HashMap<NodeId, bool>,
stats: HashMap<NodeId, NodeStats>,
text: HashMap<NodeId, String>,
}
impl NodeDataStore {
pub fn new() -> Self {
Self {
data: HashMap::new(),
data_tables: HashMap::new(),
stats: HashMap::new(),
text: HashMap::new(),
}
}
pub fn get(&self, node_id: &NodeId) -> Option<&ReadabilityData> {
self.data.get(node_id)
}
pub fn get_mut(&mut self, node_id: &NodeId) -> Option<&mut ReadabilityData> {
self.data.get_mut(node_id)
}
pub fn set(&mut self, node_id: NodeId, data: ReadabilityData) {
self.data.insert(node_id, data);
}
pub fn has(&self, node_id: &NodeId) -> bool {
self.data.contains_key(node_id)
}
pub fn get_content_score(&self, node_id: &NodeId) -> f64 {
self.data
.get(node_id)
.map(|d| d.content_score)
.unwrap_or(0.0)
}
pub fn add_content_score(&mut self, node_id: NodeId, score: f64) {
let data = self.data.entry(node_id).or_default();
data.content_score += score;
}
pub fn initialize_if_absent(&mut self, node_id: NodeId, data: ReadabilityData) -> bool {
match self.data.entry(node_id) {
hashbrown::hash_map::Entry::Occupied(_) => false,
hashbrown::hash_map::Entry::Vacant(entry) => {
entry.insert(data);
true
}
}
}
pub fn set_data_table(&mut self, node_id: NodeId, is_data_table: bool) {
self.data_tables.insert(node_id, is_data_table);
}
pub fn is_data_table(&self, node_id: &NodeId) -> Option<bool> {
self.data_tables.get(node_id).copied()
}
pub fn clear(&mut self) {
self.data.clear();
self.data_tables.clear();
self.stats.clear();
self.text.clear();
}
pub fn get_stats(&self, node_id: &NodeId) -> Option<&NodeStats> {
self.stats.get(node_id)
}
pub fn set_stats(&mut self, node_id: NodeId, stats: NodeStats) {
self.stats.insert(node_id, stats);
}
pub fn get_text(&self, node_id: &NodeId) -> Option<&str> {
self.text.get(node_id).map(String::as_str)
}
pub fn set_text(&mut self, node_id: NodeId, text: String) {
self.text.insert(node_id, text);
}
}