Skip to main content

hypergraph_rs/geometry/
positions.rs

1//! Positions by id, and the result of a placement.
2
3use indexmap::IndexMap;
4
5use super::Point;
6
7/// Positions keyed by id, in insertion order.
8///
9/// The derived `PartialEq` compares the inner map, which ignores order. Compare `iter()` listings to compare order.
10#[derive(Clone, Debug, Default, PartialEq)]
11pub struct Positions {
12    map: IndexMap<String, Point>,
13}
14
15impl Positions {
16    /// An empty set of positions.
17    #[must_use]
18    pub fn new() -> Self {
19        Self::default()
20    }
21
22    /// Sets the position of `id`. A repeated id keeps its first place in the order; the old point is returned.
23    pub fn insert(&mut self, id: impl Into<String>, at: Point) -> Option<Point> {
24        self.map.insert(id.into(), at)
25    }
26
27    /// The position of `id`, if it has one.
28    #[must_use]
29    pub fn get(&self, id: &str) -> Option<Point> {
30        self.map.get(id).copied()
31    }
32
33    /// How many ids have a position.
34    #[must_use]
35    pub fn len(&self) -> usize {
36        self.map.len()
37    }
38
39    /// Whether no id has a position.
40    #[must_use]
41    pub fn is_empty(&self) -> bool {
42        self.map.is_empty()
43    }
44
45    /// Every `(id, position)`, in insertion order.
46    pub fn iter(&self) -> impl Iterator<Item = (&str, Point)> + '_ {
47        self.map.iter().map(|(id, at)| (id.as_str(), *at))
48    }
49
50    /// The point at `index` in insertion order. Panics when out of range.
51    pub(crate) fn point_mut(&mut self, index: usize) -> &mut Point {
52        self.map
53            .get_index_mut(index)
54            .expect("index in range of positions")
55            .1
56    }
57
58    /// The id at `index` in insertion order. Panics when out of range.
59    pub(crate) fn id_at(&self, index: usize) -> &str {
60        self.map
61            .get_index(index)
62            .expect("index in range of positions")
63            .0
64            .as_str()
65    }
66}
67
68impl FromIterator<(String, Point)> for Positions {
69    fn from_iter<I: IntoIterator<Item = (String, Point)>>(iter: I) -> Self {
70        Self {
71            map: iter.into_iter().collect(),
72        }
73    }
74}
75
76/// The result of placing items.
77#[derive(Clone, Debug, Default, PartialEq)]
78pub struct Placement {
79    /// Placed items, in input order.
80    pub positions: Positions,
81    /// Items with no positive weight, in input order. They are never put at the origin.
82    pub unplaced: Vec<String>,
83}