sodg/
next.rs

1// Copyright (c) 2022-2023 Yegor Bugayenko
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included
11// in all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21use crate::Sodg;
22
23impl Sodg {
24    /// Get next unique ID of a vertex.
25    ///
26    /// This ID will never be returned by [`next_id()`] again. Also, this ID will not
27    /// be equal to any of the existing IDs of vertices.
28    pub fn next_id(&mut self) -> u32 {
29        let mut id = self.next_v;
30        for v in self.vertices.keys() {
31            if *v >= id {
32                id = *v + 1;
33            }
34        }
35        self.next_v = id + 1;
36        id
37    }
38}
39
40#[cfg(test)]
41use anyhow::Result;
42
43#[test]
44fn simple_next_id() -> Result<()> {
45    let mut g = Sodg::empty();
46    assert_eq!(0, g.next_id());
47    assert_eq!(1, g.next_id());
48    Ok(())
49}
50
51#[test]
52fn calculates_next_id() -> Result<()> {
53    let mut g = Sodg::empty();
54    g.add(0)?;
55    g.add(42)?;
56    assert_eq!(43, g.next_id());
57    assert_eq!(44, g.next_id());
58    Ok(())
59}