1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
use std::cmp;
use std::hash::{Hash};
use std::collections::{HashMap};

use serde::{Serialize};
use std::convert::TryInto;
use crate::index::{HashableIndex};


pub struct JoinEngine<'a, TIndex: Serialize + Hash + Clone + cmp::Eq + cmp::Ord> {
    pub idx_this : &'a HashableIndex<TIndex>,
    pub idx_other : &'a HashableIndex<TIndex>
}

pub struct IndexJoinPair{
    pub this_idx: usize,
    pub other_idx: usize 
}

pub struct IndexJoinPotentiallyUnmatchedPair{
    pub this_idx: usize,
    pub other_idx: Option<usize> 
}

pub fn prior_func(idx: usize) -> usize{
    if idx == 0 { 
        0 
    } else{
        idx-1
    }
}
pub fn fwd_func(idx: usize, otherlen: usize) -> usize{
    if idx >= otherlen-1 { 
        otherlen-1 
    } else {
        idx+1
    }
}


impl <'a, TIndex: Serialize + Hash + Clone + cmp::Eq + cmp::Ord> JoinEngine<'a, TIndex>{

    #[cfg(feature = "hash_precompare")]
    fn hash_index(&self, index: &HashableIndex<TIndex>) -> u64{ 
        let bytes = bincode::serialize(&index.values).unwrap();
        seahash::hash(&bytes)
    }

