databoard 0.4.0

Provides a hierarchical key-value-store
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
// Copyright © 2025 Stephan Kunz
//! A thread safe hierarchical name/value store.
#![allow(unused)]

#[cfg(feature = "std")]
extern crate std;

use core::str::FromStr;

use alloc::string::String;

use dataport::{
	AnyPortValue, BindCommons, BoundValueReadGuard, BoundValueWriteGuard, PortCollection, PortCollectionAccessors,
	PortCollectionAccessorsCommon, PortCollectionMut, PortCollectionProviderMut, PortList, PortMap, PortVariant,
};

use crate::{Arc, ConstString, Error, RemappingList, RemappingTarget, RwLock, check_local_key, check_top_level_key};

/// A hierarchical, thread safe name/value store.
/// The name is something that can be converted into an `Arc<str>`.
/// The value can be anything that implements the traits `Any` and `Debug`.
///
/// `Databoard` has internal mutability.
#[derive(Clone, Default)]
#[repr(transparent)]
pub struct Databoard(Arc<RwLock<DataboardInner>>);

/// Terminal arm of a key resolution — the operation must fail with this error.
enum ShortCircuit {
	/// The remapping is a string assignment, not a valid lookup target.
	Assignment { name: ConstString, value: ConstString },
	/// The remapping points to a parent that does not exist.
	NoParent { name: ConstString, remapped: ConstString },
}

impl From<ShortCircuit> for Error {
	fn from(sc: ShortCircuit) -> Self {
		match sc {
			ShortCircuit::Assignment { name, value } => Self::Assignment { name, value },
			ShortCircuit::NoParent { name, remapped } => Self::NoParent { name, remapped },
		}
	}
}

impl From<ShortCircuit> for dataport::Error {
	fn from(sc: ShortCircuit) -> Self {
		Error::from(sc).into()
	}
}

/// Describes how a read-only key-operation should be dispatched.
enum Resolve {
	/// Delegate to another databoard (root or parent) with the given name.
	Redirect(Databoard, ConstString),
	/// Resolve against the local database with the given name.
	Local(ConstString),
	/// The key resolves to a terminal error.
	ShortCircuit(ShortCircuit),
}

/// Describes how a write-mode key-operation should be dispatched.
///
/// The `Local` variant carries a held write guard, so the caller performs the
/// mutation inside the same lock scope used for the remapping lookup.
enum ResolveMut<'a> {
	/// Delegate to another databoard (root or parent) with the given name.
	Redirect(Databoard, ConstString),
	/// Resolve against the local database; the guard is already acquired.
	Local(ConstString, crate::RwLockWriteGuard<'a, DataboardInner>),
	/// The key resolves to a terminal error.
	ShortCircuit(ShortCircuit),
}

impl Databoard {
	pub fn insert(&mut self, name: ConstString, port: PortVariant) -> Result<(), dataport::Error> {
		match self.resolve_mut(&name, false) {
			ResolveMut::Redirect(mut board, resolved) => board.insert(resolved, port),
			ResolveMut::Local(resolved, mut guard) => guard.insert(resolved, port),
			ResolveMut::ShortCircuit(sc) => Err(sc.into()),
		}
	}

	pub fn remove(&mut self, name: &str) -> Result<PortVariant, dataport::Error> {
		match self.resolve_mut(name, false) {
			ResolveMut::Redirect(mut board, resolved) => board.remove(&resolved),
			ResolveMut::Local(resolved, mut guard) => PortCollectionMut::delete(&mut guard.database, &resolved),
			ResolveMut::ShortCircuit(sc) => Err(sc.into()),
		}
	}

	/// Creates a [`Databoard`] with given parameters.
	#[must_use]
	pub fn with(parent: Option<Self>, remappings: Option<RemappingList>, autoremap: bool) -> Self {
		Self(Arc::new(RwLock::new(DataboardInner {
			database: PortMap::default(),
			parent,
			remappings: remappings.unwrap_or_default(),
			autoremap,
		})))
	}

