Give things unique ID types, not aliases, to prevent mixups

This commit is contained in:
James Wilson
2021-06-30 16:59:03 +01:00
parent 06bd660599
commit 4308359feb
14 changed files with 308 additions and 394 deletions
+21 -34
View File
@@ -1,65 +1,52 @@
use std::{fmt::Display, hash::Hash};
use serde::{Serialize,Deserialize};
use std::hash::Hash;
use bimap::BiMap;
#[derive(Clone,Copy,Debug,Hash,PartialEq,Eq,Serialize,Deserialize)]
pub struct Id(usize);
impl std::convert::From<Id> for usize {
fn from(id: Id) -> usize {
id.0
}
}
impl std::convert::From<usize> for Id {
fn from(n: usize) -> Id {
Id(n)
}
}
impl Display for Id {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
/// A struct that allows you to assign an ID to an arbitrary set of
/// details (so long as they are Eq+Hash+Clone), and then access
/// the assigned ID given those details or access the details given
/// the ID.
#[derive(Debug)]
pub struct AssignId<Details> {
current_id: Id,
mapping: BiMap<Id, Details>
pub struct AssignId<Id, Details> {
current_id: usize,
mapping: BiMap<usize, Details>,
_id_type: std::marker::PhantomData<Id>
}
impl <Details> AssignId<Details> where Details: Eq + Hash {
impl <Id, Details> AssignId<Id, Details>
where
Details: Eq + Hash,
Id: From<usize> + Copy,
usize: From<Id>
{
pub fn new() -> Self {
Self {
current_id: Id(0),
mapping: BiMap::new()
current_id: 0,
mapping: BiMap::new(),
_id_type: std::marker::PhantomData
}
}
pub fn assign_id(&mut self, details: Details) -> Id {
let this_id = self.current_id;
self.current_id.0 += 1;
self.current_id += 1;
self.mapping.insert(this_id, details);
this_id
this_id.into()
}
pub fn get_details(&mut self, id: Id) -> Option<&Details> {
self.mapping.get_by_left(&id)
self.mapping.get_by_left(&id.into())
}
pub fn get_id(&mut self, details: &Details) -> Option<Id> {
self.mapping.get_by_right(details).map(|id| *id)
self.mapping.get_by_right(details).map(|&id| id.into())
}
pub fn remove_by_id(&mut self, id: Id) -> Option<Details> {
self.mapping.remove_by_left(&id).map(|(_,details)| details)
self.mapping.remove_by_left(&id.into()).map(|(_,details)| details)
}
pub fn remove_by_details(&mut self, details: &Details) -> Option<Id> {
self.mapping.remove_by_right(&details).map(|(id,_)| id)
self.mapping.remove_by_right(&details).map(|(id,_)| id.into())
}
pub fn clear(&mut self) {
@@ -67,6 +54,6 @@ impl <Details> AssignId<Details> where Details: Eq + Hash {
}
pub fn iter(&self) -> impl Iterator<Item = (Id, &Details)> {
self.mapping.iter().map(|(id, details)| (*id, details))
self.mapping.iter().map(|(&id, details)| (id.into(), details))
}
}