1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
use std::{collections::HashSet, fmt};

use fj_math::Scalar;

use crate::objects::GlobalVertex;

pub fn validate_vertex(
    vertex: &GlobalVertex,
    vertices: &HashSet<GlobalVertex>,
    min_distance: Scalar,
) -> Result<(), UniquenessIssues> {
    for existing in vertices {
        if (existing.position() - vertex.position()).magnitude() < min_distance
        {
            return Err(UniquenessIssues {
                duplicate_vertex: Some(*existing),
            });
        }
    }

    Ok(())
}

/// Uniqueness issues found during validation
///
/// Used by [`ValidationError`].
///
/// # Implementation Note
///
/// This struct doesn't carry any actual information, currently. Information
/// about the specific uniqueness issues found can be added as required. For
/// now, this struct exists to ease the error handling code.
///
/// [`ValidationError`]: super::ValidationError
#[derive(Debug, Default, thiserror::Error)]
pub struct UniquenessIssues {
    /// Duplicate vertex found
    pub duplicate_vertex: Option<GlobalVertex>,
}

impl fmt::Display for UniquenessIssues {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "Uniqueness issues found:")?;

        if let Some(duplicate_vertex) = &self.duplicate_vertex {
            writeln!(f, "- Duplicate vertex ({:?}", duplicate_vertex)?;
        }

        Ok(())
    }
}