dataport 0.1.0

Port abstractions for data types
Documentation
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
// Copyright © 2026 Stephan Kunz
//! Module implementing various port collections.

use core::fmt::Debug;

use alloc::boxed::Box;

use crate::{
	ConstString,
	any_port_value::AnyPortValue,
	bind::{
		BindCommons,
		bound_value::{BoundValueReadGuard, BoundValueWriteGuard},
	},
	error::Error,
	port_variant::PortVariant,
};

pub mod port_array;
pub mod port_map;
pub mod port_vec;

use crate::collections::port_array::PortArray;

/// A thread-safe wrapper for `PortArray<0>` that allows shared `&mut` access.
///
/// This is safe because `PortArray<0>` is a zero-sized empty array: all mutable
/// operations on it are no-ops (returning `NotFound` errors), so no actual
/// mutation ever occurs.
pub struct EmptyPortArray(core::cell::UnsafeCell<PortArray<0>>);

/// SAFETY: `PortArray<0>` is zero-sized with no state — `&mut` access through
/// `UnsafeCell` cannot cause data races since there is nothing to race on.
#[allow(unsafe_code)]
unsafe impl Sync for EmptyPortArray {}

impl EmptyPortArray {
	const fn new() -> Self {
		Self(core::cell::UnsafeCell::new(PortArray([])))
	}

	pub fn get(&self) -> &PortArray<0> {
		// SAFETY: No mutation occurs on a zero-element array.
		#[allow(unsafe_code)]
		unsafe {
			&*self.0.get()
		}
	}

	#[allow(clippy::mut_from_ref)]
	pub fn get_mut(&self) -> &mut PortArray<0> {
		// SAFETY: `PortArray<0>` is zero-sized and all mutable operations
		// return errors without modifying any state.
		#[allow(unsafe_code)]
		unsafe {
			&mut *self.0.get()
		}
	}
}

/// An empty port array to provide a port collection for items without ports which use the traits.
/// Using a single instance reduces memory footprint.
pub static EMPTY_PORT_ARRAY: EmptyPortArray = EmptyPortArray::new();

/// Object safe combination of PortCollection & PortCollectionAccessorsCommon
pub trait PortList: PortCollection + PortCollectionAccessorsCommon {}

/// Blanket implementation
impl<T: PortCollection + PortCollectionAccessorsCommon> PortList for T {}

/// Methods for something that is a collection of ports.
/// Each port is identified by its name, so the name has to be unique within a certain port collection.
pub trait PortCollection: Debug {
	/// Returns the port with 'name' from the collection.
	fn find(&self, name: &str) -> Option<&PortVariant>;

	/// Returns the mutable port with 'name' from the collection.
	fn find_mut(&mut self, name: &str) -> Option<&mut PortVariant>;

	/// Sets a new value created from str to the T.
	/// # Errors
	/// - [`Error::DataType`], if 'name' has not the expected type of T.
	/// - [`Error::PortType`], if 'name' is not the expected port type.
	fn set_from_str(&mut self, name: &str, value: &str) -> Result<(), Error>;

	/// Returns a boxed iterator yielding `(name, port)` pairs for every entry in the collection.
	fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (&'a str, &'a PortVariant)> + 'a>;

	/// Returns a boxed iterator yielding `(name, &mut port)` pairs for every entry in the collection.
	fn iter_mut<'a>(&'a mut self) -> Box<dyn Iterator<Item = (&'a str, &'a mut PortVariant)> + 'a>;
}

/// Methods for something that is a mutable collection of ports.
/// Each port is identified by its name, so the name has to be unique within a certain port collection.
pub trait PortCollectionMut: PortCollection {
	/// Adds a [`PortVariant`] with `name` to the collection
	fn add(&mut self, name: ConstString, port: PortVariant) -> Result<(), Error>;

	/// Removes the [`PortVariant`] with `name` from the collection and returns it.
	/// # Errors
	/// - [`Error::NotFound`] if `name` is not contained.
	fn delete(&mut self, name: &str) -> Result<PortVariant, Error>;
}

/// Common access methods for port collections.
/// Each port is identified by its name, so the name has to be unique within a certain port collection.
pub trait PortCollectionAccessorsCommon {
	/// Returns true if 'name' is in the port collection, otherwise false.
	fn contains_name(&self, name: &str) -> bool;