	/// Creates a [`Databoard`] using the given parent.
	/// The parents entries are automatically remapped into the new databoard.
	#[must_use]
	pub fn with_parent(parent: Self) -> Self {
		Self(Arc::new(RwLock::new(DataboardInner {
			database: PortMap::default(),
			parent: Some(parent),
			remappings: RemappingList::default(),
			autoremap: true,
		})))
	}
	/// Prints the content of the [`Databoard`] for debugging purpose.
	#[cfg(feature = "std")]
	pub fn debug_message(&self) {
		let _ = self.0.read().parent;
		std::println!("not yet implemented");
	}

	/// Returns a reference to the root [`Databoard`] of the hierarchy.
	fn root(&self) -> Self {
		let mut current = self.clone();
		loop {
			let next = current.0.read().parent.clone();
			match next {
				Some(parent) => current = parent,
				None => return current,
			}
		}
	}

	/// Resolves `name` into a [`Resolve`] directive describing how to dispatch the operation.
	///
	/// When `strict_root` is true, a `RootPointer` remapping without a parent yields
	/// [`ShortCircuit::NoParent`] instead of falling back to the local database — required by
	/// `give_to_bound` and `use_from_bound`.
	fn resolve(&self, name: &str, strict_root: bool) -> Resolve {
		if let Ok(stripped) = check_top_level_key(name) {
			return Resolve::Redirect(self.root(), stripped.into());
		}
		if let Ok(local) = check_local_key(name) {
			return Resolve::Local(local.into());
		}

		let (target, parent, autoremap) = {
			let guard = self.0.read();
			(guard.remappings.find(name), guard.parent.clone(), guard.autoremap)
		};

		match target {
			RemappingTarget::BoardPointer(remapped) => match parent {
				Some(p) => Resolve::Redirect(p, remapped),
				None => Resolve::ShortCircuit(ShortCircuit::NoParent {
					name: name.into(),
					remapped,
				}),
			},
			RemappingTarget::LocalPointer(remapped) => Resolve::Local(remapped),
			RemappingTarget::RootPointer(remapped) => {
				if parent.is_some() {
					Resolve::Redirect(self.root(), remapped)
				} else if strict_root {
					Resolve::ShortCircuit(ShortCircuit::NoParent {
						name: name.into(),
						remapped,
					})
				} else {
					Resolve::Local(remapped)
				}
			}
			RemappingTarget::StringAssignment(value) => Resolve::ShortCircuit(ShortCircuit::Assignment {
				name: name.into(),
				value,
			}),
			RemappingTarget::None(original) => {
				if autoremap && let Some(parent) = parent {
					Resolve::Redirect(parent, original)
				} else {
					Resolve::Local(original)
				}
			}
		}
	}

	/// Write-lock-holding variant of [`Self::resolve`].
	///
	/// Acquires a write lock for the remapping lookup and — when the operation resolves locally —
	/// hands the same guard back to the caller so the mutation runs inside one lock scope.
	/// For `Redirect` and `ShortCircuit` outcomes the guard is released before returning.
	fn resolve_mut(&self, name: &str, strict_root: bool) -> ResolveMut<'_> {
		if let Ok(stripped) = check_top_level_key(name) {
			return ResolveMut::Redirect(self.root(), stripped.into());
		}
		if let Ok(local) = check_local_key(name) {
			return ResolveMut::Local(local.into(), self.0.write());
		}

