| 1 | //! This module provides a mechanism for creating and managing composite keys |
| 2 | //! used in anchor lookups. It allows for efficient lookups without the need |
| 3 | //! to construct data structures with owned values. |
| 4 | //! |
| 5 | //! The key components are: |
| 6 | //! - `AnchorKey`: An owned version of the composite key. |
| 7 | //! - `AnchorKeyRef`: A borrowed version of the composite key. |
| 8 | //! - `BorrowDyn`: A trait that allows for dynamic borrowing of key components. |
| 9 | //! |
| 10 | //! This design enables the use of borrowed data in hash map lookups while |
| 11 | //! still storing owned data. |
| 12 | use std::{ |
| 13 | borrow::Borrow, |
| 14 | hash::{Hash, Hasher}, |
| 15 | sync::Arc, |
| 16 | }; |
| 17 | |
| 18 | use fluent_uri::Uri; |
| 19 | |
| 20 | use super::AnchorName; |
| 21 | |
| 22 | #[derive(Debug, Clone, Hash, PartialEq, Eq)] |
| 23 | pub(crate) struct AnchorKey { |
| 24 | uri: Arc<Uri<String>>, |
| 25 | name: AnchorName, |
| 26 | } |
| 27 | |
| 28 | impl AnchorKey { |
| 29 | pub(crate) fn new(uri: Arc<Uri<String>>, name: AnchorName) -> Self { |
| 30 | Self { uri, name } |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | #[derive(Copy, Clone, Hash, PartialEq, Eq)] |
| 35 | pub(crate) struct AnchorKeyRef<'a> { |
| 36 | uri: &'a Uri<String>, |
| 37 | name: &'a str, |
| 38 | } |
| 39 | |
| 40 | impl<'a> AnchorKeyRef<'a> { |
| 41 | pub(crate) fn new(uri: &'a Uri<String>, name: &'a str) -> Self { |
| 42 | AnchorKeyRef { uri, name } |
| 43 | } |
| 44 | |
| 45 | pub(crate) fn borrow_dyn(&self) -> &dyn BorrowDyn { |
| 46 | self as &dyn BorrowDyn |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | pub(crate) trait BorrowDyn { |
| 51 | fn borrowed_key(&self) -> AnchorKeyRef<'_>; |
| 52 | } |
| 53 | |
| 54 | impl BorrowDyn for AnchorKey { |
| 55 | fn borrowed_key(&self) -> AnchorKeyRef<'_> { |
| 56 | AnchorKeyRef::new(&self.uri, self.name.as_str()) |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | impl BorrowDyn for AnchorKeyRef<'_> { |
| 61 | fn borrowed_key(&self) -> AnchorKeyRef<'_> { |
| 62 | *self |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | impl<'a> Borrow<dyn BorrowDyn + 'a> for AnchorKey { |
| 67 | fn borrow(&self) -> &(dyn BorrowDyn + 'a) { |
| 68 | self |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | impl Eq for dyn BorrowDyn + '_ {} |
| 73 | |
| 74 | impl PartialEq for dyn BorrowDyn + '_ { |
| 75 | fn eq(&self, other: &dyn BorrowDyn) -> bool { |
| 76 | self.borrowed_key().eq(&other.borrowed_key()) |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | impl Hash for dyn BorrowDyn + '_ { |
| 81 | fn hash<H: Hasher>(&self, state: &mut H) { |
| 82 | self.borrowed_key().hash(state); |
| 83 | } |
| 84 | } |