	/// Connects a port from this collection to the value of another port variant.
	/// Type of connection depends on types of both ports.
	/// # Errors
	/// - [`Error::NotFound`], if 'name' is not in collection.
	/// - [`Error::DataType`], if 'name' has not the same type of T as 'bound'.
	/// - [`Error::PortType`], if 'name' and 'bound' have incompatible port types.
	fn give_to_bound(&self, name: &str, bound: &mut dyn BindCommons) -> Result<(), Error>;

	/// Connects a port from this collection to a port from another collection.
	/// Type of connection depends on types of both ports.
	/// # Errors
	/// - [`Error::NotFound`], if 'name' is not in 'self' collection.
	/// - [`Error::OtherNotFound`], if 'name' is not in 'other' collection.
	/// - [`Error::DataType`], if 'name' has not the same type of T as 'other_name'.
	/// - [`Error::PortType`], if 'name' and 'other_name' have incompatible port types.
	fn give_to_collection(
		&self,
		name: &str,
		other_collection: &mut dyn PortCollection,
		other_name: &str,
	) -> Result<(), Error>;

	/// Connects a port from this collection to the value of another port variant.
	/// Type of connection depends on types of both ports.
	/// # Errors
	/// - [`Error::NotFound`], if 'name' is not in collection.
	/// - [`Error::DataType`], if 'name' has not the same type of T as 'variant'.
	/// - [`Error::PortType`], if 'name' and 'variant' have incompatible port types.
	fn give_to_variant(&self, name: &str, variant: &mut PortVariant) -> Result<(), Error>;

	/// Returns the change sequence number,
	/// a number which
	/// - starts at `0`,
	/// - can only be incremeted by 1 and
	/// - wraps around to `1` when exceeding its limits.
	/// # Errors
	/// - [`Error::NotFound`], if 'name' is not in port collection.
	fn sequence_number(&self, name: &str) -> Result<u32, Error>;

	/// Connects a port from this collection to the value of another port variant.
	/// Type of connection depends on types of both ports.
	/// # Errors
	/// - [`Error::NotFound`], if 'name' is not in collection.
	/// - [`Error::DataType`], if 'name' has not the same type of T as 'bound'.
	/// - [`Error::PortType`], if 'name' and 'bound' have incompatible port types.
	fn use_from_bound(&mut self, name: &str, bound: &dyn BindCommons) -> Result<(), Error>;

	/// Connects a port from this collection to a port from another collection.
	/// Type of connection depends on types of both ports.
	/// # Errors
	/// - [`Error::NotFound`], if 'name' is not in 'self' collection.
	/// - [`Error::OtherNotFound`], if 'name' is not in 'other' collection.
	/// - [`Error::DataType`], if 'name' has not the same type of T as 'other_name'.
	/// - [`Error::PortType`], if 'name' and 'other_name' have incompatible port types.
	fn use_from_collection(
		&mut self,
		name: &str,
		other_collection: &dyn PortCollection,
		other_name: &str,
	) -> Result<(), Error>;

	/// Connects a port from this collection to the value of another port variant.
	/// Type of connection depends on types of both ports.
	/// # Errors
	/// - [`Error::NotFound`], if 'name' is not in collection.
	/// - [`Error::DataType`], if 'name' has not the same type of T as 'variant'.
	/// - [`Error::PortType`], if 'name' and 'variant' have incompatible port types.
	fn use_from_variant(&mut self, name: &str, variant: &PortVariant) -> Result<(), Error>;
}

/// Access methods for port collections.
/// Each port is identified by its name, so the name has to be unique within a certain port collection.
pub trait PortCollectionAccessors: PortCollectionAccessorsCommon {
	/// Returns a result of `true` if a certain `key` of type `T` is available, otherwise a result of `false`.
	/// # Errors
	/// - [`Error::NotFound`], if 'name' is not in port collection.
	/// - [`Error::DataType`], if the 'name' exists, but has not the expected type `T`.
	fn contains<T: AnyPortValue>(&self, name: &str) -> Result<bool, Error>;

	/// Returns a clone/copy of the T.
	/// Therefore T must implement [`Clone`].
	/// # Errors
	/// - [`Error::NotFound`], if 'name' is not in port collection.
	/// - [`Error::DataType`], if 'name' has not the expected type of T.
	/// - [`Error::PortType`], if 'name' is not the expected port type.
	/// - [`Error::NoValueSet`], if 'name' has no value set.
	fn get<T>(&self, name: &str) -> Result<T, Error>
	where
		T: AnyPortValue + Clone;

