dioxus_stores/impls/slice.rs
1use std::iter::FusedIterator;
2
3use crate::{impls::index::IndexWrite, store::Store};
4use dioxus_signals::{Readable, ReadableExt};
5
6impl<Lens, I> Store<Vec<I>, Lens>
7where
8 Lens: Readable<Target = Vec<I>> + 'static,
9 I: 'static,
10{
11 /// Returns the length of the slice. This will only track the shallow state of the slice.
12 /// It will only cause a re-run if the length of the slice could change.
13 ///
14 /// # Example
15 /// ```rust, no_run
16 /// use dioxus_stores::*;
17 /// let store = use_store(|| vec![1, 2, 3]);
18 /// assert_eq!(store.len(), 3);
19 /// ```
20 pub fn len(&self) -> usize {
21 self.selector().track_shallow();
22 self.selector().peek().len()
23 }
24
25 /// Checks if the slice is empty. This will only track the shallow state of the slice.
26 /// It will only cause a re-run if the length of the slice could change.
27 ///
28 /// # Example
29 /// ```rust, no_run
30 /// use dioxus_stores::*;
31 /// let store = use_store(|| vec![1, 2, 3]);
32 /// assert!(!store.is_empty());
33 /// ```
34 pub fn is_empty(&self) -> bool {
35 self.selector().track_shallow();
36 self.selector().peek().is_empty()
37 }
38
39 /// Returns an iterator over the items in the slice. This will only track the shallow state of the slice.
40 /// It will only cause a re-run if the length of the slice could change.
41 /// # Example
42 /// ```rust, no_run
43 /// use dioxus_stores::*;
44 /// let store = use_store(|| vec![1, 2, 3]);
45 /// for item in store.iter() {
46 /// println!("{}", item);
47 /// }
48 /// ```
49 pub fn iter(
50 &self,
51 ) -> impl ExactSizeIterator<Item = Store<I, IndexWrite<usize, Lens>>>
52 + DoubleEndedIterator
53 + FusedIterator
54 + '_
55 where
56 Lens: Clone,
57 {
58 (0..self.len()).map(move |i| self.clone().index(i))
59 }
60
61 /// Try to get an item from slice. This will only track the shallow state of the slice.
62 /// It will only cause a re-run if the length of the slice could change. The new store
63 /// will only update when the item at the index changes.
64 ///
65 /// # Example
66 /// ```rust, no_run
67 /// use dioxus_stores::*;
68 /// let store = use_store(|| vec![1, 2, 3]);
69 /// let indexed_store = store.get(1).unwrap();
70 /// // The indexed store can access the store methods of the indexed store.
71 /// assert_eq!(indexed_store(), 2);
72 /// ```
73 pub fn get(&self, index: usize) -> Option<Store<I, IndexWrite<usize, Lens>>>
74 where
75 Lens: Clone,
76 {
77 if index >= self.len() {
78 None
79 } else {
80 Some(self.clone().index(index))
81 }
82 }
83}