gapirs-common 0.0.1

Common library for gapirs
Documentation
use std::collections::HashMap;

pub trait SortTupleIteratorBySortKeys<Key, SortKey, VALUE>
where
    Key: PartialEq<SortKey>,
{
    type Out;
    fn sort_by_other(self, other: &[SortKey]) -> Self::Out;
}

impl<Key, SortKey, T> SortTupleIteratorBySortKeys<Key, SortKey, T> for Vec<(Key, T)>
where
    Key: PartialEq<SortKey>,
{
    type Out = Vec<(Key, T)>;
    fn sort_by_other(mut self, other: &[SortKey]) -> Self::Out {
        let mut sorted = Vec::new();
        for sort_key in other {
            //check if the key is in the list
            if let Some(index) = self.iter().position(|(k, _)| k == sort_key) {
                //move the value to the sorted list
                let v = self.remove(index);
                sorted.push(v);
            }
        }
        //add the remaining values to the end
        sorted.extend(self);
        sorted
    }
}

impl<Key, SortKey, T, const S: usize> SortTupleIteratorBySortKeys<Key, SortKey, T> for [(Key, T); S]
where
    Key: PartialEq<SortKey>,
{
    type Out = [(Key, T); S];
    fn sort_by_other(mut self, other: &[SortKey]) -> Self::Out {
        for (i, sort_key) in other.iter().enumerate() {
            if let Some(index) = self.iter().position(|(k, _)| k == sort_key) {
                self.swap(i, index);
            }
        }
        self
    }
}