indradb/models/
vertices.rs

1use crate::{util::generate_uuid_v1, Identifier};
2use std::hash::{Hash, Hasher};
3use uuid::Uuid;
4
5/// A vertex.
6///
7/// Vertices are how you would represent nouns in the datastore. An example
8/// might be a user, or a movie. All vertices have a unique ID and a type.
9#[derive(Clone, Debug)]
10pub struct Vertex {
11    /// The id of the vertex.
12    pub id: Uuid,
13
14    /// The type of the vertex.
15    pub t: Identifier,
16}
17
18impl Vertex {
19    /// Creates a new vertex with an ID generated via UUIDv1. These vertex IDs
20    /// are trivially guessable and consequently less secure, but index
21    /// better. This method is suggested unless you need vertex IDs to not be
22    /// trivially guessable.
23    ///
24    /// # Arguments
25    ///
26    /// * `t`: The type of the vertex.
27    pub fn new(t: Identifier) -> Self {
28        Self::with_id(generate_uuid_v1(), t)
29    }
30
31    /// Creates a new vertex with a specified id.
32    ///
33    /// # Arguments
34    ///
35    /// * `id`: The id of the vertex.
36    /// * `t`: The type of the vertex.
37    pub fn with_id(id: Uuid, t: Identifier) -> Self {
38        Vertex { id, t }
39    }
40}
41
42impl PartialEq for Vertex {
43    fn eq(&self, other: &Vertex) -> bool {
44        self.id == other.id
45    }
46}
47
48impl Hash for Vertex {
49    fn hash<H: Hasher>(&self, state: &mut H) {
50        self.id.hash(state);
51    }
52}
53
54impl Eq for Vertex {}
55
56#[cfg(test)]
57mod tests {
58    use super::Vertex;
59    use crate::Identifier;
60    use std::collections::HashSet;
61    use uuid::Uuid;
62
63    #[test]
64    fn should_hash() {
65        assert_eq!(
66            HashSet::from([Vertex::with_id(Uuid::default(), Identifier::new("foo").unwrap())]),
67            HashSet::from([Vertex::with_id(Uuid::default(), Identifier::new("foo").unwrap())])
68        );
69    }
70}