11//! Code for handling IDs
22use anyhow:: { Context , Result } ;
3- use indexmap:: IndexSet ;
3+ use indexmap:: { IndexMap , IndexSet } ;
4+ use std:: borrow:: Borrow ;
45use std:: collections:: HashSet ;
6+ use std:: fmt:: Display ;
7+ use std:: hash:: Hash ;
58
69/// A trait alias for ID types
7- pub trait IDLike :
8- Eq + std:: hash:: Hash + std:: borrow:: Borrow < str > + Clone + std:: fmt:: Display + From < String >
9- {
10- }
11- impl < T > IDLike for T where
12- T : Eq + std:: hash:: Hash + std:: borrow:: Borrow < str > + Clone + std:: fmt:: Display + From < String >
13- {
14- }
10+ pub trait IDLike : Eq + Hash + Borrow < str > + Clone + Display + From < String > { }
11+ impl < T > IDLike for T where T : Eq + Hash + Borrow < str > + Clone + Display + From < String > { }
1512
1613macro_rules! define_id_type {
1714 ( $name: ident) => {
@@ -78,43 +75,25 @@ pub(crate) use define_id_getter;
7875
7976/// A data structure containing a set of IDs
8077pub trait IDCollection < ID : IDLike > {
81- /// Get the ID from the collection by its string representation.
82- ///
83- /// # Arguments
84- ///
85- /// * `id` - The string representation of the ID
86- ///
87- /// # Returns
88- ///
89- /// A copy of the ID in `self`, or an error if not found.
90- fn get_id_by_str ( & self , id : & str ) -> Result < ID > ;
91-
9278 /// Check if the ID is in the collection, returning a copy of it if found.
9379 ///
9480 /// # Arguments
9581 ///
96- /// * `id` - The ID to check
82+ /// * `id` - The ID to check (can be string or ID type)
9783 ///
9884 /// # Returns
9985 ///
10086 /// A copy of the ID in `self`, or an error if not found.
101- fn get_id ( & self , id : & ID ) -> Result < ID > ;
87+ fn get_id < T : Borrow < str > + Display + ? Sized > ( & self , id : & T ) -> Result < & ID > ;
10288}
10389
10490macro_rules! define_id_methods {
10591 ( ) => {
106- fn get_id_by_str( & self , id: & str ) -> Result <ID > {
107- let found = self
108- . get( id)
109- . with_context( || format!( "Unknown ID {id} found" ) ) ?;
110- Ok ( found. clone( ) )
111- }
112-
113- fn get_id( & self , id: & ID ) -> Result <ID > {
92+ fn get_id<T : Borrow <str > + Display + ?Sized >( & self , id: & T ) -> Result <& ID > {
11493 let found = self
11594 . get( id. borrow( ) )
11695 . with_context( || format!( "Unknown ID {id} found" ) ) ?;
117- Ok ( found. clone ( ) )
96+ Ok ( found)
11897 }
11998 } ;
12099}
@@ -126,3 +105,12 @@ impl<ID: IDLike> IDCollection<ID> for HashSet<ID> {
126105impl < ID : IDLike > IDCollection < ID > for IndexSet < ID > {
127106 define_id_methods ! ( ) ;
128107}
108+
109+ impl < ID : IDLike , V > IDCollection < ID > for IndexMap < ID , V > {
110+ fn get_id < T : Borrow < str > + Display + ?Sized > ( & self , id : & T ) -> Result < & ID > {
111+ let ( found, _) = self
112+ . get_key_value ( id. borrow ( ) )
113+ . with_context ( || format ! ( "Unknown ID {id} found" ) ) ?;
114+ Ok ( found)
115+ }
116+ }
0 commit comments