Skip to main content

task_allocation/
id.rs

1//! Dense identifiers for agents and tasks.
2//!
3//! Both are plain indices: agent `AgentId(3)` is the fourth agent of a team and task
4//! `TaskId(0)` the first task of a task set. Algorithms keep per-task and per-agent tables
5//! indexed by them, so identifiers should be small and contiguous, starting at zero.
6
7use core::fmt;
8
9/// Identifies an agent by its index in the team, starting at zero.
10///
11/// The order matters: when two agents bid the same score for a task, the agent with the
12/// smaller identifier wins. Every algorithm in this crate breaks ties this way, so all agents
13/// agree on the winner without exchanging anything else.
14#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
15pub struct AgentId(pub usize);
16
17/// Identifies a task by its index in the task set, starting at zero.
18///
19/// When an agent values two tasks the same, it picks the one with the smaller identifier.
20#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
21pub struct TaskId(pub usize);
22
23impl AgentId {
24    /// The agent's index into per-agent tables.
25    #[must_use]
26    pub const fn index(self) -> usize {
27        self.0
28    }
29}
30
31impl TaskId {
32    /// The task's index into per-task tables.
33    #[must_use]
34    pub const fn index(self) -> usize {
35        self.0
36    }
37}
38
39impl fmt::Display for AgentId {
40    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41        write!(f, "agent {}", self.0)
42    }
43}
44
45impl fmt::Display for TaskId {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        write!(f, "task {}", self.0)
48    }
49}
50
51/// Unit tests for the identifier types.
52#[cfg(test)]
53mod tests {
54    use super::{AgentId, TaskId};
55    use alloc::string::ToString;
56
57    /// Identifiers print with their kind, so log lines stay unambiguous.
58    #[test]
59    fn display_names_the_kind() {
60        assert_eq!(AgentId(2).to_string(), "agent 2");
61        assert_eq!(TaskId(7).to_string(), "task 7");
62    }
63
64    /// Smaller identifiers order first, which is what tie-breaking relies on.
65    #[test]
66    fn order_follows_the_index() {
67        assert!(AgentId(1) < AgentId(2));
68        assert_eq!(TaskId(4).index(), 4);
69    }
70}