1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
//
// Copyright (c) 2023 ZettaScale Technology
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
//
// Contributors:
//   ZettaScale Zenoh Team, <zenoh@zettascale.tech>
//

use alloc::{boxed::Box, vec::Vec};
use core::convert::{TryFrom, TryInto};

use zenoh_result::{bail, zerror, Error};

use crate::key_expr::keyexpr;

#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct Spec<'a> {
    pub(crate) spec: &'a str,
    pub(crate) id_end: u16,
    pub(crate) pattern_end: u16,
}
impl<'a> TryFrom<&'a str> for Spec<'a> {
    type Error = Error;
    fn try_from(spec: &'a str) -> Result<Self, Self::Error> {
        let Some(id_end) = spec.find(':') else {
            bail!("Spec {spec} didn't contain `:`")
        };
        let pattern_start = id_end + 1;
        let pattern_end = spec[pattern_start..].find('#').unwrap_or(u16::MAX as usize);
        if pattern_start < spec.len() {
            let Ok(id_end) = id_end.try_into() else {
                bail!("Spec {spec} contains an id longer than {}", u16::MAX)
            };
            if pattern_end > u16::MAX as usize {
                bail!("Spec {spec} contains a pattern longer than {}", u16::MAX)
            }
            Ok(Self {
                spec,
                id_end,
                pattern_end: pattern_end as u16,
            })
        } else {
            bail!("Spec {spec} has an empty pattern")
        }
    }
}
impl<'a> Spec<'a> {
    pub fn id(&self) -> &str {
        &self.spec[..self.id_end as usize]
    }
    pub fn pattern(&self) -> &keyexpr {
        unsafe {
            keyexpr::from_str_unchecked(if self.pattern_end != u16::MAX {
                &self.spec[(self.id_end + 1) as usize..self.pattern_end as usize]
            } else {
                &self.spec[(self.id_end + 1) as usize..]
            })
        }
    }
    pub fn default(&self) -> Option<&keyexpr> {
        let pattern_end = self.pattern_end as usize;
        (self.spec.len() > pattern_end)
            .then(|| unsafe { keyexpr::from_str_unchecked(&self.spec[(pattern_end + 1)..]) })
    }
}
impl core::fmt::Debug for Spec<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Display::fmt(self, f)
    }
}
impl core::fmt::Display for Spec<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let spec = self.spec;
        if spec.contains('}') {
            write!(f, "$#{{{spec}}}#")
        } else {
            write!(f, "${{{spec}}}")
        }
    }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Segment<'a> {
    pub(crate) prefix: &'a str,
    pub(crate) spec: Spec<'a>,
}

pub enum IterativeConstructor<Complete, Partial, Error> {
    Complete(Complete),
    Partial(Partial),
    Error(Error),
}
pub trait IKeFormatStorage<'s>: Sized {
    type PartialConstruct;
    type ConstructionError: core::fmt::Display;
    fn new_constructor(
    ) -> IterativeConstructor<Self, Self::PartialConstruct, Self::ConstructionError>;
    fn add_segment(
        constructor: IterativeConstructor<Self, Self::PartialConstruct, Self::ConstructionError>,
        segment: Segment<'s>,
    ) -> IterativeConstructor<Self, Self::PartialConstruct, Self::ConstructionError>;
    fn segments(&self) -> &[Segment<'s>];
    fn segments_mut(&mut self) -> &mut [Segment<'s>];
    fn segment(&self, id: &str) -> Option<&Segment<'s>> {
        self.segments().iter().find(|s| s.spec.id() == id)
    }
    fn segment_mut(&mut self, id: &str) -> Option<&mut Segment<'s>> {
        self.segments_mut().iter_mut().find(|s| s.spec.id() == id)
    }
    type ValuesStorage<T>: AsMut<[T]> + AsRef<[T]>;
    fn values_storage<T, F: FnMut(usize) -> T>(&self, f: F) -> Self::ValuesStorage<T>;
}

