TopSet

Struct TopSet 

Source
pub struct TopSet<X, C>
where C: Fn(&X, &X) -> bool,
{ /* private fields */ }
Expand description

A top N set of items.

This set contains no more than N items. When this limit is reached, the smallest (according to the specified comparison) is thrown.

Comparing two elements is done by a duel, resolved by a provided closure: if true is returned, the first item wins, if false the second.

By the way, using PartialOrd::gt will select the top elements and PartialOrd::lt will select the lowest.

Of course, any closure could be used but it should satisfy the transitivity. In other words, if a beats b and b beats c then a should beat c too. If it is not the case, the results are unpredictable.

Implementations§

Source§

impl<X, C> TopSet<X, C>
where C: Fn(&X, &X) -> bool,

Source

pub fn new(n: usize, beat: C) -> Self

Creates a new top set with a selecting closure.

The size corresponds to the maximum number of items allowed in the top set.

The function C is the challenge to decide if an element beats another one and so takes its place. It should corresponds to a total ordering.

If the first one beats the second one then true should be returned and if `false’ corresponds to the case when the second item beats the first one. This function should always returns the same result when dealing with the same items or results are unpredictable.

§Example

Collecting the 5 greatest integers is performed by using a topset with n = 5 and beat = i32::gt.

let mut topset = TopSet::new(5, i32::gt);
Examples found in repository?
examples/lowest_cost.rs (line 5)
3pub fn main()
4{
5    let mut top = TopSet::<f32,_>::new(5, f32::lt);
6    // top.extend(vec![81.5, 4.5, 4., 1., 45., 22., 11.]);
7    //  top.extend(vec![81.5, 4.5, 4., 1., 45., 22., 11.]);
8    vec![81.5, 4.5, 4., 1., 45., 22., 11.,93.].into_iter().for_each(|u| { dbg!(&top); dbg!(&u); dbg!(top.insert(u)); dbg!(&top); });
9    vec![81.5, 4.5, 4., 1., 45., 22., 11.].into_iter().for_each(|u| { dbg!(&top); dbg!(&u); dbg!(top.insert(u));dbg!(&top); });
10    assert_eq![ top.pop(), Some(4.5) ];
11    assert_eq![ top.pop(), Some(4.) ];
12    assert_eq![ top.pop(), Some(4.) ];
13    assert_eq![ top.pop(), Some(1.) ];
14    assert_eq![ top.pop(), Some(1.) ];
15    assert_eq![ top.pop(), None ];
16}
Source

pub fn with_init<I: IntoIterator<Item = X>>(n: usize, beat: C, init: I) -> Self

Creates a new top set with a selecting closure and an initial set of items.

If the initial set contains more than n elements, only the n greatest ones (according to beat challenging function) are stored.

§Example
let mut topset = TopSet::with_init(2, u32::gt, vec![7,5,6,9,4,2,3]);
assert_eq!( topset.pop(), Some(7));
assert_eq!( topset.pop(), Some(9));
assert_eq!( topset.pop(), None);
Source

pub fn is_empty(&self) -> bool

Check if the top set is empty

§Example
let mut topset = TopSet::new(2, u32::gt);
assert!( topset.is_empty() );
topset.extend( vec![7,5,6,9,4,2,3] );
assert!( ! topset.is_empty() );
Source

pub fn len(&self) -> usize

Get the number of stored items.

It never exceeds the predefined capacity (the capacity does not grow by itself, only by calling Self::resize).

§Example
let mut topset = TopSet::with_init(2, u32::gt, vec![7,5,6,9,4,2,3] );
assert_eq!( topset.len(), 2 );
topset.pop();
assert_eq!( topset.len(), 1 );
Source

pub fn capacity(&self) -> usize

Get the capacity of this top set

The capacity limits the number of elements to keep. This capacity could only change by calling [resize].

§Example
let mut topset = TopSet::new(4, u32::gt);
assert_eq!( topset.capacity(), 4 );
assert_eq!( topset.len(), 0 );
Source

pub fn peek(&self) -> Option<&X>

Read access to the lowest item of the top set

Notice that it actually returned the lowest one and so all the others are better (or equal) this one.

To access to this lowest element and removing it, consider Self::pop.

§Example
let mut topset = TopSet::with_init(2, u32::gt, vec![7,5,6,9,4,2,3] );
assert_eq!( topset.peek(), Some(&7) );
assert_eq!( topset.pop(), Some(7) );
assert_eq!( topset.peek(), Some(&9) );
Source

pub fn is_candidate(&self, x: &X) -> bool

Checks if an item will be inserted or not

If it true is returned, it means that a call to Self::insert will actually insert the candidate. If false, then the insertion will be a non-op.

Note that in any case the insertion is not done. See Self::insert to perform the test and the insertion in one time.

§Example
// this topset contains { 7, 9 }
let topset = TopSet::with_init(2, u32::gt, vec![7,5,6,9,4,2,3] );
assert!( topset.is_candidate(&10) );
assert!( topset.is_candidate(&8) );
assert!( ! topset.is_candidate(&7) );
assert!( ! topset.is_candidate(&6) );
Source

pub fn iter(&self) -> impl Iterator<Item = &X>

Iterate over all the top selected items.

The iterator is not sorted. A sorted iteration could be obtained by iterative call to Self::pop or by using Self::into_iter_sorted.

To get a vector with all elements, instead of using this iterator, consider Self::into_vec.

§Example
// this topset contains { 7, 9 }
let topset = TopSet::with_init(2, u32::gt, vec![7,5,6,9,4,2,3] );
let elts = topset.iter().cloned().collect::<Vec<_>>();
Source

pub fn into_vec(self) -> Vec<X>

Gets all the top set elements in a vector.

This vector is not sorted. See Self::into_sorted_vec if a sorted result is expected.

§Example
// this topset contains { 7, 9 }
let topset = TopSet::with_init(2, u32::gt, vec![7,5,6,9,4,2,3] );
let elts = topset.into_vec();
Source

pub fn insert(&mut self, x: X) -> Option<X>

Insert a new item.

If the top set is not filled (i.e. its length is less than its capacity), the item is simply added and None is returned.

If there is no more room, then one item should be rejected:

  • if the new item is better than some already stored ones, it is added and the removed item is returned
  • if the new item is worse than all the stored ones, it is returned
§Example
let mut topset = TopSet::new(2, u32::gt);
assert_eq!( topset.insert(7), None);
assert_eq!( topset.insert(8), None);
assert_eq!( topset.insert(9), Some(7));
assert_eq!( topset.insert(6), Some(6));
Examples found in repository?
examples/lowest_cost.rs (line 8)
3pub fn main()
4{
5    let mut top = TopSet::<f32,_>::new(5, f32::lt);
6    // top.extend(vec![81.5, 4.5, 4., 1., 45., 22., 11.]);
7    //  top.extend(vec![81.5, 4.5, 4., 1., 45., 22., 11.]);
8    vec![81.5, 4.5, 4., 1., 45., 22., 11.,93.].into_iter().for_each(|u| { dbg!(&top); dbg!(&u); dbg!(top.insert(u)); dbg!(&top); });
9    vec![81.5, 4.5, 4., 1., 45., 22., 11.].into_iter().for_each(|u| { dbg!(&top); dbg!(&u); dbg!(top.insert(u));dbg!(&top); });
10    assert_eq![ top.pop(), Some(4.5) ];
11    assert_eq![ top.pop(), Some(4.) ];
12    assert_eq![ top.pop(), Some(4.) ];
13    assert_eq![ top.pop(), Some(1.) ];
14    assert_eq![ top.pop(), Some(1.) ];
15    assert_eq![ top.pop(), None ];
16}
Source

pub fn into_iter_sorted(self) -> IntoIterSorted<X, C>

Converts this topset into a sorted iterator

Notice that the lowest item of the top set is the first one. The greatest item is the last one.

§Example
// this topset contains { 7, 9 }
let topset = TopSet::with_init(2, u32::gt, vec![7,5,6,9,4,2,3] );
let mut iter = topset.into_iter_sorted();
assert_eq!( iter.next(), Some(7));
assert_eq!( iter.next(), Some(9));
assert_eq!( iter.next(), None);
Source

pub fn into_sorted_vec(self) -> Vec<X>
where X: PartialEq,

Returns the topset in a sorted vector.

The first element of the vector is the lowest item of the top set and the last one is the greatest one.

§Example
// this topset contains { 7, 9 }
let topset = TopSet::with_init(3, u32::gt, vec![1,2,7,4,7,5,6,9,4,2,3] );
assert_eq!( topset.into_sorted_vec(), vec![7,7,9]);
Source

pub fn drain(&mut self) -> Drain<'_, X>

Clears the binary heap, returning an iterator over the removed elements in arbitrary order. If the iterator is dropped before being fully consumed, it drops the remaining elements in arbitrary order.

The returned iterator keeps a mutable borrow on the heap to optimize its implementation.

§Example
let mut topset = TopSet::with_init(4, u32::gt, vec![7,5,6,9,4,2,3] );
let _ = topset.drain();
assert! (topset.is_empty());
Source

pub fn resize(&mut self, n: usize)

Resize the top set

If the size decreases, then the lowest items are removed. If the size increases, nothing else happens but there is still more room for next insertions.

§Example
let mut topset = TopSet::with_init(4, u32::gt, vec![7,5,6,9,4,2,3] );

// the topset contains { 7, 5, 6, 9 }
assert_eq! (topset.peek(), Some(&5));

topset.resize(2);
// the topset contains { 7, 9 }
assert_eq! (topset.peek(), Some(&7));

// try to add 1 but no more room left
assert_eq!( topset.insert(1), Some(1) );

topset.resize(3); // grows by one
assert_eq!( topset.insert(1), None ); // one room left
assert_eq!( topset.insert(2), Some(1) ); // but now, is full
// at this point, the topset contains { 7, 9, 2 }
Source

pub fn pop(&mut self) -> Option<X>

Pop the lowest item of the top set

Remove and return the lowest item of the top set. After this call, there is one more room for a item.

This method is the only way to get the top elements in a sorted way (from the lowest to the best). Resize the top set

If the size decreases, then the lowest items are removed. If the size increases, nothing else happens but there is still more room for next insertions.

§Example
let mut topset = TopSet::with_init(2, u32::gt, vec![7,5,6,9,4,2,3] );

assert_eq! (topset.pop(), Some(7));
assert_eq! (topset.pop(), Some(9));
assert_eq! (topset.pop(), None);
Examples found in repository?
examples/lowest_cost.rs (line 10)
3pub fn main()
4{
5    let mut top = TopSet::<f32,_>::new(5, f32::lt);
6    // top.extend(vec![81.5, 4.5, 4., 1., 45., 22., 11.]);
7    //  top.extend(vec![81.5, 4.5, 4., 1., 45., 22., 11.]);
8    vec![81.5, 4.5, 4., 1., 45., 22., 11.,93.].into_iter().for_each(|u| { dbg!(&top); dbg!(&u); dbg!(top.insert(u)); dbg!(&top); });
9    vec![81.5, 4.5, 4., 1., 45., 22., 11.].into_iter().for_each(|u| { dbg!(&top); dbg!(&u); dbg!(top.insert(u));dbg!(&top); });
10    assert_eq![ top.pop(), Some(4.5) ];
11    assert_eq![ top.pop(), Some(4.) ];
12    assert_eq![ top.pop(), Some(4.) ];
13    assert_eq![ top.pop(), Some(1.) ];
14    assert_eq![ top.pop(), Some(1.) ];
15    assert_eq![ top.pop(), None ];
16}
Source

pub fn clear(&mut self)

Removes all the elements in the top set

§Example
let mut topset = TopSet::with_init(2, u32::gt, vec![7,5,6,9,4,2,3] );

assert_eq! (topset.len(), 2);
topset.clear();
assert_eq!( topset.len(), 0)
Source

pub fn beat(&self, a: &X, b: &X) -> bool

Checks if an element beats the other.

It does not related to the current elements in the topset but refers only to the comparing function (the beat).

§Example
let mut topset = TopSet::with_init(2, u32::gt, vec![7,5,6,9,4,2,3] );

assert! ( topset.beat(&4, &3));
assert! ( ! topset.beat(&4, &7));

Trait Implementations§

Source§

impl<X: Clone, C> Clone for TopSet<X, C>
where C: Fn(&X, &X) -> bool + Clone,

Source§

fn clone(&self) -> TopSet<X, C>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<X, C> Debug for TopSet<X, C>
where X: Debug, C: Fn(&X, &X) -> bool,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<X, C> Extend<X> for TopSet<X, C>
where C: Fn(&X, &X) -> bool,

Source§

fn extend<T: IntoIterator<Item = X>>(&mut self, iter: T)

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl<X, C> From<TopSet<X, C>> for IntoIterSorted<X, C>
where C: Fn(&X, &X) -> bool,

Source§

fn from(topset: TopSet<X, C>) -> Self

Converts to this type from the input type.
Source§

impl<'a, X, C> IntoIterator for &'a TopSet<X, C>
where C: Fn(&X, &X) -> bool,

Source§

type Item = &'a X

The type of the elements being iterated over.
Source§

type IntoIter = <&'a Vec<X> as IntoIterator>::IntoIter

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<X, C> IntoIterator for TopSet<X, C>
where C: Fn(&X, &X) -> bool,

Source§

type Item = X

The type of the elements being iterated over.
Source§

type IntoIter = <Vec<X> as IntoIterator>::IntoIter

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more

Auto Trait Implementations§

§

impl<X, C> Freeze for TopSet<X, C>
where C: Freeze,

§

impl<X, C> RefUnwindSafe for TopSet<X, C>

§

impl<X, C> Send for TopSet<X, C>
where C: Send, X: Send,

§

impl<X, C> Sync for TopSet<X, C>
where C: Sync, X: Sync,

§

impl<X, C> Unpin for TopSet<X, C>
where C: Unpin, X: Unpin,

§

impl<X, C> UnwindSafe for TopSet<X, C>
where C: UnwindSafe, X: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<I> TopSetReducing for I
where I: IntoIterator,

Source§

type Item = <I as IntoIterator>::Item

Source§

fn topset<C>(self, n: usize, beat: C) -> TopSet<<I as TopSetReducing>::Item, C>
where C: Fn(&<I as TopSetReducing>::Item, &<I as TopSetReducing>::Item) -> bool,

Build the top set according to the specified challenge.
Source§

fn topset_greatest( self, n: usize, ) -> TopSet<Self::Item, fn(&Self::Item, &Self::Item) -> bool>
where Self::Item: PartialOrd, Self: Sized,

Build the top set of the greatest values.
Source§

fn topset_lowest( self, n: usize, ) -> TopSet<Self::Item, fn(&Self::Item, &Self::Item) -> bool>
where Self::Item: PartialOrd, Self: Sized,

Build the top set of the lowest values.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.