toql_core/map_key.rs
1//! An iterator that maps entities into keys.
2
3use crate::keyed::Keyed;
4
5/// This `struct` is created by the [map_key] method on Iterator. See its documentation for more.
6pub struct MapKeyIter<I> {
7 orig: I,
8}
9
10impl<I> Iterator for MapKeyIter<I>
11where
12 I: Iterator,
13 I::Item: Keyed,
14{
15 type Item = <I::Item as Keyed>::Key;
16
17 #[inline]
18 fn next(&mut self) -> Option<Self::Item> {
19 self.orig.next().map(|v| v.key())
20 }
21
22 #[inline]
23 fn size_hint(&self) -> (usize, Option<usize>) {
24 self.orig.size_hint()
25 }
26}
27/// Takes a list of entities and turn them into keys.
28/// This can also be used to create key predicates.
29///
30/// ### Example
31/// - Basic collection of keys
32/// - Building a key predicate for a Toql query
33///
34/// ```rust, ignore
35/// use toql_derive::Toql;
36/// use toql_core::{map_key::MapKey, query::Query};
37///
38/// #[derive(Toql)]
39/// struct User {
40/// #[toql(key)]
41/// id: u64,
42/// name: String
43/// }
44///
45/// let users = vec![User{id:5, name: "Joe".to_string()}, User{id:7, name: "Sue".to_string()}];
46/// let keys = users.iter().map_key().collect::<Vec<_>>(); // Returns Vec<UserKey>
47/// let predicate = users.iter().map_key().collect::<Query>(); // Build query
48///
49/// assert_eq!(predicate.to_string, "(id eq 5;id eq 7)");
50/// ```
51/// Notice that when keys are be collected into a [Query](crate::query::Query) the
52/// predicates are concatenated with OR.
53pub fn map_key<I: Iterator>(xs: I) -> MapKeyIter<I> {
54 MapKeyIter { orig: xs }
55}
56
57/// An iterator trait to turn entities into keys.
58pub trait MapKey: Sized {
59 fn map_key(self) -> MapKeyIter<Self>;
60}
61
62impl<I: Iterator> MapKey for I {
63 fn map_key(self) -> MapKeyIter<Self> {
64 map_key(self)
65 }
66}