		let guard = self.0.write();
		let target = guard.remappings.find(name);
		match target {
			RemappingTarget::BoardPointer(remapped) => {
				let parent = guard.parent.clone();
				drop(guard);
				match parent {
					Some(p) => ResolveMut::Redirect(p, remapped),
					None => ResolveMut::ShortCircuit(ShortCircuit::NoParent {
						name: name.into(),
						remapped,
					}),
				}
			}
			RemappingTarget::LocalPointer(remapped) => ResolveMut::Local(remapped, guard),
			RemappingTarget::RootPointer(remapped) => {
				if guard.parent.is_some() {
					drop(guard);
					ResolveMut::Redirect(self.root(), remapped)
				} else if strict_root {
					ResolveMut::ShortCircuit(ShortCircuit::NoParent {
						name: name.into(),
						remapped,
					})
				} else {
					ResolveMut::Local(remapped, guard)
				}
			}
			RemappingTarget::StringAssignment(value) => ResolveMut::ShortCircuit(ShortCircuit::Assignment {
				name: name.into(),
				value,
			}),
			RemappingTarget::None(original) => {
				if guard.autoremap
					&& let Some(parent) = guard.parent.clone()
				{
					drop(guard);
					ResolveMut::Redirect(parent, original)
				} else {
					ResolveMut::Local(original, guard)
				}
			}
		}
	}

	/// Add a list of remappings to the databoard.
	/// # Errors
	/// - [`Error::AlreadyRemapped`] if a name is already remapped.
	pub fn add_remappings(&mut self, remappings: RemappingList) -> Result<(), Error> {
		let mut guard = self.0.write();
		let list = &mut *guard;
		let mut remappings = remappings.into_inner();
		while let Some(entry) = remappings.pop() {
			list.remappings.add_target(entry)?;
		}
		Ok(())
	}

	/// Returns a clone of the remappings, if there are any, otherwise `None`.
	#[must_use]
	pub fn remappings(&self) -> RemappingList {
		self.0.read().remappings.clone()
	}

	/// Returns a clone of the [`PortVariant`] stored under `name`.
	/// # Errors
	/// - [`Error::Assignment`] if the remapping contains an assignment of a `str` value.
	/// - [`Error::NoParent`]   if `name` is remapped to a parent without having a parent.
	/// - [`Error::NotFound`]   if `name` is not contained.
	pub fn entry(&self, name: &str) -> Result<PortVariant, Error> {
		match self.resolve(name, false) {
			Resolve::Redirect(board, resolved) => board.entry(&resolved),
			Resolve::Local(resolved) => self
				.0
				.read()
				.database
				.find(&resolved)
				.map_or_else(|| Err(Error::NotFound { name: name.into() }), |p| Ok(p.clone())),
			Resolve::ShortCircuit(sc) => Err(sc.into()),
		}
	}

	/// Returns either a clone/copy of the T or if content is .
	/// Therefore T must implement [`Clone`] and [`FromStr`].
	/// # Errors
	/// - [`Error::ConversionFromStr`], if content of 'name' cannot be converted from `str` to T
	/// - [`Error::DataType`], if 'name' has not the expected type of T
	/// - [`Error::NotFound`], if 'name' is not in port collection.
	/// - [`Error::NoValue`], if 'name' has no value set.
	pub fn get_from_str<T: AnyPortValue + FromStr + Clone>(&self, key: &str) -> Result<T, Error> {
		match self.get(key) {
			Ok(res) => Ok(res),
			Err(err) => match err {
				dataport::Error::ReturnTypeMismatch { port, value } => {
					// try to convert from str
					T::from_str(&value).map_or_else(|_| Err(Error::ConversionFromStr { value, port }), |val| Ok(val))
				}
				dataport::Error::NotFound { name } => Err(Error::NotFound { name }),
				dataport::Error::NoValueSet => Err(Error::NoValue { name: key.into() }),
				// this is unreachable
				// dataport::Error::IsLocked => Err(Error::IsLocked { name: key.into() }),
				dataport::Error::DataType => Err(Error::DataType { name: key.into() }),
				// this shoul never be reached
				_ => Err(Error::Unreachable("get_from_str".into(), line!())),
			},
		}
	}

	/// Sets the port 'key' with a value parsed from the string `s`.
	///
	/// The port must have been created with a `_parseable` constructor
	/// (e.g. [`Self::create_outbound_parseable`]) so that the `FromStr`
	/// capability was captured at creation time.
	/// # Errors
	/// - [`Error::FromStr`], if parsing or the setter was not registered.
	/// - [`Error::PortType`], if the port variant does not support writing.
	pub fn set_from_str(&mut self, name: &str, value: &str) -> Result<(), dataport::Error> {
		match self.resolve_mut(name, false) {
			ResolveMut::Redirect(mut board, resolved) => board.set_from_str(&resolved, value),
			ResolveMut::Local(resolved, mut guard) => {
				if guard.database.contains_name(&resolved) {
					guard.database.set_from_str(&resolved, value)
				} else {
					guard
						.database
						.add(resolved, PortVariant::create_inoutbound(String::from(value)))
				}
			}
			ResolveMut::ShortCircuit(sc) => Err(sc.into()),
		}
	}

	/// Sets the autoremapping flag to the desired value.
	pub fn set_autoremap(&mut self, autoremap: bool) {
		self.0.write().autoremap = autoremap;
	}

	/// Create a port using the corresponding port from the [`PortList`].
	/// # Errors
	pub fn create_from_collection(
		&mut self,
		name: ConstString,
		portlist: &dyn PortList,
		portlist_name: &str,
	) -> Result<(), dataport::Error> {
		portlist.find(portlist_name).map_or_else(
			|| {
				Err(dataport::Error::NotFound {
					name: portlist_name.into(),
				})
			},
			|variant| self.insert(name, variant.clone()),
		)
	}

	/// Create a port using the corresponding port from the [`PortList`].
	/// # Errors
	pub fn create_from_variant(&mut self, name: ConstString, variant: &PortVariant) -> Result<(), dataport::Error> {
		self.insert(name, variant.clone())
	}

	/// Adds a remapping to the blackboard.
	/// # Errors
	/// - [`Error::CreateRemapping`] if creation of the [`RemappingTarget`](crate::RemappingTarget) is not possible
	#[allow(clippy::option_if_let_else)]
	pub fn add_remapping(&mut self, key: &str, target: &str) -> Result<(), Error> {
		// handle target '{=}'
		let target = target.replace('=', key);
		let new_target = RemappingTarget::from_str(&target)?;
		let old_target = self.0.read().remappings.find(key);
		match old_target {
			RemappingTarget::None(_) => self
				.0
				.write()
				.remappings
				.add_target((key.into(), new_target)),
			_ => {
				if old_target == new_target {
					Err(Error::AlreadyExists { name: key.into() })
				} else {
					Err(Error::AlreadyRemapped {
						name: key.into(),
						remapped: target.into(),
					})
				}
			}
		}
	}

	/// Reverse search
	#[must_use]
	pub fn find_origin(&self, name: &str) -> Option<Arc<str>> {
		self.remappings().find_origin(name)
	}

	/// Provides shared access to the local [`PortCollection`] within a closure.
	///
	/// Since the underlying storage is behind an [`RwLock`](crate::RwLock),
	/// a direct `&dyn PortCollection` cannot be returned.
	/// This method acquires a read lock and passes the inner [`PortMap`] to the closure.
	pub fn with_collection<F, R>(&self, f: F) -> R
	where
		F: FnOnce(&PortMap) -> R,
	{
		let guard = self.0.read();
		f(&guard.database)
	}

	/// Provides exclusive access to the local [`PortCollection`] within a closure.
	///
	/// Since the underlying storage is behind an [`RwLock`](crate::RwLock),
	/// a direct `&mut dyn PortCollection` cannot be returned.
	/// This method acquires a write lock and passes the inner [`PortMap`] to the closure.
	pub fn with_collection_mut<F, R>(&self, f: F) -> R
	where
		F: FnOnce(&mut PortMap) -> R,
	{
		let mut guard = self.0.write();
		f(&mut guard.database)
	}
}

