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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
use std::{
convert::TryFrom,
fmt::{self, Debug, Display, Formatter},
str::FromStr,
};
use anyhow::anyhow;
use derive_more::Display;
use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};
use crate::{
scalar::nonempty_string,
scalars::{NodeId, StreamId},
tags::TagSet,
};
#[derive(Debug, Display, PartialEq)]
pub enum ParseError {
#[display(fmt = "SourceId was longer than maximum")]
SourceIdTooLong,
#[display(fmt = "Empty string is not permissible for SourceId")]
EmptySourceId,
#[display(fmt = "Empty string is not permissible for Semantics")]
EmptySemantics,
#[display(fmt = "Empty string is not permissible for FishName")]
EmptyFishName,
}
impl std::error::Error for ParseError {}
#[macro_export]
macro_rules! semantics {
($lit:tt) => {{
#[allow(dead_code)]
type X = $crate::assert_len!($lit, 1..);
use ::std::convert::TryFrom;
$crate::legacy::Semantics::try_from($lit).unwrap()
}};
}
#[macro_export]
macro_rules! fish_name {
($lit:tt) => {{
#[allow(dead_code)]
type X = $crate::assert_len!($lit, 1..);
use ::std::convert::TryFrom;
$crate::legacy::FishName::try_from($lit).unwrap()
}};
}
#[macro_export]
macro_rules! source_id {
($lit:tt) => {{
#[allow(dead_code)]
type X = $crate::assert_len!($lit, 1..=15);
use ::std::convert::TryFrom;
$crate::legacy::SourceId::try_from($lit).unwrap()
}};
}
pub(crate) const MAX_SOURCEID_LENGTH: usize = 15;
mk_scalar!(
struct Semantics, ParseError, crate::legacy::validate_semantics, "crate::scalar::nonempty_string"
);
pub fn validate_semantics(s: &str) -> Result<(), ParseError> {
if s.is_empty() {
return Err(ParseError::EmptySemantics);
}
Ok(())
}
impl Semantics {
pub fn unknown() -> Self {
semantics!("_t_")
}
}
mk_scalar!(
struct FishName, ParseError, crate::legacy::validate_fishname, "crate::scalar::nonempty_string"
);
pub fn validate_fishname(s: &str) -> Result<(), ParseError> {
if s.is_empty() {
return Err(ParseError::EmptySemantics);
}
Ok(())
}
impl FishName {
pub fn unknown() -> Self {
fish_name!("_t_")
}
}
impl TryFrom<&TagSet> for Semantics {
type Error = anyhow::Error;
fn try_from(value: &TagSet) -> Result<Self, Self::Error> {
let sem = value
.iter()
.filter(|t| t.to_string().starts_with("semantics:"))
.filter_map(|t| {
let t = t.to_string();
let pos = t.find(':')?;
Semantics::try_from(&t[pos + 1..]).ok()
})
.collect::<Vec<_>>();
if sem.len() == 1 {
sem.into_iter().next().ok_or_else(|| anyhow!("cannot happen"))
} else {
Err(anyhow!("no unique semantics tag found"))
}
}
}
impl TryFrom<&TagSet> for FishName {
type Error = anyhow::Error;
fn try_from(value: &TagSet) -> Result<Self, Self::Error> {
let names = value
.iter()
.filter(|t| t.to_string().starts_with("fish_name:"))
.filter_map(|t| {
let t = t.to_string();
let pos = t.find(':')?;
FishName::try_from(&t[pos + 1..]).ok()
})
.collect::<Vec<_>>();
if names.len() == 1 {
names.into_iter().next().ok_or_else(|| anyhow!("cannot happen"))
} else {
Err(anyhow!("no unique fish_name tag found"))
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[cfg_attr(feature = "dataflow", derive(Abomonation))]
#[serde(rename_all = "camelCase")]
pub struct StreamInfo {
pub semantics: Semantics,
pub name: FishName,
pub source: SourceId,
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "dataflow", derive(Abomonation))]
pub struct SourceId(pub(crate) [u8; MAX_SOURCEID_LENGTH + 1]);
impl SourceId {
pub fn new(s: String) -> Result<Self, ParseError> {
Self::from_str(s.as_ref())
}
pub fn as_str(&self) -> &str {
let length = self.0[MAX_SOURCEID_LENGTH] as usize;
std::str::from_utf8(&self.0[0..length]).expect("content must be valid utf8 string")
}
pub fn is_wildcard(&self) -> bool {
self.is_empty()
}
pub fn is_empty(&self) -> bool {
self.0[MAX_SOURCEID_LENGTH] as usize == 0
}
}
impl Debug for SourceId {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(f, "SourceId({})", self.as_str())
}
}
impl TryFrom<&str> for SourceId {
type Error = ParseError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::from_str(value)
}
}
impl FromStr for SourceId {
type Err = ParseError;
fn from_str(text: &str) -> Result<SourceId, ParseError> {
let bytes = text.as_bytes();
if bytes.len() > MAX_SOURCEID_LENGTH {
return Result::Err(ParseError::SourceIdTooLong);
}
if bytes.is_empty() {
return Result::Err(ParseError::EmptySourceId);
}
let mut buf = [0; MAX_SOURCEID_LENGTH + 1];
buf[MAX_SOURCEID_LENGTH] = bytes.len() as u8;
buf[..bytes.len()].clone_from_slice(bytes);
Result::Ok(SourceId(buf))
}
}
impl From<SourceId> for StreamId {
fn from(src: SourceId) -> Self {
Self::from(&src)
}
}
impl From<&SourceId> for StreamId {
fn from(src: &SourceId) -> Self {
let mut bytes = [0u8; 32];
bytes[0..=MAX_SOURCEID_LENGTH].copy_from_slice(&src.0[..]);
StreamId {
node_id: NodeId(bytes),
stream_nr: 0.into(),
}
}
}
impl Display for SourceId {
fn fmt(&self, f: &mut Formatter) -> Result<(), std::fmt::Error> {
write!(f, "{}", self.as_str())
}
}
impl<'de> Deserialize<'de> for SourceId {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<SourceId, D::Error> {
nonempty_string(deserializer).and_then(|arc| SourceId::try_from(&*arc).map_err(D::Error::custom))
}
}
impl Serialize for SourceId {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deserialize() {
assert_eq!(
serde_json::from_str::<Semantics>(r#""abc""#).unwrap(),
semantics!("abc")
);
let res = serde_json::from_str::<Semantics>("\"\"").unwrap_err();
assert_eq!(res.to_string(), "expected non-empty string");
}
#[test]
fn deserialize_owned() {
assert_eq!(
serde_json::from_reader::<_, Semantics>(br#""abc""#.as_ref()).unwrap(),
semantics!("abc")
);
let res = serde_json::from_reader::<_, Semantics>(b"\"\"".as_ref()).unwrap_err();
assert_eq!(res.to_string(), "expected non-empty string");
assert_eq!(
serde_json::from_reader::<_, SourceId>(br#""abc""#.as_ref()).unwrap(),
source_id!("abc")
);
let res = serde_json::from_reader::<_, SourceId>(b"\"\"".as_ref()).unwrap_err();
assert_eq!(res.to_string(), "expected non-empty string");
}
#[test]
fn reject_empty_source_id() {
SourceId::from_str("").unwrap_err();
}
}