zenoh_keyexpr/keyexpr_tree/
support.rs1use alloc::boxed::Box;
2use core::ops::{Deref, DerefMut};
3
4pub trait IWildness: 'static {
9 fn non_wild() -> Self;
10 fn get(&self) -> bool;
11 fn set(&mut self, wildness: bool) -> bool;
12}
13#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
17pub struct NonWild;
18impl IWildness for NonWild {
19 fn non_wild() -> Self {
20 NonWild
21 }
22 fn get(&self) -> bool {
23 false
24 }
25 fn set(&mut self, wildness: bool) -> bool {
26 if wildness {
27 panic!("Attempted to set NonWild to wild, which breaks its contract. You likely attempted to insert a wild key into a `NonWild` tree. Use `bool` instead to make wildness determined at runtime.")
28 }
29 false
30 }
31}
32#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
34pub struct UnknownWildness;
35impl IWildness for UnknownWildness {
36 fn non_wild() -> Self {
37 UnknownWildness
38 }
39 fn get(&self) -> bool {
40 true
41 }
42 fn set(&mut self, _wildness: bool) -> bool {
43 true
44 }
45}
46impl IWildness for bool {
49 fn non_wild() -> Self {
50 false
51 }
52 fn get(&self) -> bool {
53 *self
54 }
55 fn set(&mut self, wildness: bool) -> bool {
56 core::mem::replace(self, wildness)
57 }
58}
59
60pub enum IterOrOption<Iter: Iterator, Item> {
61 Opt(Option<Item>),
62 Iter(Iter),
63}
64impl<Iter: Iterator, Item> Iterator for IterOrOption<Iter, Item>
65where
66 Iter::Item: Coerce<Item>,
67{
68 type Item = Item;
69 fn next(&mut self) -> Option<Self::Item> {
70 match self {
71 IterOrOption::Opt(v) => v.take(),
72 IterOrOption::Iter(it) => it.next().map(Coerce::coerce),
73 }
74 }
75}
76pub struct Coerced<Iter: Iterator, Item> {
77 iter: Iter,
78 _item: core::marker::PhantomData<Item>,
79}
80
81impl<Iter: Iterator, Item> Coerced<Iter, Item> {
82 pub fn new(iter: Iter) -> Self {
83 Self {
84 iter,
85 _item: Default::default(),
86 }
87 }
88}
89impl<Iter: Iterator, Item> Iterator for Coerced<Iter, Item>
90where
91 Iter::Item: Coerce<Item>,
92{
93 type Item = Item;
94
95 fn next(&mut self) -> Option<Self::Item> {
96 self.iter.next().map(Coerce::coerce)
97 }
98}
99
100trait Coerce<Into> {
101 fn coerce(self) -> Into;
102}
103impl<T> Coerce<T> for T {
104 fn coerce(self) -> T {
105 self
106 }
107}
108impl<'a, T> Coerce<&'a T> for &'a Box<T> {
109 fn coerce(self) -> &'a T {
110 self.deref()
111 }
112}
113impl<'a, T> Coerce<&'a mut T> for &'a mut Box<T> {
114 fn coerce(self) -> &'a mut T {
115 self.deref_mut()
116 }
117}
118impl<Iter: Iterator, Item> From<Iter> for IterOrOption<Iter, Item> {
119 fn from(it: Iter) -> Self {
120 Self::Iter(it)
121 }
122}