	/// Returns an immutable guard to the ports value T.
	/// # Errors
	/// - [`Error::NotFound`], if 'name' is not in port collection.
	/// - [`Error::DataType`], if 'name' has not the expected type of T.
	/// - [`Error::PortType`], if 'name' is not the expected port type.
	fn read<T: AnyPortValue>(&self, name: &str) -> Result<BoundValueReadGuard<T>, Error>;

	/// Returns an immutable guard to the ports value T.
	/// # Errors
	/// - [`Error::IsLocked`], if 'name' is locked.
	/// - [`Error::NotFound`], if 'name' is not in port collection.
	/// - [`Error::DataType`], if 'name' has not the expected type of T.
	/// - [`Error::PortType`], if 'name' is not the expected port type.
	fn try_read<T: AnyPortValue>(&self, name: &str) -> Result<BoundValueReadGuard<T>, Error>;

	/// Sets a new value to the T and returns the old T.
	/// # Errors
	/// - [`Error::NotFound`], if 'name' is not in port collection.
	/// - [`Error::DataType`], if 'name' has not the expected type of T.
	/// - [`Error::PortType`], if 'name' is not the expected port type.
	fn replace<T: AnyPortValue>(&mut self, name: &str, value: T) -> Result<Option<T>, Error>;

	/// Sets a new value to the T.
	/// # Errors
	/// - [`Error::DataType`], if 'name' has not the expected type of T.
	/// - [`Error::PortType`], if 'name' is not the expected port type.
	fn set<T: AnyPortValue>(&mut self, name: &str, value: T) -> Result<(), Error>;

	/// Returns the T, removing it from the port.
	/// # Errors
	/// - [`Error::NotFound`], if 'name' is not in port collection.
	/// - [`Error::DataType`], if 'name' has not the expected type of T.
	/// - [`Error::PortType`], if 'name' is not the expected port type.
	fn take<T: AnyPortValue>(&mut self, name: &str) -> Result<Option<T>, Error>;

	/// Returns a mutable guard to the ports value T.
	/// # Errors
	/// - [`Error::NotFound`], if 'name' is not in port collection.
	/// - [`Error::DataType`], if 'name' has not the expected type of T.
	/// - [`Error::PortType`], if 'name' is not the expected port type.
	fn write<T: AnyPortValue>(&mut self, name: &str) -> Result<BoundValueWriteGuard<T>, Error>;

	/// Returns a mutable guard to the ports value T.
	/// # Errors
	/// - [`Error::IsLocked`], if 'name' is locked.
	/// - [`Error::NotFound`], if 'name' is not in port collection.
	/// - [`Error::DataType`], if 'name' has not the expected type of T.
	/// - [`Error::PortType`], if 'name' is not the expected port type.
	fn try_write<T: AnyPortValue>(&mut self, name: &str) -> Result<BoundValueWriteGuard<T>, Error>;
}

/// Trait for something that provides a collection of Ports.
pub trait PortCollectionProvider {
	/// Returns immutable access to the collections entries.
	fn provided_ports(&self) -> &impl PortCollectionAccessors {
		EMPTY_PORT_ARRAY.get()
	}

	/// Returns mutable access to the collections entries.
	fn provided_ports_mut(&mut self) -> &mut impl PortCollectionAccessors {
		EMPTY_PORT_ARRAY.get_mut()
	}

	/// Returns an immutable [`PortCollection`].
	fn port_collection(&self) -> &impl PortCollection {
		EMPTY_PORT_ARRAY.get()
	}
}

/// Trait for something that provides a mutable collection of Ports.
pub trait PortCollectionProviderMut: PortCollectionProvider {
	/// Returns a mutable [`PortCollection`].
	fn port_collection_mut(&mut self) -> &mut impl PortCollectionMut;
}

#[cfg(test)]
mod tests {
	use super::*;

	const fn is_normal<T: Sized + Send + Sync>() {}

	#[test]
	const fn normal_types() {
		is_normal::<&EmptyPortArray>();
		is_normal::<EmptyPortArray>();
	}

	#[test]
	fn get_returns_empty_array() {
		let array = EMPTY_PORT_ARRAY.get();
		assert!(array.is_empty());
		assert!(array.find("any").is_none());
	}

	#[test]
	fn get_mut_returns_empty_array() {
		let array = EMPTY_PORT_ARRAY.get_mut();
		assert!(array.is_empty());
		assert!(array.find_mut("any").is_none());
	}

	#[test]
	fn get_mut_set_from_str_returns_not_found() {
		let array = EMPTY_PORT_ARRAY.get_mut();
		assert_eq!(array.set_from_str("any", "42"), Err(Error::NotFound { name: "any".into() }));
	}

