Skip to main content

tuwunel_database/map/
id.rs

1use crate::{engine::descriptor::Descriptor, maps::MAPS};
2
3/// Identifies a column by its position in the database catalog.
4///
5/// Construct handles with [`map!`](crate::map!) to check names at compile time.
6/// A handle identifies the same catalog position in every database instance.
7#[derive(Clone, Copy, Debug)]
8pub struct MapId(pub(crate) usize);
9
10/// Resolves a column name into a compile-time catalog handle.
11///
12/// Unknown names fail constant evaluation. Indexing a database still panics if
13/// the catalog entry was dropped or its column family is unavailable.
14#[macro_export]
15macro_rules! map {
16	($name:expr) => {
17		const { $crate::MapId::named($name) }
18	};
19}
20
21impl MapId {
22	/// Finds a column's position in the database catalog.
23	///
24	/// Names are compared byte for byte. An unknown name panics with that name,
25	/// which becomes a build error when evaluated in a constant context.
26	#[must_use]
27	pub const fn named(name: &str) -> Self {
28		let mut index = 0; // Const iteration requires a cursor.
29
30		while index < MAPS.len() {
31			if MAPS[index].name.len() == name.len() && matches(&MAPS[index], name.as_bytes()) {
32				return Self(index);
33			}
34
35			index = index.saturating_add(1);
36		}
37
38		panic!("{}", name);
39	}
40}
41
42const fn matches(desc: &Descriptor, name: &[u8]) -> bool {
43	let mut index = 0; // Const iteration requires a cursor.
44
45	while index < desc.name.len() {
46		if desc.name.as_bytes()[index] != name[index] {
47			return false;
48		}
49
50		index = index.saturating_add(1);
51	}
52
53	true
54}