Skip to main content

solverforge_scoring/stream/
key_extract.rs

1//! KeyExtract trait and adapters for zero-erasure join key extraction.
2//!
3//! The `KeyExtract` trait replaces bare `Fn(&S, &A, usize) -> K` bounds,
4//! allowing named adapter structs to be used as associated types in `JoinTarget`.
5
6/// Extracts a join key from a solution and entity.
7///
8/// Blanket impl for `Fn(&S, &A, usize) -> K` preserves all existing usage.
9/// `EntityKeyAdapter` wraps entity-only key functions for the self-join case.
10pub trait KeyExtract<S, A, K>: Send + Sync {
11    /// Extracts the key from the entity.
12    fn extract(&self, s: &S, a: &A, idx: usize) -> K;
13}
14
15impl<S, A, K, F> KeyExtract<S, A, K> for F
16where
17    F: Fn(&S, &A, usize) -> K + Send + Sync,
18{
19    #[inline]
20    fn extract(&self, s: &S, a: &A, idx: usize) -> K {
21        self(s, a, idx)
22    }
23}
24
25/// Wraps an entity-only key function `Fn(&A) -> K` as a `KeyExtract`.
26///
27/// Used in the self-join case where the user passes `equal(|a: &A| key_fn(a))`.
28/// The solution and index parameters are ignored.
29pub struct EntityKeyAdapter<KA> {
30    key_fn: KA,
31}
32
33impl<KA> EntityKeyAdapter<KA> {
34    /// Creates a new `EntityKeyAdapter` from an entity-only key function.
35    pub fn new(key_fn: KA) -> Self {
36        Self { key_fn }
37    }
38}
39
40impl<S, A, K, KA> KeyExtract<S, A, K> for EntityKeyAdapter<KA>
41where
42    KA: Fn(&A) -> K + Send + Sync,
43{
44    #[inline]
45    fn extract(&self, _s: &S, a: &A, _idx: usize) -> K {
46        (self.key_fn)(a)
47    }
48}
49
50impl<KA: Clone> Clone for EntityKeyAdapter<KA> {
51    fn clone(&self) -> Self {
52        Self {
53            key_fn: self.key_fn.clone(),
54        }
55    }
56}
57
58impl<KA: Copy> Copy for EntityKeyAdapter<KA> {}