1use crate::{UtilsError, UtilsResult};
6use scirs2_core::ndarray::Array2;
7use scirs2_core::numeric::Zero;
8use std::collections::{HashMap, HashSet, VecDeque};
9use std::fmt;
10use std::hash::Hash;
11use std::sync::atomic::{AtomicUsize, Ordering};
12use std::sync::{Arc, Mutex, RwLock};
13
14#[derive(Clone, Debug)]
16pub struct ConcurrentQueue<T> {
17 pub(crate) inner: Arc<Mutex<VecDeque<T>>>,
18}
19impl<T: Clone> ConcurrentQueue<T> {
20 pub fn new() -> Self {
22 Self {
23 inner: Arc::new(Mutex::new(VecDeque::new())),
24 }
25 }
26 pub fn push_back(&self, item: T) -> UtilsResult<()> {
28 let mut queue = self
29 .inner
30 .lock()
31 .map_err(|_| UtilsError::InvalidParameter("Lock poisoned".to_string()))?;
32 queue.push_back(item);
33 Ok(())
34 }
35 pub fn push_front(&self, item: T) -> UtilsResult<()> {
37 let mut queue = self
38 .inner
39 .lock()
40 .map_err(|_| UtilsError::InvalidParameter("Lock poisoned".to_string()))?;
41 queue.push_front(item);
42 Ok(())
43 }
44 pub fn pop_front(&self) -> UtilsResult<Option<T>> {
46 let mut queue = self
47 .inner
48 .lock()
49 .map_err(|_| UtilsError::InvalidParameter("Lock poisoned".to_string()))?;
50 Ok(queue.pop_front())
51 }
52 pub fn pop_back(&self) -> UtilsResult<Option<T>> {
54 let mut queue = self
55 .inner
56 .lock()
57 .map_err(|_| UtilsError::InvalidParameter("Lock poisoned".to_string()))?;
58 Ok(queue.pop_back())
59 }
60 pub fn len(&self) -> UtilsResult<usize> {
62 let queue = self
63 .inner
64 .lock()
65 .map_err(|_| UtilsError::InvalidParameter("Lock poisoned".to_string()))?;
66 Ok(queue.len())
67 }
68 pub fn is_empty(&self) -> UtilsResult<bool> {
70 let queue = self
71 .inner
72 .lock()
73 .map_err(|_| UtilsError::InvalidParameter("Lock poisoned".to_string()))?;
74 Ok(queue.is_empty())
75 }
76}
77#[derive(Clone, Debug)]
79pub struct ConcurrentHashMap<K, V> {
80 pub(crate) inner: Arc<RwLock<HashMap<K, V>>>,
81}
82impl<K: Clone + Eq + Hash, V: Clone> ConcurrentHashMap<K, V> {
83 pub fn new() -> Self {
85 Self {
86 inner: Arc::new(RwLock::new(HashMap::new())),
87 }
88 }
89 pub fn insert(&self, key: K, value: V) -> UtilsResult<Option<V>> {
91 let mut map = self
92 .inner
93 .write()
94 .map_err(|_| UtilsError::InvalidParameter("Lock poisoned".to_string()))?;
95 Ok(map.insert(key, value))
96 }
97 pub fn get(&self, key: &K) -> UtilsResult<Option<V>> {
99 let map = self
100 .inner
101 .read()
102 .map_err(|_| UtilsError::InvalidParameter("Lock poisoned".to_string()))?;
103 Ok(map.get(key).cloned())
104 }
105 pub fn remove(&self, key: &K) -> UtilsResult<Option<V>> {
107 let mut map = self
108 .inner
109 .write()
110 .map_err(|_| UtilsError::InvalidParameter("Lock poisoned".to_string()))?;
111 Ok(map.remove(key))
112 }
113 pub fn contains_key(&self, key: &K) -> UtilsResult<bool> {
115 let map = self
116 .inner
117 .read()
118 .map_err(|_| UtilsError::InvalidParameter("Lock poisoned".to_string()))?;
119 Ok(map.contains_key(key))
120 }
121 pub fn len(&self) -> UtilsResult<usize> {
123 let map = self
124 .inner
125 .read()
126 .map_err(|_| UtilsError::InvalidParameter("Lock poisoned".to_string()))?;
127 Ok(map.len())
128 }
129 pub fn is_empty(&self) -> UtilsResult<bool> {
131 let map = self
132 .inner
133 .read()
134 .map_err(|_| UtilsError::InvalidParameter("Lock poisoned".to_string()))?;
135 Ok(map.is_empty())
136 }
137}
138pub struct RingBufferIter<'a, T> {
140 pub(crate) buffer: &'a RingBuffer<T>,
141 pub(crate) index: usize,
142}
143#[derive(Clone, Debug)]
145pub struct TreeNode<T> {
146 pub value: T,
147 pub left: Option<Box<TreeNode<T>>>,
148 pub right: Option<Box<TreeNode<T>>>,
149}
150impl<T> TreeNode<T> {
151 pub fn new(value: T) -> Self {
153 Self {
154 value,
155 left: None,
156 right: None,
157 }
158 }
159 pub fn with_children(
161 value: T,
162 left: Option<Box<TreeNode<T>>>,
163 right: Option<Box<TreeNode<T>>>,
164 ) -> Self {
165 Self { value, left, right }
166 }
167}
168#[derive(Clone, Debug)]
170pub struct WeightedGraph<T, W> {
171 pub(crate) vertices: Vec<T>,
172 pub(crate) edges: Vec<Vec<(usize, W)>>,
173 pub(crate) vertex_map: HashMap<T, usize>,
174}
175impl<T: Clone + Eq + Hash, W: Clone + PartialOrd> WeightedGraph<T, W> {
176 pub fn new() -> Self {
178 Self {
179 vertices: Vec::new(),
180 edges: Vec::new(),
181 vertex_map: HashMap::new(),
182 }
183 }
184 pub fn add_vertex(&mut self, vertex: T) -> usize {
186 if let Some(&idx) = self.vertex_map.get(&vertex) {
187 return idx;
188 }
189 let idx = self.vertices.len();
190 self.vertices.push(vertex.clone());
191 self.edges.push(Vec::new());
192 self.vertex_map.insert(vertex, idx);
193 idx
194 }
195 pub fn add_edge(&mut self, from: &T, to: &T, weight: W) -> UtilsResult<()> {
197 let from_idx = self
198 .vertex_map
199 .get(from)
200 .ok_or_else(|| UtilsError::InvalidParameter("From vertex not found".to_string()))?;
201 let to_idx = self
202 .vertex_map
203 .get(to)
204 .ok_or_else(|| UtilsError::InvalidParameter("To vertex not found".to_string()))?;
205 self.edges[*from_idx].push((*to_idx, weight));
206 Ok(())
207 }
208 pub fn minimum_spanning_tree(&self) -> UtilsResult<Vec<(usize, usize, W)>>
210 where
211 W: Clone + PartialOrd + Copy,
212 {
213 if self.vertices.is_empty() {
214 return Ok(Vec::new());
215 }
216 let mut edges = Vec::new();
217 for (from, adj_list) in self.edges.iter().enumerate() {
218 for &(to, weight) in adj_list {
219 edges.push((weight, from, to));
220 }
221 }
222 edges.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
223 let mut parent = (0..self.vertices.len()).collect::<Vec<_>>();
224 let mut mst = Vec::new();
225 fn find(parent: &mut Vec<usize>, x: usize) -> usize {
226 if parent[x] != x {
227 parent[x] = find(parent, parent[x]);
228 }
229 parent[x]
230 }
231 fn union(parent: &mut Vec<usize>, x: usize, y: usize) {
232 let px = find(parent, x);
233 let py = find(parent, y);
234 if px != py {
235 parent[px] = py;
236 }
237 }
238 for (weight, from, to) in edges {
239 if find(&mut parent, from) != find(&mut parent, to) {
240 union(&mut parent, from, to);
241 mst.push((from, to, weight));
242 }
243 }
244 Ok(mst)
245 }
246 pub fn vertices(&self) -> &[T] {
248 &self.vertices
249 }
250 pub fn edges(&self) -> &[Vec<(usize, W)>] {
252 &self.edges
253 }
254 pub fn serialize(&self) -> String
256 where
257 T: fmt::Display,
258 W: fmt::Display,
259 {
260 let mut result = String::new();
261 result.push_str("WeightedGraph {\n");
262 result.push_str(&format!(" vertices: {} nodes\n", self.vertices.len()));
263 let total_edges: usize = self.edges.iter().map(|edges| edges.len()).sum();
264 result.push_str(&format!(" edges: {total_edges} weighted connections\n"));
265 result.push_str(" adjacency_list: {\n");
266 for (i, vertex) in self.vertices.iter().enumerate() {
267 result.push_str(&format!(" {vertex}: ["));
268 let edge_strs: Vec<String> = self.edges[i]
269 .iter()
270 .map(|(to_idx, weight)| format!("{}:{}", self.vertices[*to_idx], weight))
271 .collect();
272 result.push_str(&edge_strs.join(", "));
273 result.push_str("]\n");
274 }
275 result.push_str(" }\n");
276 result.push_str("}\n");
277 result
278 }
279 pub fn visualize(&self) -> String
281 where
282 T: fmt::Display,
283 W: fmt::Display,
284 {
285 let mut result = String::from("Weighted Graph Visualization:\n");
286 if self.vertices.is_empty() {
287 result.push_str(" (empty graph)\n");
288 return result;
289 }
290 let total_edges: usize = self.edges.iter().map(|edges| edges.len()).sum();
291 result.push_str(&format!(" Vertices: {}\n", self.vertices.len()));
292 result.push_str(&format!(" Weighted Edges: {total_edges}\n"));
293 result.push_str(" Connections:\n");
294 for (i, vertex) in self.vertices.iter().enumerate() {
295 if !self.edges[i].is_empty() {
296 result.push_str(&format!(" {vertex} -> ["));
297 let edge_strs: Vec<String> = self.edges[i]
298 .iter()
299 .map(|(to_idx, weight)| format!("{}(w:{})", self.vertices[*to_idx], weight))
300 .collect();
301 result.push_str(&edge_strs.join(", "));
302 result.push_str("]\n");
303 } else {
304 result.push_str(&format!(" {vertex} -> []\n"));
305 }
306 }
307 result
308 }
309 pub fn structural_equals(&self, other: &Self) -> bool
311 where
312 T: PartialEq,
313 W: PartialEq + Eq + Hash,
314 {
315 if self.vertices.len() != other.vertices.len() {
316 return false;
317 }
318 if self.edges.len() != other.edges.len() {
319 return false;
320 }
321 for vertex in &self.vertices {
322 if !other.vertices.contains(vertex) {
323 return false;
324 }
325 }
326 for (vertex, edges) in self.vertices.iter().zip(self.edges.iter()) {
327 if let Some(&other_idx) = other.vertex_map.get(vertex) {
328 let other_edges = &other.edges[other_idx];
329 if edges.len() != other_edges.len() {
330 return false;
331 }
332 let self_edge_set: HashSet<_> = edges
333 .iter()
334 .map(|(idx, weight)| (&self.vertices[*idx], weight))
335 .collect();
336 let other_edge_set: HashSet<_> = other_edges
337 .iter()
338 .map(|(idx, weight)| (&other.vertices[*idx], weight))
339 .collect();
340 if self_edge_set != other_edge_set {
341 return false;
342 }
343 } else {
344 return false;
345 }
346 }
347 true
348 }
349}
350#[derive(Debug, Default, Clone)]
352pub struct TrieStatistics {
353 pub node_count: usize,
354 pub leaf_count: usize,
355 pub internal_count: usize,
356 pub word_count: usize,
357 pub max_depth: usize,
358 pub branch_factor: usize,
359}
360#[derive(Clone, Debug)]
362pub struct Graph<T> {
363 pub(crate) vertices: Vec<T>,
364 pub(crate) adjacency: Vec<Vec<usize>>,
365 pub(crate) vertex_map: HashMap<T, usize>,
366}
367impl<T: Clone + Eq + Hash> Graph<T> {
368 pub fn new() -> Self {
370 Self {
371 vertices: Vec::new(),
372 adjacency: Vec::new(),
373 vertex_map: HashMap::new(),
374 }
375 }
376 pub fn add_vertex(&mut self, vertex: T) -> usize {
378 if let Some(&idx) = self.vertex_map.get(&vertex) {
379 return idx;
380 }
381 let idx = self.vertices.len();
382 self.vertices.push(vertex.clone());
383 self.adjacency.push(Vec::new());
384 self.vertex_map.insert(vertex, idx);
385 idx
386 }
387 pub fn add_edge(&mut self, from: &T, to: &T) -> UtilsResult<()> {
389 let from_idx = self
390 .vertex_map
391 .get(from)
392 .ok_or_else(|| UtilsError::InvalidParameter("From vertex not found".to_string()))?;
393 let to_idx = self
394 .vertex_map
395 .get(to)
396 .ok_or_else(|| UtilsError::InvalidParameter("To vertex not found".to_string()))?;
397 self.adjacency[*from_idx].push(*to_idx);
398 Ok(())
399 }
400 pub fn add_undirected_edge(&mut self, v1: &T, v2: &T) -> UtilsResult<()> {
402 self.add_edge(v1, v2)?;
403 self.add_edge(v2, v1)?;
404 Ok(())
405 }
406 pub fn neighbors(&self, vertex: &T) -> UtilsResult<Vec<&T>> {
408 let idx = self
409 .vertex_map
410 .get(vertex)
411 .ok_or_else(|| UtilsError::InvalidParameter("Vertex not found".to_string()))?;
412 Ok(self.adjacency[*idx]
413 .iter()
414 .map(|&i| &self.vertices[i])
415 .collect())
416 }
417 pub fn num_vertices(&self) -> usize {
419 self.vertices.len()
420 }
421 pub fn num_edges(&self) -> usize {
423 self.adjacency.iter().map(|adj| adj.len()).sum()
424 }
425 pub fn bfs(&self, start: &T) -> UtilsResult<Vec<&T>> {
427 let start_idx = self
428 .vertex_map
429 .get(start)
430 .ok_or_else(|| UtilsError::InvalidParameter("Start vertex not found".to_string()))?;
431 let mut visited = vec![false; self.vertices.len()];
432 let mut queue = VecDeque::new();
433 let mut result = Vec::new();
434 queue.push_back(*start_idx);
435 visited[*start_idx] = true;
436 while let Some(current) = queue.pop_front() {
437 result.push(&self.vertices[current]);
438 for &neighbor in &self.adjacency[current] {
439 if !visited[neighbor] {
440 visited[neighbor] = true;
441 queue.push_back(neighbor);
442 }
443 }
444 }
445 Ok(result)
446 }
447 pub fn dfs(&self, start: &T) -> UtilsResult<Vec<&T>> {
449 let start_idx = self
450 .vertex_map
451 .get(start)
452 .ok_or_else(|| UtilsError::InvalidParameter("Start vertex not found".to_string()))?;
453 let mut visited = vec![false; self.vertices.len()];
454 let mut result = Vec::new();
455 self.dfs_recursive(*start_idx, &mut visited, &mut result);
456 Ok(result)
457 }
458 fn dfs_recursive<'a>(
459 &'a self,
460 current: usize,
461 visited: &mut Vec<bool>,
462 result: &mut Vec<&'a T>,
463 ) {
464 visited[current] = true;
465 result.push(&self.vertices[current]);
466 for &neighbor in &self.adjacency[current] {
467 if !visited[neighbor] {
468 self.dfs_recursive(neighbor, visited, result);
469 }
470 }
471 }
472 pub fn has_cycle(&self) -> bool {
474 let mut visited = vec![false; self.vertices.len()];
475 let mut rec_stack = vec![false; self.vertices.len()];
476 for i in 0..self.vertices.len() {
477 if !visited[i] && self.has_cycle_util(i, &mut visited, &mut rec_stack) {
478 return true;
479 }
480 }
481 false
482 }
483 fn has_cycle_util(
484 &self,
485 current: usize,
486 visited: &mut Vec<bool>,
487 rec_stack: &mut Vec<bool>,
488 ) -> bool {
489 visited[current] = true;
490 rec_stack[current] = true;
491 for &neighbor in &self.adjacency[current] {
492 if (!visited[neighbor] && self.has_cycle_util(neighbor, visited, rec_stack))
493 || rec_stack[neighbor]
494 {
495 return true;
496 }
497 }
498 rec_stack[current] = false;
499 false
500 }
501 pub fn to_adjacency_matrix(&self) -> Array2<u8> {
503 let n = self.vertices.len();
504 let mut matrix = Array2::zeros((n, n));
505 for (i, neighbors) in self.adjacency.iter().enumerate() {
506 for &j in neighbors {
507 matrix[[i, j]] = 1;
508 }
509 }
510 matrix
511 }
512 pub fn vertices(&self) -> &[T] {
514 &self.vertices
515 }
516 pub fn adjacency(&self) -> &[Vec<usize>] {
518 &self.adjacency
519 }
520 pub fn serialize(&self) -> String
522 where
523 T: fmt::Display,
524 {
525 let mut result = String::new();
526 result.push_str("Graph {\n");
527 result.push_str(&format!(" vertices: {} nodes\n", self.vertices.len()));
528 result.push_str(&format!(" edges: {} connections\n", self.num_edges()));
529 result.push_str(" adjacency_list: {\n");
530 for (i, vertex) in self.vertices.iter().enumerate() {
531 result.push_str(&format!(" {vertex}: ["));
532 let neighbors: Vec<String> = self.adjacency[i]
533 .iter()
534 .map(|&idx| self.vertices[idx].to_string())
535 .collect();
536 result.push_str(&neighbors.join(", "));
537 result.push_str("]\n");
538 }
539 result.push_str(" }\n");
540 result.push_str("}\n");
541 result
542 }
543 pub fn visualize(&self) -> String
545 where
546 T: fmt::Display,
547 {
548 let mut result = String::from("Graph Visualization:\n");
549 if self.vertices.is_empty() {
550 result.push_str(" (empty graph)\n");
551 return result;
552 }
553 result.push_str(&format!(" Vertices: {}\n", self.vertices.len()));
554 result.push_str(&format!(" Edges: {}\n", self.num_edges()));
555 result.push_str(&format!(" Has cycle: {}\n", self.has_cycle()));
556 result.push_str(" Connections:\n");
557 for vertex in &self.vertices {
558 if let Ok(neighbors) = self.neighbors(vertex) {
559 result.push_str(&format!(" {vertex} -> ["));
560 let neighbor_strs: Vec<String> = neighbors.iter().map(|n| n.to_string()).collect();
561 result.push_str(&neighbor_strs.join(", "));
562 result.push_str("]\n");
563 }
564 }
565 result
566 }
567 pub fn structural_equals(&self, other: &Self) -> bool
569 where
570 T: PartialEq,
571 {
572 if self.vertices.len() != other.vertices.len() {
573 return false;
574 }
575 if self.adjacency.len() != other.adjacency.len() {
576 return false;
577 }
578 for vertex in &self.vertices {
579 if !other.vertices.contains(vertex) {
580 return false;
581 }
582 }
583 for (vertex, neighbors) in self.vertices.iter().zip(self.adjacency.iter()) {
584 if let Some(&other_idx) = other.vertex_map.get(vertex) {
585 let other_neighbors = &other.adjacency[other_idx];
586 if neighbors.len() != other_neighbors.len() {
587 return false;
588 }
589 let self_neighbor_vertices: HashSet<_> =
590 neighbors.iter().map(|&idx| &self.vertices[idx]).collect();
591 let other_neighbor_vertices: HashSet<_> = other_neighbors
592 .iter()
593 .map(|&idx| &other.vertices[idx])
594 .collect();
595 if self_neighbor_vertices != other_neighbor_vertices {
596 return false;
597 }
598 } else {
599 return false;
600 }
601 }
602 true
603 }
604}
605#[derive(Clone, Debug)]
607pub struct ConcurrentRingBuffer<T> {
608 pub(crate) inner: Arc<Mutex<RingBuffer<T>>>,
609}
610impl<T: Clone> ConcurrentRingBuffer<T> {
611 pub fn new(capacity: usize) -> Self {
613 Self {
614 inner: Arc::new(Mutex::new(RingBuffer::new(capacity))),
615 }
616 }
617 pub fn push(&self, item: T) -> UtilsResult<Option<T>> {
619 let mut buffer = self
620 .inner
621 .lock()
622 .map_err(|_| UtilsError::InvalidParameter("Lock poisoned".to_string()))?;
623 Ok(buffer.push(item))
624 }
625 pub fn pop(&self) -> UtilsResult<Option<T>> {
627 let mut buffer = self
628 .inner
629 .lock()
630 .map_err(|_| UtilsError::InvalidParameter("Lock poisoned".to_string()))?;
631 Ok(buffer.pop())
632 }
633 pub fn len(&self) -> UtilsResult<usize> {
635 let buffer = self
636 .inner
637 .lock()
638 .map_err(|_| UtilsError::InvalidParameter("Lock poisoned".to_string()))?;
639 Ok(buffer.len())
640 }
641 pub fn is_empty(&self) -> UtilsResult<bool> {
643 let buffer = self
644 .inner
645 .lock()
646 .map_err(|_| UtilsError::InvalidParameter("Lock poisoned".to_string()))?;
647 Ok(buffer.is_empty())
648 }
649 pub fn is_full(&self) -> UtilsResult<bool> {
651 let buffer = self
652 .inner
653 .lock()
654 .map_err(|_| UtilsError::InvalidParameter("Lock poisoned".to_string()))?;
655 Ok(buffer.is_full())
656 }
657}
658#[derive(Clone, Debug)]
660pub struct BinarySearchTree<T> {
661 pub(crate) root: Option<Box<TreeNode<T>>>,
662}
663impl<T: Clone + PartialOrd> BinarySearchTree<T> {
664 pub fn new() -> Self {
666 Self { root: None }
667 }
668 pub fn insert(&mut self, value: T) {
670 self.root = Self::insert_recursive(self.root.take(), value);
671 }
672 fn insert_recursive(node: Option<Box<TreeNode<T>>>, value: T) -> Option<Box<TreeNode<T>>> {
673 match node {
674 None => Some(Box::new(TreeNode::new(value))),
675 Some(mut node) => {
676 if value <= node.value {
677 node.left = Self::insert_recursive(node.left.take(), value);
678 } else {
679 node.right = Self::insert_recursive(node.right.take(), value);
680 }
681 Some(node)
682 }
683 }
684 }
685 pub fn search(&self, value: &T) -> bool {
687 Self::search_recursive(&self.root, value)
688 }
689 fn search_recursive(node: &Option<Box<TreeNode<T>>>, value: &T) -> bool {
690 match node {
691 None => false,
692 Some(node) => {
693 if *value == node.value {
694 true
695 } else if *value < node.value {
696 Self::search_recursive(&node.left, value)
697 } else {
698 Self::search_recursive(&node.right, value)
699 }
700 }
701 }
702 }
703 pub fn inorder(&self) -> Vec<&T> {
705 let mut result = Vec::new();
706 Self::inorder_recursive(&self.root, &mut result);
707 result
708 }
709 fn inorder_recursive<'a>(node: &'a Option<Box<TreeNode<T>>>, result: &mut Vec<&'a T>) {
710 if let Some(node) = node {
711 Self::inorder_recursive(&node.left, result);
712 result.push(&node.value);
713 Self::inorder_recursive(&node.right, result);
714 }
715 }
716 pub fn preorder(&self) -> Vec<&T> {
718 let mut result = Vec::new();
719 Self::preorder_recursive(&self.root, &mut result);
720 result
721 }
722 fn preorder_recursive<'a>(node: &'a Option<Box<TreeNode<T>>>, result: &mut Vec<&'a T>) {
723 if let Some(node) = node {
724 result.push(&node.value);
725 Self::preorder_recursive(&node.left, result);
726 Self::preorder_recursive(&node.right, result);
727 }
728 }
729 pub fn postorder(&self) -> Vec<&T> {
731 let mut result = Vec::new();
732 Self::postorder_recursive(&self.root, &mut result);
733 result
734 }
735 fn postorder_recursive<'a>(node: &'a Option<Box<TreeNode<T>>>, result: &mut Vec<&'a T>) {
736 if let Some(node) = node {
737 Self::postorder_recursive(&node.left, result);
738 Self::postorder_recursive(&node.right, result);
739 result.push(&node.value);
740 }
741 }
742 pub fn height(&self) -> usize {
744 Self::height_recursive(&self.root)
745 }
746 fn height_recursive(node: &Option<Box<TreeNode<T>>>) -> usize {
747 match node {
748 None => 0,
749 Some(node) => {
750 1 + std::cmp::max(
751 Self::height_recursive(&node.left),
752 Self::height_recursive(&node.right),
753 )
754 }
755 }
756 }
757 pub fn root(&self) -> &Option<Box<TreeNode<T>>> {
759 &self.root
760 }
761 pub fn serialize(&self) -> String
763 where
764 T: fmt::Display,
765 {
766 Self::serialize_node(&self.root, 0)
767 }
768 fn serialize_node(node: &Option<Box<TreeNode<T>>>, depth: usize) -> String
769 where
770 T: fmt::Display,
771 {
772 match node {
773 None => "null".to_string(),
774 Some(node) => {
775 let indent = " ".repeat(depth);
776 let mut result = format!("{}node: {}\n", indent, node.value);
777 if node.left.is_some() || node.right.is_some() {
778 result.push_str(&format!("{indent}left:\n"));
779 result.push_str(&Self::serialize_node(&node.left, depth + 1));
780 result.push_str(&format!("{indent}right:\n"));
781 result.push_str(&Self::serialize_node(&node.right, depth + 1));
782 }
783 result
784 }
785 }
786 }
787 pub fn visualize(&self) -> String
789 where
790 T: fmt::Display,
791 {
792 if self.root.is_none() {
793 return "Empty tree".to_string();
794 }
795 Self::visualize_node(&self.root, "", true)
796 }
797 fn visualize_node(node: &Option<Box<TreeNode<T>>>, prefix: &str, is_last: bool) -> String
798 where
799 T: fmt::Display,
800 {
801 match node {
802 None => String::new(),
803 Some(node) => {
804 let mut result = String::new();
805 let connector = if is_last { "└── " } else { "├── " };
806 result.push_str(&format!("{}{}{}\n", prefix, connector, node.value));
807 let extension = if is_last { " " } else { "│ " };
808 let new_prefix = format!("{prefix}{extension}");
809 if node.left.is_some() || node.right.is_some() {
810 if node.right.is_some() {
811 result.push_str(&Self::visualize_node(
812 &node.right,
813 &new_prefix,
814 node.left.is_none(),
815 ));
816 }
817 if node.left.is_some() {
818 result.push_str(&Self::visualize_node(&node.left, &new_prefix, true));
819 }
820 }
821 result
822 }
823 }
824 }
825 pub fn structural_equals(&self, other: &Self) -> bool
827 where
828 T: PartialEq,
829 {
830 Self::nodes_equal(&self.root, &other.root)
831 }
832 fn nodes_equal(node1: &Option<Box<TreeNode<T>>>, node2: &Option<Box<TreeNode<T>>>) -> bool
833 where
834 T: PartialEq,
835 {
836 match (node1, node2) {
837 (None, None) => true,
838 (Some(n1), Some(n2)) => {
839 n1.value == n2.value
840 && Self::nodes_equal(&n1.left, &n2.left)
841 && Self::nodes_equal(&n1.right, &n2.right)
842 }
843 _ => false,
844 }
845 }
846 pub fn same_structure(&self, other: &Self) -> bool {
848 Self::same_structure_nodes(&self.root, &other.root)
849 }
850 fn same_structure_nodes(
851 node1: &Option<Box<TreeNode<T>>>,
852 node2: &Option<Box<TreeNode<T>>>,
853 ) -> bool {
854 match (node1, node2) {
855 (None, None) => true,
856 (Some(n1), Some(n2)) => {
857 Self::same_structure_nodes(&n1.left, &n2.left)
858 && Self::same_structure_nodes(&n1.right, &n2.right)
859 }
860 _ => false,
861 }
862 }
863 pub fn statistics(&self) -> TreeStatistics {
865 let mut stats = TreeStatistics::default();
866 Self::collect_statistics(&self.root, &mut stats, 0);
867 stats
868 }
869 fn collect_statistics(
870 node: &Option<Box<TreeNode<T>>>,
871 stats: &mut TreeStatistics,
872 depth: usize,
873 ) {
874 match node {
875 None => {
876 stats.max_depth = stats.max_depth.max(depth);
877 }
878 Some(node) => {
879 stats.node_count += 1;
880 stats.max_depth = stats.max_depth.max(depth);
881 let has_left = node.left.is_some();
882 let has_right = node.right.is_some();
883 match (has_left, has_right) {
884 (false, false) => stats.leaf_count += 1,
885 (true, false) | (false, true) => stats.internal_count += 1,
886 (true, true) => stats.internal_count += 1,
887 }
888 Self::collect_statistics(&node.left, stats, depth + 1);
889 Self::collect_statistics(&node.right, stats, depth + 1);
890 }
891 }
892 }
893 pub fn is_balanced(&self) -> bool {
895 Self::check_balance(&self.root).is_some()
896 }
897 fn check_balance(node: &Option<Box<TreeNode<T>>>) -> Option<usize> {
898 match node {
899 None => Some(0),
900 Some(node) => {
901 let left_height = Self::check_balance(&node.left)?;
902 let right_height = Self::check_balance(&node.right)?;
903 if left_height.abs_diff(right_height) <= 1 {
904 Some(1 + left_height.max(right_height))
905 } else {
906 None
907 }
908 }
909 }
910 }
911}
912#[derive(Clone, Debug)]
914pub struct AtomicCounter {
915 pub(crate) value: Arc<AtomicUsize>,
916}
917impl AtomicCounter {
918 pub fn new(initial: usize) -> Self {
920 Self {
921 value: Arc::new(AtomicUsize::new(initial)),
922 }
923 }
924 pub fn increment(&self) -> usize {
926 self.value.fetch_add(1, Ordering::SeqCst) + 1
927 }
928 pub fn decrement(&self) -> usize {
930 self.value.fetch_sub(1, Ordering::SeqCst).saturating_sub(1)
931 }
932 pub fn add(&self, val: usize) -> usize {
934 self.value.fetch_add(val, Ordering::SeqCst) + val
935 }
936 pub fn sub(&self, val: usize) -> usize {
938 self.value
939 .fetch_sub(val, Ordering::SeqCst)
940 .saturating_sub(val)
941 }
942 pub fn get(&self) -> usize {
944 self.value.load(Ordering::SeqCst)
945 }
946 pub fn set(&self, val: usize) {
948 self.value.store(val, Ordering::SeqCst);
949 }
950 pub fn compare_and_swap(&self, current: usize, new: usize) -> usize {
952 match self
953 .value
954 .compare_exchange(current, new, Ordering::SeqCst, Ordering::SeqCst)
955 {
956 Ok(prev) => prev,
957 Err(prev) => prev,
958 }
959 }
960}
961#[derive(Debug, Default, Clone)]
963pub struct TreeStatistics {
964 pub node_count: usize,
965 pub leaf_count: usize,
966 pub internal_count: usize,
967 pub max_depth: usize,
968}
969#[derive(Clone, Debug)]
971pub struct Trie {
972 pub(crate) children: HashMap<char, Trie>,
973 pub(crate) is_end_of_word: bool,
974}
975impl Trie {
976 pub fn new() -> Self {
978 Self {
979 children: HashMap::new(),
980 is_end_of_word: false,
981 }
982 }
983 pub fn insert(&mut self, word: &str) {
985 let mut current = self;
986 for ch in word.chars() {
987 current = current.children.entry(ch).or_default();
988 }
989 current.is_end_of_word = true;
990 }
991 pub fn search(&self, word: &str) -> bool {
993 let mut current = self;
994 for ch in word.chars() {
995 match current.children.get(&ch) {
996 Some(node) => current = node,
997 None => return false,
998 }
999 }
1000 current.is_end_of_word
1001 }
1002 pub fn starts_with(&self, prefix: &str) -> bool {
1004 let mut current = self;
1005 for ch in prefix.chars() {
1006 match current.children.get(&ch) {
1007 Some(node) => current = node,
1008 None => return false,
1009 }
1010 }
1011 true
1012 }
1013 pub fn words_with_prefix(&self, prefix: &str) -> Vec<String> {
1015 let mut current = self;
1016 for ch in prefix.chars() {
1017 match current.children.get(&ch) {
1018 Some(node) => current = node,
1019 None => return Vec::new(),
1020 }
1021 }
1022 let mut words = Vec::new();
1023 current.collect_words(prefix.to_string(), &mut words);
1024 words
1025 }
1026 fn collect_words(&self, prefix: String, words: &mut Vec<String>) {
1027 if self.is_end_of_word {
1028 words.push(prefix.clone());
1029 }
1030 for (&ch, child) in &self.children {
1031 let mut new_prefix = prefix.clone();
1032 new_prefix.push(ch);
1033 child.collect_words(new_prefix, words);
1034 }
1035 }
1036 pub fn all_words(&self) -> Vec<String> {
1038 let mut words = Vec::new();
1039 self.collect_words(String::new(), &mut words);
1040 words
1041 }
1042 pub fn word_count(&self) -> usize {
1044 let mut count = 0;
1045 if self.is_end_of_word {
1046 count += 1;
1047 }
1048 for child in self.children.values() {
1049 count += child.word_count();
1050 }
1051 count
1052 }
1053 pub fn serialize(&self) -> String {
1055 let mut result = String::new();
1056 self.serialize_node("".to_string(), &mut result, 0);
1057 result
1058 }
1059 fn serialize_node(&self, prefix: String, result: &mut String, depth: usize) {
1060 let indent = " ".repeat(depth);
1061 if self.is_end_of_word {
1062 result.push_str(&format!("{indent}word: {prefix}\n"));
1063 }
1064 for (&ch, child) in &self.children {
1065 let mut new_prefix = prefix.clone();
1066 new_prefix.push(ch);
1067 result.push_str(&format!("{indent}char: {ch} -> \n"));
1068 child.serialize_node(new_prefix, result, depth + 1);
1069 }
1070 }
1071 pub fn visualize(&self) -> String {
1073 let mut result = String::from("Trie\n");
1074 self.visualize_node("", "", true, &mut result);
1075 result
1076 }
1077 fn visualize_node(&self, prefix: &str, char_prefix: &str, is_last: bool, result: &mut String) {
1078 let connector = if is_last { "└── " } else { "├── " };
1079 if self.is_end_of_word {
1080 result.push_str(&format!("{char_prefix}{connector}[{prefix}] ✓\n"));
1081 } else if !prefix.is_empty() {
1082 result.push_str(&format!("{char_prefix}{connector}[{prefix}]\n"));
1083 }
1084 let extension = if is_last { " " } else { "│ " };
1085 let new_char_prefix = format!("{char_prefix}{extension}");
1086 let children: Vec<_> = self.children.iter().collect();
1087 for (i, (&ch, child)) in children.iter().enumerate() {
1088 let is_last_child = i == children.len() - 1;
1089 let mut new_prefix = prefix.to_string();
1090 new_prefix.push(ch);
1091 child.visualize_node(&new_prefix, &new_char_prefix, is_last_child, result);
1092 }
1093 }
1094 pub fn structural_equals(&self, other: &Self) -> bool {
1096 if self.is_end_of_word != other.is_end_of_word {
1097 return false;
1098 }
1099 if self.children.len() != other.children.len() {
1100 return false;
1101 }
1102 for (&ch, child) in &self.children {
1103 match other.children.get(&ch) {
1104 Some(other_child) => {
1105 if !child.structural_equals(other_child) {
1106 return false;
1107 }
1108 }
1109 None => return false,
1110 }
1111 }
1112 true
1113 }
1114 pub fn contains_trie(&self, other: &Self) -> bool {
1116 for word in other.all_words() {
1117 if !self.search(&word) {
1118 return false;
1119 }
1120 }
1121 true
1122 }
1123 pub fn statistics(&self) -> TrieStatistics {
1125 let mut stats = TrieStatistics::default();
1126 self.collect_trie_statistics(&mut stats, 0);
1127 stats
1128 }
1129 fn collect_trie_statistics(&self, stats: &mut TrieStatistics, depth: usize) {
1130 stats.node_count += 1;
1131 stats.max_depth = stats.max_depth.max(depth);
1132 if self.is_end_of_word {
1133 stats.word_count += 1;
1134 }
1135 if self.children.is_empty() {
1136 stats.leaf_count += 1;
1137 } else {
1138 stats.internal_count += 1;
1139 stats.branch_factor = stats.branch_factor.max(self.children.len());
1140 }
1141 for child in self.children.values() {
1142 child.collect_trie_statistics(stats, depth + 1);
1143 }
1144 }
1145 pub fn remove(&mut self, word: &str) -> bool {
1147 let chars: Vec<char> = word.chars().collect();
1148 self.remove_recursive(&chars, 0).0
1149 }
1150 fn remove_recursive(&mut self, chars: &[char], index: usize) -> (bool, bool) {
1151 if index == chars.len() {
1152 if self.is_end_of_word {
1153 self.is_end_of_word = false;
1154 return (true, self.children.is_empty());
1155 }
1156 return (false, false);
1157 }
1158 let ch = chars[index];
1159 if let Some(child) = self.children.get_mut(&ch) {
1160 let (word_existed, should_remove_child) = child.remove_recursive(chars, index + 1);
1161 if should_remove_child {
1162 self.children.remove(&ch);
1163 }
1164 let can_remove_self = !self.is_end_of_word && self.children.is_empty();
1165 return (word_existed, can_remove_self);
1166 }
1167 (false, false)
1168 }
1169 pub fn longest_common_prefix(&self) -> String {
1171 let mut prefix = String::new();
1172 let mut current = self;
1173 while current.children.len() == 1 && !current.is_end_of_word {
1174 let (&ch, child) = current.children.iter().next().unwrap();
1175 prefix.push(ch);
1176 current = child;
1177 }
1178 prefix
1179 }
1180}
1181#[derive(Clone, Debug)]
1183pub struct BlockMatrix<T> {
1184 pub(crate) data: Vec<T>,
1185 pub(crate) rows: usize,
1186 pub(crate) cols: usize,
1187 pub(crate) block_size: usize,
1188}
1189impl<T: Clone + Zero> BlockMatrix<T> {
1190 pub fn new(rows: usize, cols: usize, block_size: usize) -> Self {
1192 let total_size = rows * cols;
1193 Self {
1194 data: vec![T::zero(); total_size],
1195 rows,
1196 cols,
1197 block_size,
1198 }
1199 }
1200 pub fn get(&self, row: usize, col: usize) -> UtilsResult<&T> {
1202 if row >= self.rows || col >= self.cols {
1203 return Err(UtilsError::InvalidParameter(format!(
1204 "Index ({}, {}) out of bounds for {}x{} matrix",
1205 row, col, self.rows, self.cols
1206 )));
1207 }
1208 let index = self.block_index(row, col);
1209 Ok(&self.data[index])
1210 }
1211 pub fn set(&mut self, row: usize, col: usize, value: T) -> UtilsResult<()> {
1213 if row >= self.rows || col >= self.cols {
1214 return Err(UtilsError::InvalidParameter(format!(
1215 "Index ({}, {}) out of bounds for {}x{} matrix",
1216 row, col, self.rows, self.cols
1217 )));
1218 }
1219 let index = self.block_index(row, col);
1220 self.data[index] = value;
1221 Ok(())
1222 }
1223 fn block_index(&self, row: usize, col: usize) -> usize {
1224 let block_row = row / self.block_size;
1225 let block_col = col / self.block_size;
1226 let in_block_row = row % self.block_size;
1227 let in_block_col = col % self.block_size;
1228 let blocks_per_row = (self.cols + self.block_size - 1) / self.block_size;
1229 let block_index = block_row * blocks_per_row + block_col;
1230 let block_start = block_index * self.block_size * self.block_size;
1231 block_start + in_block_row * self.block_size + in_block_col
1232 }
1233 pub fn dim(&self) -> (usize, usize) {
1235 (self.rows, self.cols)
1236 }
1237}
1238#[derive(Clone, Debug)]
1240pub struct WorkQueue<T> {
1241 pub(crate) queue: Arc<Mutex<VecDeque<T>>>,
1242 pub(crate) active_workers: Arc<AtomicUsize>,
1243}
1244impl<T: Clone> WorkQueue<T> {
1245 pub fn new() -> Self {
1247 Self {
1248 queue: Arc::new(Mutex::new(VecDeque::new())),
1249 active_workers: Arc::new(AtomicUsize::new(0)),
1250 }
1251 }
1252 pub fn add_work(&self, work: T) -> UtilsResult<()> {
1254 let mut queue = self
1255 .queue
1256 .lock()
1257 .map_err(|_| UtilsError::InvalidParameter("Lock poisoned".to_string()))?;
1258 queue.push_back(work);
1259 Ok(())
1260 }
1261 pub fn get_work(&self) -> UtilsResult<Option<T>> {
1263 let mut queue = self
1264 .queue
1265 .lock()
1266 .map_err(|_| UtilsError::InvalidParameter("Lock poisoned".to_string()))?;
1267 Ok(queue.pop_front())
1268 }
1269 pub fn register_worker(&self) {
1271 self.active_workers.fetch_add(1, Ordering::SeqCst);
1272 }
1273 pub fn unregister_worker(&self) {
1275 self.active_workers.fetch_sub(1, Ordering::SeqCst);
1276 }
1277 pub fn active_worker_count(&self) -> usize {
1279 self.active_workers.load(Ordering::SeqCst)
1280 }
1281 pub fn has_work(&self) -> UtilsResult<bool> {
1283 let queue = self
1284 .queue
1285 .lock()
1286 .map_err(|_| UtilsError::InvalidParameter("Lock poisoned".to_string()))?;
1287 Ok(!queue.is_empty())
1288 }
1289 pub fn queue_size(&self) -> UtilsResult<usize> {
1291 let queue = self
1292 .queue
1293 .lock()
1294 .map_err(|_| UtilsError::InvalidParameter("Lock poisoned".to_string()))?;
1295 Ok(queue.len())
1296 }
1297}
1298#[derive(Clone, Debug)]
1300pub struct RingBuffer<T> {
1301 pub(crate) data: Vec<Option<T>>,
1302 pub(crate) capacity: usize,
1303 pub(crate) head: usize,
1304 pub(crate) tail: usize,
1305 pub(crate) size: usize,
1306}
1307impl<T: Clone> RingBuffer<T> {
1308 pub fn new(capacity: usize) -> Self {
1310 Self {
1311 data: vec![None; capacity],
1312 capacity,
1313 head: 0,
1314 tail: 0,
1315 size: 0,
1316 }
1317 }
1318 pub fn push(&mut self, item: T) -> Option<T> {
1320 let old_item = if self.size == self.capacity {
1321 self.data[self.tail].take()
1322 } else {
1323 None
1324 };
1325 self.data[self.tail] = Some(item);
1326 self.tail = (self.tail + 1) % self.capacity;
1327 if self.size == self.capacity {
1328 self.head = (self.head + 1) % self.capacity;
1329 } else {
1330 self.size += 1;
1331 }
1332 old_item
1333 }
1334 pub fn pop(&mut self) -> Option<T> {
1336 if self.size == 0 {
1337 return None;
1338 }
1339 let item = self.data[self.head].take();
1340 self.head = (self.head + 1) % self.capacity;
1341 self.size -= 1;
1342 item
1343 }
1344 pub fn len(&self) -> usize {
1346 self.size
1347 }
1348 pub fn is_empty(&self) -> bool {
1350 self.size == 0
1351 }
1352 pub fn is_full(&self) -> bool {
1354 self.size == self.capacity
1355 }
1356 pub fn iter(&self) -> RingBufferIter<'_, T> {
1358 RingBufferIter {
1359 buffer: self,
1360 index: 0,
1361 }
1362 }
1363}