    #[cfg(feature = "hash_precompare")]
    fn hash_precompare(&self) -> bool{
        if self.idx_this.len() == self.idx_other.len(){
            self.hash_index(self.idx_this) == self.hash_index(self.idx_other)
        } else{
            false
        }
    }
    fn index_is_same(&self) -> bool{ #![allow(unused_assignments)] #![allow(unused_mut)] #![allow(clippy::let_and_return)]
        let mut out = false; 
        #[cfg(feature = "hash_precompare")]{
            out = self.hash_precompare();
        }               
        out
    }

    fn gen_base_lookup(&self,hashbase: &HashableIndex<TIndex>) -> HashMap<TIndex, usize>
    {
        let mut lookup: HashMap<TIndex, usize> = HashMap::with_capacity(hashbase.len());    //reserve to avoid reallocate
        hashbase.iter().enumerate().for_each(|(idx, key)| {
            lookup.insert(key.clone(), idx);
        });
        lookup
    }
    
    /// Hash inner join
    pub fn get_inner_hash_joined_indicies(&self) -> Vec<IndexJoinPair>
    {
        if self.index_is_same() {
            //if we are the same just skip this whole thing
            self.idx_this.iter().enumerate().map(|(idx,_x)| IndexJoinPair{this_idx : idx,other_idx : idx}).collect()
        }
        else {
            let (lookup, this_shorter) = match self.idx_this.len() <= self.idx_this.len() { 
                true => (self.gen_base_lookup(&self.idx_this),false),
                false => (self.gen_base_lookup(&self.idx_other),true)
            };
    
            if this_shorter {
                let res: Vec<IndexJoinPair> = self.idx_this.iter().enumerate().map(|(idx_this, key)| {
                    if let Some(idx_other) = lookup.get(&key) {                    
                        Some(IndexJoinPair { 
                            this_idx : idx_this, 
                            other_idx : *idx_other
                        })
                    }
                    else{
                        None
                    }
                })
                .filter(|x| x.is_some())
                .map(|x| x.unwrap())
                .collect();
    
                res
            } else {
                let res = self.idx_other.iter().enumerate().map(|(idx_other, key)| {
                    if let Some(idx_this) = lookup.get(&key) {                    
                        Some(IndexJoinPair { 
                            this_idx : *idx_this, 
                            other_idx : idx_other
                        })
                    }
                    else{
                        None
                    }
                })
                .filter(|x| x.is_some())
                .map(|x| x.unwrap())
                .collect();
    
                res
            }
        }

    }
    
    /// Hash join left. 
    /// All left values are joined so no Option<usize> on the base index
    pub fn get_left_hash_joined_indicies(&self) -> Vec<IndexJoinPotentiallyUnmatchedPair>
    {
        if self.index_is_same() {
            //if we are the same just skip this whole thing
            self.idx_this.iter().enumerate().map(|(idx,_x)| IndexJoinPotentiallyUnmatchedPair{this_idx : idx,other_idx : Some(idx)}).collect()
        }
        else{
            let lookup = self.gen_base_lookup(&self.idx_other);
    
            let res: Vec<IndexJoinPotentiallyUnmatchedPair> = self.idx_this.iter().enumerate().map(|(idx_this, key)| {
                if let Some(idx_other) = lookup.get(&key) {                    
                    IndexJoinPotentiallyUnmatchedPair { 
                        this_idx : idx_this, 
                        other_idx : Some(*idx_other)
                    }
                }
                else{
                    IndexJoinPotentiallyUnmatchedPair { 
                        this_idx : idx_this, 
                        other_idx : None
                    }
                }
            })
            .collect();
            res
        }
    }

    pub fn get_left_merge_joined_indicies(&self) -> Vec<IndexJoinPotentiallyUnmatchedPair>
    {
        if self.index_is_same() {
            //if we are the same just skip this whole thing
            self.idx_this.iter().enumerate().map(|(idx,_x)| IndexJoinPotentiallyUnmatchedPair{this_idx : idx,other_idx : Some(idx)}).collect()
        }
        else{
            let mut output: Vec<IndexJoinPotentiallyUnmatchedPair> = Vec::new();
            let mut pos1: usize = 0;
            let mut pos2: usize = 0;

            while pos1 < self.idx_this.len() {
                match self.idx_this[pos1].cmp(&self.idx_other[pos2]) {
                    cmp::Ordering::Greater => {
                        output.push(IndexJoinPotentiallyUnmatchedPair{
                            this_idx: pos1,
                            other_idx: None
                        });
                        if pos2 < (self.idx_other.len() - 1){
                            pos2 += 1;
                        }
                        else{
                            pos1 += 1;     //the first index might still be longer so we gotta keep rolling it forward even though we are out of space on the other index                       
                        }

                    },
                    cmp::Ordering::Less => {
                        output.push(IndexJoinPotentiallyUnmatchedPair{
                            this_idx: pos1,
                            other_idx: None
                        });
                        pos1 += 1;
                    },
                    cmp::Ordering::Equal => {
                        output.push(IndexJoinPotentiallyUnmatchedPair{
                            this_idx: pos1,
                            other_idx: Some(pos2)
                        });
                        pos1 += 1;
                        if pos2 < (self.idx_other.len() - 1){
                            pos2 += 1;
                        }
                        
                    }
                }
            }
            output
        }
    }

    /// merge sort joirn join a and b.
    pub fn get_inner_merge_joined_indicies(&self) -> Vec<IndexJoinPair>
    {
        if self.index_is_same() {
            //if we are the same just skip this whole thing
            self.idx_this.iter().enumerate().map(|(idx,_x)| IndexJoinPair{this_idx : idx,other_idx : idx}).collect()
        }
        else {
            let mut output: Vec<IndexJoinPair> = Vec::new();
            let mut pos1: usize = 0;
            let mut pos2: usize = 0;

            while pos1 < self.idx_this.len() && pos2 < self.idx_other.len() {
                match self.idx_this[pos1].cmp(&self.idx_other[pos2]) {
                    cmp::Ordering::Greater => {
                        pos2 += 1;
                    },
                    cmp::Ordering::Less => {
                        pos1 += 1;
                    },
                    cmp::Ordering::Equal => {
                        output.push(IndexJoinPair{
                            this_idx: pos1,
                            other_idx: pos2
                        });
                        pos1 += 1;
                        pos2 += 1;
                    }
                }
            }
            output
        }
    }
    
    /// merge sort joirn join a and b.
    pub fn get_asof_merge_joined_indicies(&self, compare_func: Option<Box<dyn Fn(&TIndex,&TIndex,&TIndex)->(cmp::Ordering,i64)>>,other_idx_func: Option<Box<dyn Fn(usize)->usize>>) -> Vec<IndexJoinPotentiallyUnmatchedPair>
    { #![allow(clippy::type_complexity)]
        if self.index_is_same() {
            //if we are the same just skip this whole thing
            self.idx_this.iter().enumerate().map(|(idx,_x)| IndexJoinPotentiallyUnmatchedPair{this_idx : idx,other_idx : Some(idx)}).collect()
        }
        else {
            let mut output: Vec<IndexJoinPotentiallyUnmatchedPair> = Vec::new();
            let mut pos1: usize = 0;
            let mut pos2: usize = 0;

            let comp_func = match compare_func{
                Some(func)=> func,
                None => Box::new(|this:&TIndex, other:&TIndex, _other_prior:&TIndex| (this.cmp(&other),0)) // use built in ordinal compare if no override
            };
            
            let cand_idx_func = match other_idx_func{
                Some(func) =>func,
                None => Box::new(|idx| idx)
            };

            while pos1 < self.idx_this.len() {
                let comp_res = comp_func(&self.idx_this[pos1],&self.idx_other[pos2],&self.idx_other[cand_idx_func(pos2)]);
                let offset = comp_res.1;
                match comp_res.0 { 
                    // (Evaluated as,  but is actually)
                    cmp::Ordering::Greater => {
                        output.push(IndexJoinPotentiallyUnmatchedPair{
                            this_idx: pos1,
                            other_idx: None
                        });
                        if pos2 < (self.idx_other.len() -  1){
                            pos1 += 1; //the first index might still be longer so we gotta keep rolling it forward even though we are out of space on the other index
                        }

                    },
                    cmp::Ordering::Less => {
                        output.push(IndexJoinPotentiallyUnmatchedPair{
                            this_idx: pos1,
                            other_idx: None
                        });
                        pos1 += 1;
                    },
                    cmp::Ordering::Equal => {
                        let pas64:i64 = pos2.try_into().unwrap();
                        let idx0:i64 =  pas64 + offset;
                        output.push(IndexJoinPotentiallyUnmatchedPair{
                            this_idx: pos1,
                            other_idx: Some(idx0.try_into().unwrap())
                        });
                        if self.idx_this[pos1].eq(&self.idx_other[pos2]) && pos2 < (self.idx_other.len() - 1) { // only incr if things are actually equal and you have room to run
                            pos2 += 1;
                        }
                        pos1 += 1;
                    }
                }
            }
            output
        }
    } 
    

}