	#[test]
	fn get_contains_name_returns_false() {
		let array = EMPTY_PORT_ARRAY.get();
		assert!(!array.contains_name("any"));
	}

	#[test]
	fn get_sequence_number_returns_not_found() {
		let array = EMPTY_PORT_ARRAY.get();
		assert_eq!(array.sequence_number("any"), Err(Error::NotFound { name: "any".into() }));
	}

	#[test]
	fn get_read_returns_error() {
		let array = EMPTY_PORT_ARRAY.get();
		assert!(array.read::<i32>("any").is_err());
	}

	#[test]
	fn get_mut_write_returns_error() {
		let array = EMPTY_PORT_ARRAY.get_mut();
		assert!(array.write::<i32>("any").is_err());
	}

	#[test]
	fn get_mut_set_returns_not_found() {
		let array = EMPTY_PORT_ARRAY.get_mut();
		assert_eq!(array.set::<i32>("any", 42), Err(Error::NotFound { name: "any".into() }));
	}

	#[test]
	fn new_creates_empty_array() {
		let empty = EmptyPortArray::new();
		let array = empty.get();
		assert!(array.is_empty());
	}

	#[test]
	fn get_try_read_returns_error() {
		let array = EMPTY_PORT_ARRAY.get();
		assert!(array.try_read::<i32>("any").is_err());
	}

	#[test]
	fn get_mut_try_write_returns_error() {
		let array = EMPTY_PORT_ARRAY.get_mut();
		assert!(array.try_write::<i32>("any").is_err());
	}

	#[test]
	fn get_contains_returns_ok_false() {
		let array = EMPTY_PORT_ARRAY.get();
		assert_eq!(array.contains::<i32>("any"), Ok(false));
	}

	#[test]
	fn get_get_returns_not_found() {
		let array = EMPTY_PORT_ARRAY.get();
		assert_eq!(array.get::<i32>("any"), Err(Error::NotFound { name: "any".into() }));
	}

	#[test]
	fn get_mut_replace_returns_not_found() {
		let array = EMPTY_PORT_ARRAY.get_mut();
		assert_eq!(array.replace::<i32>("any", 42), Err(Error::NotFound { name: "any".into() }));
	}

	#[test]
	fn get_mut_take_returns_not_found() {
		let array = EMPTY_PORT_ARRAY.get_mut();
		assert_eq!(array.take::<i32>("any"), Err(Error::NotFound { name: "any".into() }));
	}

	#[test]
	fn get_give_to_variant_returns_not_found() {
		let array = EMPTY_PORT_ARRAY.get();
		let mut variant = PortVariant::create_inbound(0i32);
		assert_eq!(
			array.give_to_variant("any", &mut variant),
			Err(Error::NotFound { name: "any".into() })
		);
	}

	#[test]
	fn get_give_to_bound_returns_not_found() {
		use crate::bind::in_::InBound;
		let array = EMPTY_PORT_ARRAY.get();
		let mut port = InBound::with_value(42i32);
		assert_eq!(
			array.give_to_bound("any", &mut port),
			Err(Error::NotFound { name: "any".into() })
		);
	}

	#[test]
	fn get_give_to_collection_returns_not_found() {
		let array = EMPTY_PORT_ARRAY.get();
		let mut other = crate::collections::port_array::PortArray::<0>::empty();
		assert_eq!(
			array.give_to_collection("any", &mut other, "other"),
			Err(Error::NotFound { name: "any".into() })
		);
	}

	#[test]
	fn get_mut_use_from_variant_returns_not_found() {
		let array = EMPTY_PORT_ARRAY.get_mut();
		let variant = PortVariant::create_inbound(0i32);
		assert_eq!(
			array.use_from_variant("any", &variant),
			Err(Error::NotFound { name: "any".into() })
		);
	}

	#[test]
	fn get_mut_use_from_bound_returns_not_found() {
		use crate::bind::in_::InBound;
		let array = EMPTY_PORT_ARRAY.get_mut();
		let port = InBound::with_value(42i32);
		assert_eq!(
			array.use_from_bound("any", &port),
			Err(Error::NotFound { name: "any".into() })
		);
	}

	#[test]
	fn get_mut_use_from_collection_returns_not_found() {
		let array = EMPTY_PORT_ARRAY.get_mut();
		let other = crate::collections::port_array::PortArray::<0>::empty();
		assert_eq!(
			array.use_from_collection("any", &other, "other"),
			Err(Error::NotFound { name: "any".into() })
		);
	}
}