impl core::fmt::Debug for Databoard {
	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
		let inner = self.0.read();
		write!(f, "Databoard {{ ")?;
		write!(f, "autoremap: {:?}", &inner.autoremap)?;
		write!(f, ", {:?}", &inner.database)?;
		write!(f, ", {:?}", &inner.remappings)?;
		write!(f, ", parent: ")?;
		if let Some(parent) = &inner.parent {
			write!(f, "{parent:?}",)
		} else {
			write!(f, "None")
		}?;
		write!(f, " }}")
	}
}

impl PortCollectionAccessorsCommon for Databoard {
	fn contains_name(&self, key: &str) -> bool {
		match self.resolve(key, false) {
			Resolve::Redirect(board, resolved) => board.contains_name(&resolved),
			Resolve::Local(resolved) => self.0.read().database.contains_name(&resolved),
			Resolve::ShortCircuit(_) => false,
		}
	}

	fn give_to_bound(&self, name: &str, bound: &mut dyn BindCommons) -> Result<(), dataport::Error> {
		match self.resolve_mut(name, true) {
			ResolveMut::Redirect(board, resolved) => board.give_to_bound(&resolved, bound),
			ResolveMut::Local(resolved, guard) => guard.database.give_to_bound(&resolved, bound),
			ResolveMut::ShortCircuit(sc) => Err(sc.into()),
		}
	}

