dcbor_pattern/pattern/meta/
any_pattern.rs1use dcbor::prelude::*;
2
3use crate::pattern::{Matcher, Path, Pattern, vm::Instr};
4
5#[derive(Debug, Clone, Hash, PartialEq, Eq)]
7pub struct AnyPattern;
8
9impl AnyPattern {
10 pub fn new() -> Self { AnyPattern }
12}
13
14impl Default for AnyPattern {
15 fn default() -> Self { Self::new() }
16}
17
18impl Matcher for AnyPattern {
19 fn paths(&self, haystack: &CBOR) -> Vec<Path> {
20 vec![vec![haystack.clone()]]
22 }
23
24 fn paths_with_captures(
25 &self,
26 haystack: &CBOR,
27 ) -> (Vec<Path>, std::collections::HashMap<String, Vec<Path>>) {
28 (self.paths(haystack), std::collections::HashMap::new())
31 }
32
33 fn compile(
34 &self,
35 code: &mut Vec<Instr>,
36 _literals: &mut Vec<Pattern>,
37 _captures: &mut Vec<String>,
38 ) {
39 code.push(Instr::Save);
41 }
42
43 fn collect_capture_names(&self, _names: &mut Vec<String>) {
44 }
46}
47
48impl std::fmt::Display for AnyPattern {
49 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50 write!(f, "*")
51 }
52}
53
54#[cfg(test)]
55mod tests {
56 use super::*;
57
58 #[test]
59 fn test_any_pattern_display() {
60 let pattern = AnyPattern::new();
61 assert_eq!(pattern.to_string(), "*");
62 }
63
64 #[test]
65 fn test_any_pattern_matches_everything() {
66 let pattern = AnyPattern::new();
67
68 assert!(pattern.matches(&CBOR::from(42)));
70 assert!(pattern.matches(&CBOR::from("hello")));
71 assert!(pattern.matches(&CBOR::from(true)));
72 assert!(pattern.matches(&CBOR::from(vec![1, 2, 3])));
73 assert!(pattern.matches(&CBOR::null()));
74 }
75
76 #[test]
77 fn test_any_pattern_paths() {
78 let pattern = AnyPattern::new();
79 let cbor = CBOR::from("test");
80 let paths = pattern.paths(&cbor);
81
82 assert_eq!(paths.len(), 1);
83 assert_eq!(paths[0], vec![cbor]);
84 }
85}