impl<'s, const N: usize> IKeFormatStorage<'s> for [Segment<'s>; N] {
    type PartialConstruct = ([core::mem::MaybeUninit<Segment<'s>>; N], u16);
    type ConstructionError = Error;
    fn new_constructor(
    ) -> IterativeConstructor<Self, Self::PartialConstruct, Self::ConstructionError> {
        if N > u16::MAX as usize {
            IterativeConstructor::Error(
                zerror!(
                    "[Segments; {N}] unsupported because {N} is too big (max: {}).",
                    u16::MAX
                )
                .into(),
            )
        } else {
            IterativeConstructor::Partial(([core::mem::MaybeUninit::uninit(); N], 0))
        }
    }
    fn add_segment(
        constructor: IterativeConstructor<Self, Self::PartialConstruct, Self::ConstructionError>,
        segment: Segment<'s>,
    ) -> IterativeConstructor<Self, Self::PartialConstruct, Self::ConstructionError> {
        match constructor {
            IterativeConstructor::Complete(_) => IterativeConstructor::Error(
                zerror!("Attempted to add more than {N} segments to [Segment<'s>; {N}]").into(),
            ),
            IterativeConstructor::Partial((mut this, n)) => {
                let mut n = n as usize;
                this[n] = core::mem::MaybeUninit::new(segment);
                n += 1;
                if n == N {
                    IterativeConstructor::Complete(this.map(|e| unsafe { e.assume_init() }))
                } else {
                    IterativeConstructor::Partial((this, n as u16))
                }
            }
            IterativeConstructor::Error(e) => IterativeConstructor::Error(e),
        }
    }

    fn segments(&self) -> &[Segment<'s>] {
        self
    }
    fn segments_mut(&mut self) -> &mut [Segment<'s>] {
        self
    }

    type ValuesStorage<T> = [T; N];
    fn values_storage<T, F: FnMut(usize) -> T>(&self, mut f: F) -> Self::ValuesStorage<T> {
        let mut values = PartialSlice::new();
        for i in 0..N {
            values.push(f(i));
        }
        match values.try_into() {
            Ok(v) => v,
            Err(_) => unreachable!(),
        }
    }
}
struct PartialSlice<T, const N: usize> {
    buffer: [core::mem::MaybeUninit<T>; N],
    n: u16,
}

impl<T, const N: usize> PartialSlice<T, N> {
    fn new() -> Self {
        Self {
            buffer: [(); N].map(|_| core::mem::MaybeUninit::uninit()),
            n: 0,
        }
    }
    fn push(&mut self, value: T) {
        self.buffer[self.n as usize] = core::mem::MaybeUninit::new(value);
        self.n += 1;
    }
}
impl<T, const N: usize> TryFrom<PartialSlice<T, N>> for [T; N] {
    type Error = PartialSlice<T, N>;
    fn try_from(value: PartialSlice<T, N>) -> Result<Self, Self::Error> {
        let buffer = unsafe { core::ptr::read(&value.buffer) };
        if value.n as usize == N {
            core::mem::forget(value);
            Ok(buffer.map(|v| unsafe { v.assume_init() }))
        } else {
            Err(value)
        }
    }
}
impl<T, const N: usize> Drop for PartialSlice<T, N> {
    fn drop(&mut self) {
        for i in 0..self.n as usize {
            unsafe { core::mem::MaybeUninit::assume_init_drop(&mut self.buffer[i]) }
        }
    }
}

impl<'s> IKeFormatStorage<'s> for Vec<Segment<'s>> {
    type PartialConstruct = core::convert::Infallible;
    type ConstructionError = core::convert::Infallible;
    fn new_constructor(
    ) -> IterativeConstructor<Self, Self::PartialConstruct, Self::ConstructionError> {
        IterativeConstructor::Complete(Self::new())
    }
    fn add_segment(
        constructor: IterativeConstructor<Self, Self::PartialConstruct, Self::ConstructionError>,
        segment: Segment<'s>,
    ) -> IterativeConstructor<Self, Self::PartialConstruct, Self::ConstructionError> {
        let IterativeConstructor::Complete(mut this) = constructor else {
            unsafe { core::hint::unreachable_unchecked() }
        };
        this.push(segment);
        IterativeConstructor::Complete(this)
    }

    fn segments(&self) -> &[Segment<'s>] {
        self
    }
    fn segments_mut(&mut self) -> &mut [Segment<'s>] {
        self
    }

    type ValuesStorage<T> = Box<[T]>;
    fn values_storage<T, F: FnMut(usize) -> T>(&self, mut f: F) -> Self::ValuesStorage<T> {
        let mut ans = Vec::with_capacity(self.len());
        for i in 0..self.len() {
            ans.push(f(i))
        }
        ans.into()
    }
}

pub(crate) fn trim_prefix_slash(target: &str) -> &str {
    &target[matches!(target.as_bytes().first(), Some(b'/')) as usize..]
}
pub(crate) fn trim_suffix_slash(target: &str) -> &str {
    &target[..(target.len() - matches!(target.as_bytes().last(), Some(b'/')) as usize)]
}