Skip to main content

task_allocation/
assignment.rs

1//! The outcome of an allocation: one bundle per agent.
2
3use alloc::vec::Vec;
4
5use crate::bundle::Bundle;
6use crate::id::{AgentId, TaskId};
7
8/// Which agent holds which tasks: one [`Bundle`] per agent, indexed by [`AgentId`].
9///
10/// An assignment is *conflict-free* when no task is in two bundles. Every algorithm in this
11/// crate returns conflict-free assignments; consensus algorithms reach one once their agents
12/// agree.
13#[derive(Clone, Debug, Default, PartialEq, Eq)]
14pub struct Assignment {
15    /// The bundle of each agent, indexed by agent.
16    bundles: Vec<Bundle<TaskId>>,
17}
18
19impl Assignment {
20    /// An assignment from one bundle per agent, in agent order.
21    #[must_use]
22    pub const fn from_bundles(bundles: Vec<Bundle<TaskId>>) -> Self {
23        Self { bundles }
24    }
25
26    /// An assignment of `agents` empty bundles.
27    #[must_use]
28    pub fn empty(agents: usize) -> Self {
29        Self::from_bundles((0..agents).map(|_| Bundle::new()).collect())
30    }
31
32    /// The number of agents.
33    #[must_use]
34    pub fn agents(&self) -> usize {
35        self.bundles.len()
36    }
37
38    /// The bundle of `agent`.
39    ///
40    /// # Panics
41    ///
42    /// Panics when `agent` is not part of the assignment.
43    #[must_use]
44    pub fn bundle(&self, agent: AgentId) -> &Bundle<TaskId> {
45        &self.bundles[agent.index()]
46    }
47
48    /// The bundle of `agent`, to change it.
49    ///
50    /// # Panics
51    ///
52    /// Panics when `agent` is not part of the assignment.
53    pub fn bundle_mut(&mut self, agent: AgentId) -> &mut Bundle<TaskId> {
54        &mut self.bundles[agent.index()]
55    }
56
57    /// The bundles, in agent order.
58    #[must_use]
59    pub fn bundles(&self) -> &[Bundle<TaskId>] {
60        &self.bundles
61    }
62
63    /// The agent holding `task`; `None` when no agent holds it. When several do, the one with
64    /// the smallest identifier.
65    #[must_use]
66    pub fn holder(&self, task: TaskId) -> Option<AgentId> {
67        self.bundles
68            .iter()
69            .position(|bundle| bundle.contains(&task))
70            .map(AgentId)
71    }
72
73    /// The total value: the sum of the bundles' values, saturating at [`u64::MAX`].
74    #[must_use]
75    pub fn value(&self) -> u64 {
76        self.bundles
77            .iter()
78            .fold(0, |total, bundle| total.saturating_add(bundle.value()))
79    }
80
81    /// Whether every task is held by at most one agent.
82    #[must_use]
83    pub fn is_conflict_free(&self) -> bool {
84        let mut seen: Vec<TaskId> = self
85            .bundles
86            .iter()
87            .flat_map(Bundle::tasks)
88            .copied()
89            .collect();
90        let held = seen.len();
91        seen.sort_unstable();
92        seen.dedup();
93
94        seen.len() == held
95    }
96}
97
98/// Unit tests for [`Assignment`].
99#[cfg(test)]
100mod tests {
101    use super::Assignment;
102    use crate::id::{AgentId, TaskId};
103    use crate::valuation::Insertion;
104
105    /// Records `task` in the bundle of `agent` with gain `gain`, appended to the path.
106    fn give(assignment: &mut Assignment, agent: usize, task: usize, gain: u64) {
107        let bundle = assignment.bundle_mut(AgentId(agent));
108        let position = bundle.len();
109        bundle.insert(TaskId(task), Insertion { position, gain });
110    }
111
112    /// Holders, values and conflicts follow the bundles.
113    #[test]
114    fn reports_holders_and_value() {
115        let mut assignment = Assignment::empty(2);
116        give(&mut assignment, 0, 1, 4);
117        give(&mut assignment, 1, 0, 3);
118
119        assert_eq!(assignment.agents(), 2);
120        assert_eq!(assignment.bundles().len(), 2);
121        assert_eq!(assignment.holder(TaskId(1)), Some(AgentId(0)));
122        assert_eq!(assignment.holder(TaskId(2)), None);
123        assert_eq!(assignment.value(), 7);
124        assert!(assignment.is_conflict_free());
125
126        give(&mut assignment, 1, 1, 2);
127        assert!(!assignment.is_conflict_free());
128    }
129}