	fn give_to_collection(
		&self,
		name: &str,
		other_collection: &mut dyn PortCollection,
		other_name: &str,
	) -> Result<(), dataport::Error> {
		other_collection.find_mut(other_name).map_or_else(
			|| Err(dataport::Error::OtherNotFound { name: other_name.into() }),
			|other| self.give_to_variant(name, other),
		)
	}

	fn give_to_variant(&self, name: &str, variant: &mut PortVariant) -> Result<(), dataport::Error> {
		match variant {
			PortVariant::InBound(bound) => self.give_to_bound(name, bound),
			PortVariant::InOutBound(bound) => self.give_to_bound(name, bound),
			PortVariant::OutBound(bound) => self.give_to_bound(name, bound),
		}
	}

	fn sequence_number(&self, name: &str) -> Result<u32, dataport::Error> {
		match self.resolve(name, false) {
			Resolve::Redirect(board, resolved) => board.sequence_number(&resolved),
			Resolve::Local(resolved) => self.0.read().database.sequence_number(&resolved),
			Resolve::ShortCircuit(sc) => Err(sc.into()),
		}
	}

	fn use_from_bound(&mut self, name: &str, bound: &dyn BindCommons) -> Result<(), dataport::Error> {
		match self.resolve_mut(name, true) {
			ResolveMut::Redirect(mut board, resolved) => board.use_from_bound(&resolved, bound),
			ResolveMut::Local(resolved, mut guard) => guard.database.use_from_bound(&resolved, bound),
			ResolveMut::ShortCircuit(sc) => Err(sc.into()),
		}
	}

	fn use_from_collection(
		&mut self,
		name: &str,
		other_collection: &dyn PortCollection,
		other_name: &str,
	) -> Result<(), dataport::Error> {
		other_collection.find(other_name).map_or_else(
			|| Err(dataport::Error::OtherNotFound { name: other_name.into() }),
			|other| self.use_from_variant(name, other),
		)
	}

	fn use_from_variant(&mut self, name: &str, variant: &PortVariant) -> Result<(), dataport::Error> {
		match variant {
			PortVariant::InBound(bound) => self.use_from_bound(name, bound),
			PortVariant::InOutBound(bound) => self.use_from_bound(name, bound),
			PortVariant::OutBound(bound) => self.use_from_bound(name, bound),
		}
	}
}

impl PortCollectionAccessors for Databoard {
	fn contains<T: AnyPortValue>(&self, key: &str) -> Result<bool, dataport::Error> {
		match self.resolve(key, false) {
			Resolve::Redirect(board, resolved) => board.contains::<T>(&resolved),
			Resolve::Local(resolved) => self.0.read().database.contains::<T>(&resolved),
			Resolve::ShortCircuit(sc) => Err(sc.into()),
		}
	}

	fn get<T: AnyPortValue + Clone>(&self, key: &str) -> Result<T, dataport::Error> {
		match self.resolve(key, false) {
			Resolve::Redirect(board, resolved) => board.get::<T>(&resolved),
			Resolve::Local(resolved) => self.0.read().database.get::<T>(&resolved),
			Resolve::ShortCircuit(sc) => Err(sc.into()),
		}
	}

	fn read<T: AnyPortValue>(&self, key: &str) -> Result<BoundValueReadGuard<T>, dataport::Error> {
		match self.resolve(key, false) {
			Resolve::Redirect(board, resolved) => board.read(&resolved),
			Resolve::Local(resolved) => self.0.read().database.read(&resolved),
			Resolve::ShortCircuit(sc) => Err(sc.into()),
		}
	}

	fn try_read<T: AnyPortValue>(&self, key: &str) -> Result<BoundValueReadGuard<T>, dataport::Error> {
		match self.resolve(key, false) {
			Resolve::Redirect(board, resolved) => board.try_read(&resolved),
			Resolve::Local(resolved) => self.0.read().database.try_read(&resolved),
			Resolve::ShortCircuit(sc) => Err(sc.into()),
		}
	}

