git_scanner/
git_user_dictionary.rs

1#![warn(clippy::all)]
2use crate::git_logger::User;
3use serde::ser::SerializeSeq;
4use serde::{Serialize, Serializer};
5use std::collections::HashMap;
6
7#[derive(Debug, Clone)]
8pub struct GitUserDictionary {
9    next_id: usize,
10    users: HashMap<User, usize>,
11}
12
13impl GitUserDictionary {
14    pub fn new() -> Self {
15        GitUserDictionary {
16            next_id: 0,
17            users: HashMap::new(),
18        }
19    }
20    pub fn register(&mut self, user: &User) -> usize {
21        match self.users.get(user) {
22            Some(id) => *id,
23            None => {
24                let result = self.next_id;
25                self.users.insert(user.clone(), result);
26                self.next_id += 1;
27                result
28            }
29        }
30    }
31    #[allow(dead_code)]
32    pub fn user_count(&self) -> usize {
33        self.next_id
34    }
35    #[allow(dead_code)]
36    pub fn user_id(&self, user: &User) -> Option<&usize> {
37        self.users.get(user)
38    }
39}
40
41/// We store, rather redundantly, the user ID in the JSON, even though users are output as an array.
42/// This makes it easier for humans to correlate users with data without counting from 0
43/// It also will make it easier later to alias users to other users.
44#[derive(Debug, PartialEq, Serialize)]
45struct UserKey<'a> {
46    id: usize,
47    user: &'a User,
48}
49
50impl Serialize for GitUserDictionary {
51    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
52    where
53        S: Serializer,
54    {
55        let mut reverse_index: HashMap<usize, &User> = HashMap::new();
56        for (user, id) in self.users.iter() {
57            reverse_index.insert(*id, user);
58        }
59        let mut seq = serializer.serialize_seq(Some(self.next_id))?;
60        for id in 0..self.next_id {
61            let user = reverse_index.get(&id).unwrap();
62            seq.serialize_element(&UserKey { id, user })?;
63        }
64        seq.end()
65    }
66}