dcbor_pattern/pattern/value/
null_pattern.rs1use dcbor::prelude::*;
2
3use crate::pattern::{Matcher, Path, Pattern, vm::Instr};
4
5#[derive(Debug, Clone, Hash, Eq, PartialEq, Default)]
7pub struct NullPattern;
8
9impl Matcher for NullPattern {
10 fn paths(&self, haystack: &CBOR) -> Vec<Path> {
11 if haystack.is_null() {
12 vec![vec![haystack.clone()]]
13 } else {
14 vec![]
15 }
16 }
17
18 fn compile(
19 &self,
20 code: &mut Vec<Instr>,
21 literals: &mut Vec<Pattern>,
22 _captures: &mut Vec<String>,
23 ) {
24 let idx = literals.len();
25 literals.push(Pattern::Value(crate::pattern::ValuePattern::Null(
26 self.clone(),
27 )));
28 code.push(Instr::MatchPredicate(idx));
29 }
30}
31
32impl std::fmt::Display for NullPattern {
33 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34 write!(f, "null")
35 }
36}
37
38#[cfg(test)]
39mod tests {
40 use super::*;
41
42 #[test]
43 fn test_null_pattern_matching() {
44 let null_cbor = CBOR::null();
45 let pattern = NullPattern;
46 let paths = pattern.paths(&null_cbor);
47 assert_eq!(paths.len(), 1);
48 assert_eq!(paths[0], vec![null_cbor.clone()]);
49
50 let text_cbor = "test".to_cbor();
52 let paths = pattern.paths(&text_cbor);
53 assert!(paths.is_empty());
54
55 let number_cbor = 42.to_cbor();
56 let paths = pattern.paths(&number_cbor);
57 assert!(paths.is_empty());
58 }
59
60 #[test]
61 fn test_null_pattern_display() {
62 assert_eq!(NullPattern.to_string(), "null");
63 }
64
65 #[test]
66 fn test_null_pattern_matches() {
67 let pattern = NullPattern;
68 let null_cbor = CBOR::null();
69 assert!(pattern.matches(&null_cbor));
70
71 let text_cbor = "test".to_cbor();
72 assert!(!pattern.matches(&text_cbor));
73
74 let bool_cbor = true.to_cbor();
75 assert!(!pattern.matches(&bool_cbor));
76 }
77}