	fn replace<T: AnyPortValue>(&mut self, name: &str, value: T) -> Result<Option<T>, dataport::Error> {
		match self.resolve_mut(name, false) {
			ResolveMut::Redirect(mut board, resolved) => board.replace::<T>(&resolved, value),
			ResolveMut::Local(resolved, mut guard) => guard.database.replace::<T>(&resolved, value),
			ResolveMut::ShortCircuit(sc) => Err(sc.into()),
		}
	}

	fn take<T: AnyPortValue>(&mut self, name: &str) -> Result<Option<T>, dataport::Error> {
		match self.resolve_mut(name, false) {
			ResolveMut::Redirect(mut board, resolved) => board.take::<T>(&resolved),
			ResolveMut::Local(resolved, mut guard) => PortCollectionAccessors::take::<T>(&mut guard.database, &resolved),
			ResolveMut::ShortCircuit(sc) => Err(sc.into()),
		}
	}

	fn set<T: AnyPortValue>(&mut self, name: &str, value: T) -> Result<(), dataport::Error> {
		match self.resolve_mut(name, false) {
			ResolveMut::Redirect(mut board, resolved) => board.set::<T>(&resolved, value),
			ResolveMut::Local(resolved, mut guard) => {
				if guard.database.contains_name(&resolved) {
					guard.database.set::<T>(&resolved, value)
				} else {
					guard
						.database
						.add(resolved, PortVariant::create_inoutbound(value))
				}
			}
			ResolveMut::ShortCircuit(sc) => Err(sc.into()),
		}
	}

	fn write<T: AnyPortValue>(&mut self, name: &str) -> Result<BoundValueWriteGuard<T>, dataport::Error> {
		match self.resolve_mut(name, false) {
			ResolveMut::Redirect(mut board, resolved) => board.write::<T>(&resolved),
			ResolveMut::Local(resolved, mut guard) => guard.database.write(&resolved),
			ResolveMut::ShortCircuit(sc) => Err(sc.into()),
		}
	}

	fn try_write<T: AnyPortValue>(&mut self, name: &str) -> Result<BoundValueWriteGuard<T>, dataport::Error> {
		match self.resolve_mut(name, false) {
			ResolveMut::Redirect(mut board, resolved) => board.try_write::<T>(&resolved),
			ResolveMut::Local(resolved, mut guard) => guard.database.try_write(&resolved),
			ResolveMut::ShortCircuit(sc) => Err(sc.into()),
		}
	}
}

/// Internal data for a hierarchical databoard.
#[derive(Default)]
struct DataboardInner {
	/// Database of this `Databoard`.
	/// It is behind an `RwLock` to protect against data races.
	database: PortMap,
	/// An optional reference to a parent `Databoard`.
	parent: Option<Databoard>,
	/// Manual remapping rules from this `Databoard` to the parent.
	remappings: RemappingList,
	/// Whether to use automatic remapping to parents content.
	autoremap: bool,
}

impl DataboardInner {
	fn insert(&mut self, name: ConstString, port: PortVariant) -> Result<(), dataport::Error> {
		// insertion into databoard always needs read- and writeable ports
		// so we need to convert all other ports
		let io_port = port.to_in_out();
		// self.database.insert(name, io_port)
		PortMap::add(&mut self.database, name, io_port)
	}
}

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

	// check, that the auto traits are available
	const fn is_normal<T: Sized + Send + Sync>() {}

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

	// Read-only `resolve` with `strict_root = true` has no public caller.
	#[test]
	fn resolve_root_pointer_strict_no_parent() {
		let mut remappings = RemappingList::default();
		remappings.push(("alias".into(), RemappingTarget::RootPointer("rkey".into())));
		let db = Databoard::with(None, Some(remappings), false);

		// strict_root=true  → ShortCircuit::NoParent  (the path under test)
		// strict_root=false → Resolve::Local          (else-arm, covers the if-let's else branch)
		// Iterating both results through a single `if let` means both arms execute,
		// eliminating the zero-count sub-region that `assert!(matches!(…))` would leave.
		let results = [
			db.resolve("alias", true),
			db.resolve("alias", false),
		];
		let mut got_no_parent = false;
		for result in results {
			if let Resolve::ShortCircuit(ShortCircuit::NoParent { .. }) = result {
				got_no_parent = true;
			}
		}
		assert!(got_no_parent);
	}
}