[go: up one dir, main page]

Vector

Struct Vector 

Source
pub struct Vector<A> { /* private fields */ }
Available on crate feature im only.
Expand description

A persistent vector.

This is a sequence of elements in insertion order - if you need a list of things, any kind of list of things, this is what you’re looking for.

It’s implemented as an RRB vector with smart head/tail chunking. In performance terms, this means that practically every operation is O(log n), except push/pop on both sides, which will be O(1) amortised, and O(log n) in the worst case. In practice, the push/pop operations will be blindingly fast, nearly on par with the native VecDeque, and other operations will have decent, if not high, performance, but they all have more or less the same O(log n) complexity, so you don’t need to keep their performance characteristics in mind - everything, even splitting and merging, is safe to use and never too slow.

§Performance Notes

Because of the head/tail chunking technique, until you push a number of items above double the tree’s branching factor (that’s self.len() = 2 × k (where k = 64) = 128) on either side, the data structure is still just a handful of arrays, not yet an RRB tree, so you’ll see performance and memory characteristics similar to Vec or VecDeque.

This means that the structure always preallocates four chunks of size k (k being the tree’s branching factor), equivalent to a Vec with an initial capacity of 256. Beyond that, it will allocate tree nodes of capacity k as needed.

In addition, vectors start out as single chunks, and only expand into the full data structure once you go past the chunk size. This makes them perform identically to Vec at small sizes.

Implementations§

Source§

impl<A> Vector<A>
where A: Clone,

Source

pub fn new() -> Vector<A>

Construct an empty vector.

Examples found in repository?
examples/invalidation.rs (line 35)
29pub fn main() {
30    let window = WindowDesc::new(build_widget()).title(
31        LocalizedString::new("invalidate-demo-window-title").with_placeholder("Invalidate demo"),
32    );
33    let state = AppState {
34        label: "My label".into(),
35        circles: Vector::new(),
36    };
37    AppLauncher::with_window(window)
38        .log_to_console()
39        .launch(state)
40        .expect("launch failed");
41}
Source

pub fn len(&self) -> usize

Get the length of a vector.

Time: O(1)

§Examples
assert_eq!(5, vector![1, 2, 3, 4, 5].len());
Examples found in repository?
examples/tabs.rs (line 50)
49    fn remove_tab(&mut self, idx: usize) {
50        if idx >= self.tab_labels.len() {
51            tracing::warn!("Attempt to remove non existent tab at index {}", idx)
52        } else {
53            self.removed_tabs += 1;
54            self.tab_labels.remove(idx);
55        }
56    }
More examples
Hide additional examples
examples/list.rs (line 42)
35pub fn main() {
36    let main_window = WindowDesc::new(ui_builder())
37        .title(LocalizedString::new("list-demo-window-title").with_placeholder("List Demo"));
38    // Set our initial data
39    let left = vector![1, 2];
40    let right = vector![1, 2, 3];
41    let data = AppData {
42        l_index: left.len(),
43        r_index: right.len(),
44        left,
45        right,
46    };
47    AppLauncher::with_window(main_window)
48        .log_to_console()
49        .launch(data)
50        .expect("launch failed");
51}
Source

pub fn is_empty(&self) -> bool

Test whether a vector is empty.

Time: O(1)

§Examples
let vec = vector!["Joe", "Mike", "Robert"];
assert_eq!(false, vec.is_empty());
assert_eq!(true, Vector::<i32>::new().is_empty());
Examples found in repository?
examples/invalidation.rs (line 103)
70    fn event(&mut self, ctx: &mut EventCtx, ev: &Event, data: &mut Vector<Circle>, _env: &Env) {
71        if let Event::MouseDown(ev) = ev {
72            if ev.mods.shift() {
73                data.push_back(Circle {
74                    pos: ev.pos,
75                    time: Instant::now(),
76                });
77            } else if ev.mods.ctrl() {
78                data.retain(|c| {
79                    if (c.pos - ev.pos).hypot() > RADIUS {
80                        true
81                    } else {
82                        ctx.request_paint_rect(kurbo::Circle::new(c.pos, RADIUS).bounding_box());
83                        false
84                    }
85                });
86            } else {
87                // Move the circle to a new location, invalidating the old locations. The new location
88                // will be invalidated during AnimFrame.
89                for c in data.iter() {
90                    ctx.request_paint_rect(kurbo::Circle::new(c.pos, RADIUS).bounding_box());
91                }
92                data.clear();
93                data.push_back(Circle {
94                    pos: ev.pos,
95                    time: Instant::now(),
96                });
97            }
98            ctx.request_anim_frame();
99        } else if let Event::AnimFrame(_) = ev {
100            for c in &*data {
101                ctx.request_paint_rect(kurbo::Circle::new(c.pos, RADIUS).bounding_box());
102            }
103            if !data.is_empty() {
104                ctx.request_anim_frame();
105            }
106        }
107    }
Source

pub fn is_inline(&self) -> bool

Test whether a vector is currently inlined.

Vectors small enough that their contents could be stored entirely inside the space of std::mem::size_of::<Vector<A>>() bytes are stored inline on the stack instead of allocating any chunks. This method returns true if this vector is currently inlined, or false if it currently has chunks allocated on the heap.

This may be useful in conjunction with ptr_eq(), which checks if two vectors’ heap allocations are the same, and thus will never return true for inlined vectors.

Time: O(1)

Source

pub fn ptr_eq(&self, other: &Vector<A>) -> bool

Test whether two vectors refer to the same content in memory.

This uses the following rules to determine equality:

  • If the two sides are references to the same vector, return true.
  • If the two sides are single chunk vectors pointing to the same chunk, return true.
  • If the two sides are full trees pointing to the same chunks, return true.

This would return true if you’re comparing a vector to itself, or if you’re comparing a vector to a fresh clone of itself. The exception to this is if you’ve cloned an inline array (ie. an array with so few elements they can fit inside the space a Vector allocates for its pointers, so there are no heap allocations to compare).

Time: O(1)

Source

pub fn iter(&self) -> Iter<'_, A>

Get an iterator over a vector.

Time: O(1)

Examples found in repository?
examples/tabs.rs (line 181)
180    fn tabs(&self, data: &DynamicTabData) -> Vec<Self::Key> {
181        data.tab_labels.iter().copied().collect()
182    }
More examples
Hide additional examples
examples/invalidation.rs (line 89)
70    fn event(&mut self, ctx: &mut EventCtx, ev: &Event, data: &mut Vector<Circle>, _env: &Env) {
71        if let Event::MouseDown(ev) = ev {
72            if ev.mods.shift() {
73                data.push_back(Circle {
74                    pos: ev.pos,
75                    time: Instant::now(),
76                });
77            } else if ev.mods.ctrl() {
78                data.retain(|c| {
79                    if (c.pos - ev.pos).hypot() > RADIUS {
80                        true
81                    } else {
82                        ctx.request_paint_rect(kurbo::Circle::new(c.pos, RADIUS).bounding_box());
83                        false
84                    }
85                });
86            } else {
87                // Move the circle to a new location, invalidating the old locations. The new location
88                // will be invalidated during AnimFrame.
89                for c in data.iter() {
90                    ctx.request_paint_rect(kurbo::Circle::new(c.pos, RADIUS).bounding_box());
91                }
92                data.clear();
93                data.push_back(Circle {
94                    pos: ev.pos,
95                    time: Instant::now(),
96                });
97            }
98            ctx.request_anim_frame();
99        } else if let Event::AnimFrame(_) = ev {
100            for c in &*data {
101                ctx.request_paint_rect(kurbo::Circle::new(c.pos, RADIUS).bounding_box());
102            }
103            if !data.is_empty() {
104                ctx.request_anim_frame();
105            }
106        }
107    }
Source

pub fn iter_mut(&mut self) -> IterMut<'_, A>

Get a mutable iterator over a vector.

Time: O(1)

Source

pub fn leaves(&self) -> Chunks<'_, A>

Get an iterator over the leaf nodes of a vector.

This returns an iterator over the Chunks at the leaves of the RRB tree. These are useful for efficient parallelisation of work on the vector, but should not be used for basic iteration.

Time: O(1)

Source

pub fn leaves_mut(&mut self) -> ChunksMut<'_, A>

Get a mutable iterator over the leaf nodes of a vector. This returns an iterator over the Chunks at the leaves of the RRB tree. These are useful for efficient parallelisation of work on the vector, but should not be used for basic iteration.

Time: O(1)

Source

pub fn focus(&self) -> Focus<'_, A>

Construct a Focus for a vector.

Time: O(1)

Source

pub fn focus_mut(&mut self) -> FocusMut<'_, A>

Construct a FocusMut for a vector.

Time: O(1)

Source

pub fn get(&self, index: usize) -> Option<&A>

Get a reference to the value at index index in a vector.

Returns None if the index is out of bounds.

Time: O(log n)

§Examples
let vec = vector!["Joe", "Mike", "Robert"];
assert_eq!(Some(&"Robert"), vec.get(2));
assert_eq!(None, vec.get(5));
Source

pub fn get_mut(&mut self, index: usize) -> Option<&mut A>

Get a mutable reference to the value at index index in a vector.

Returns None if the index is out of bounds.

Time: O(log n)

§Examples
let mut vec = vector!["Joe", "Mike", "Robert"];
{
    let robert = vec.get_mut(2).unwrap();
    assert_eq!(&mut "Robert", robert);
    *robert = "Bjarne";
}
assert_eq!(vector!["Joe", "Mike", "Bjarne"], vec);
Source

pub fn front(&self) -> Option<&A>

Get the first element of a vector.

If the vector is empty, None is returned.

Time: O(log n)

Source

pub fn front_mut(&mut self) -> Option<&mut A>

Get a mutable reference to the first element of a vector.

If the vector is empty, None is returned.

Time: O(log n)

Source

pub fn head(&self) -> Option<&A>

Get the first element of a vector.

If the vector is empty, None is returned.

This is an alias for the front method.

Time: O(log n)

Source

pub fn back(&self) -> Option<&A>

Get the last element of a vector.

If the vector is empty, None is returned.

Time: O(log n)

Source

pub fn back_mut(&mut self) -> Option<&mut A>

Get a mutable reference to the last element of a vector.

If the vector is empty, None is returned.

Time: O(log n)

Source

pub fn last(&self) -> Option<&A>

Get the last element of a vector.

If the vector is empty, None is returned.

This is an alias for the back method.

Time: O(log n)

Source

pub fn index_of(&self, value: &A) -> Option<usize>
where A: PartialEq,

Get the index of a given element in the vector.

Searches the vector for the first occurrence of a given value, and returns the index of the value if it’s there. Otherwise, it returns None.

Time: O(n)

§Examples
let mut vec = vector![1, 2, 3, 4, 5];
assert_eq!(Some(2), vec.index_of(&3));
assert_eq!(None, vec.index_of(&31337));
Examples found in repository?
examples/tabs.rs (line 193)
192    fn close_tab(&self, key: Self::Key, data: &mut DynamicTabData) {
193        if let Some(idx) = data.tab_labels.index_of(&key) {
194            data.remove_tab(idx)
195        }
196    }
Source

pub fn contains(&self, value: &A) -> bool
where A: PartialEq,

Test if a given element is in the vector.

Searches the vector for the first occurrence of a given value, and returns true if it’s there. If it’s nowhere to be found in the vector, it returns false.

Time: O(n)

§Examples
let mut vec = vector![1, 2, 3, 4, 5];
assert_eq!(true, vec.contains(&3));
assert_eq!(false, vec.contains(&31337));
Source

pub fn clear(&mut self)

Discard all elements from the vector.

This leaves you with an empty vector, and all elements that were previously inside it are dropped.

Time: O(n)

Examples found in repository?
examples/invalidation.rs (line 92)
70    fn event(&mut self, ctx: &mut EventCtx, ev: &Event, data: &mut Vector<Circle>, _env: &Env) {
71        if let Event::MouseDown(ev) = ev {
72            if ev.mods.shift() {
73                data.push_back(Circle {
74                    pos: ev.pos,
75                    time: Instant::now(),
76                });
77            } else if ev.mods.ctrl() {
78                data.retain(|c| {
79                    if (c.pos - ev.pos).hypot() > RADIUS {
80                        true
81                    } else {
82                        ctx.request_paint_rect(kurbo::Circle::new(c.pos, RADIUS).bounding_box());
83                        false
84                    }
85                });
86            } else {
87                // Move the circle to a new location, invalidating the old locations. The new location
88                // will be invalidated during AnimFrame.
89                for c in data.iter() {
90                    ctx.request_paint_rect(kurbo::Circle::new(c.pos, RADIUS).bounding_box());
91                }
92                data.clear();
93                data.push_back(Circle {
94                    pos: ev.pos,
95                    time: Instant::now(),
96                });
97            }
98            ctx.request_anim_frame();
99        } else if let Event::AnimFrame(_) = ev {
100            for c in &*data {
101                ctx.request_paint_rect(kurbo::Circle::new(c.pos, RADIUS).bounding_box());
102            }
103            if !data.is_empty() {
104                ctx.request_anim_frame();
105            }
106        }
107    }
Source

pub fn binary_search_by<F>(&self, f: F) -> Result<usize, usize>
where F: FnMut(&A) -> Ordering,

Binary search a sorted vector for a given element using a comparator function.

Assumes the vector has already been sorted using the same comparator function, eg. by using sort_by.

If the value is found, it returns Ok(index) where index is the index of the element. If the value isn’t found, it returns Err(index) where index is the index at which the element would need to be inserted to maintain sorted order.

Time: O(log n)

Binary search a sorted vector for a given element.

If the value is found, it returns Ok(index) where index is the index of the element. If the value isn’t found, it returns Err(index) where index is the index at which the element would need to be inserted to maintain sorted order.

Time: O(log n)

Source

pub fn binary_search_by_key<B, F>(&self, b: &B, f: F) -> Result<usize, usize>
where F: FnMut(&A) -> B, B: Ord,

Binary search a sorted vector for a given element with a key extract function.

Assumes the vector has already been sorted using the same key extract function, eg. by using sort_by_key.

If the value is found, it returns Ok(index) where index is the index of the element. If the value isn’t found, it returns Err(index) where index is the index at which the element would need to be inserted to maintain sorted order.

Time: O(log n)

Source§

impl<A> Vector<A>
where A: Clone,

Source

pub fn unit(a: A) -> Vector<A>

Construct a vector with a single value.

§Examples
let vec = Vector::unit(1337);
assert_eq!(1, vec.len());
assert_eq!(
  vec.get(0),
  Some(&1337)
);
Source

pub fn update(&self, index: usize, value: A) -> Vector<A>

Create a new vector with the value at index index updated.

Panics if the index is out of bounds.

Time: O(log n)

§Examples
let mut vec = vector![1, 2, 3];
assert_eq!(vector![1, 5, 3], vec.update(1, 5));
Source

pub fn set(&mut self, index: usize, value: A) -> A

Update the value at index index in a vector.

Returns the previous value at the index.

Panics if the index is out of bounds.

Time: O(log n)

Source

pub fn swap(&mut self, i: usize, j: usize)

Swap the elements at indices i and j.

Time: O(log n)

Source

pub fn push_front(&mut self, value: A)

Push a value to the front of a vector.

Time: O(1)*

§Examples
let mut vec = vector![5, 6, 7];
vec.push_front(4);
assert_eq!(vector![4, 5, 6, 7], vec);
Source

pub fn push_back(&mut self, value: A)

Push a value to the back of a vector.

Time: O(1)*

§Examples
let mut vec = vector![1, 2, 3];
vec.push_back(4);
assert_eq!(vector![1, 2, 3, 4], vec);
Examples found in repository?
examples/tabs.rs (line 46)
44    fn add_tab(&mut self) {
45        self.highest_tab += 1;
46        self.tab_labels.push_back(self.highest_tab);
47    }
More examples
Hide additional examples
examples/invalidation.rs (lines 73-76)
70    fn event(&mut self, ctx: &mut EventCtx, ev: &Event, data: &mut Vector<Circle>, _env: &Env) {
71        if let Event::MouseDown(ev) = ev {
72            if ev.mods.shift() {
73                data.push_back(Circle {
74                    pos: ev.pos,
75                    time: Instant::now(),
76                });
77            } else if ev.mods.ctrl() {
78                data.retain(|c| {
79                    if (c.pos - ev.pos).hypot() > RADIUS {
80                        true
81                    } else {
82                        ctx.request_paint_rect(kurbo::Circle::new(c.pos, RADIUS).bounding_box());
83                        false
84                    }
85                });
86            } else {
87                // Move the circle to a new location, invalidating the old locations. The new location
88                // will be invalidated during AnimFrame.
89                for c in data.iter() {
90                    ctx.request_paint_rect(kurbo::Circle::new(c.pos, RADIUS).bounding_box());
91                }
92                data.clear();
93                data.push_back(Circle {
94                    pos: ev.pos,
95                    time: Instant::now(),
96                });
97            }
98            ctx.request_anim_frame();
99        } else if let Event::AnimFrame(_) = ev {
100            for c in &*data {
101                ctx.request_paint_rect(kurbo::Circle::new(c.pos, RADIUS).bounding_box());
102            }
103            if !data.is_empty() {
104                ctx.request_anim_frame();
105            }
106        }
107    }
examples/list.rs (line 62)
53fn ui_builder() -> impl Widget<AppData> {
54    let mut root = Flex::column();
55
56    // Build a button to add children to both lists
57    root.add_child(
58        Button::new("Add")
59            .on_click(|_, data: &mut AppData, _| {
60                // Add child to left list
61                data.l_index += 1;
62                data.left.push_back(data.l_index as u32);
63
64                // Add child to right list
65                data.r_index += 1;
66                data.right.push_back(data.r_index as u32);
67            })
68            .fix_height(30.0)
69            .expand_width(),
70    );
71
72    let mut lists = Flex::row().cross_axis_alignment(CrossAxisAlignment::Start);
73
74    // Build a simple list
75    lists.add_flex_child(
76        Scroll::new(List::new(|| {
77            Label::new(|item: &u32, _env: &_| format!("List item #{item}"))
78                .align_vertical(UnitPoint::LEFT)
79                .padding(10.0)
80                .expand()
81                .height(50.0)
82                .background(Color::rgb(0.5, 0.5, 0.5))
83        }))
84        .vertical()
85        .lens(AppData::left),
86        1.0,
87    );
88
89    // Build a list with shared data
90    lists.add_flex_child(
91        Scroll::new(
92            List::new(|| {
93                Flex::row()
94                    .with_child(
95                        Label::new(|(_, item): &(Vector<u32>, u32), _env: &_| {
96                            format!("List item #{item}")
97                        })
98                        .align_vertical(UnitPoint::LEFT),
99                    )
100                    .with_flex_spacer(1.0)
101                    .with_child(
102                        Button::new("Delete")
103                            .on_click(|_ctx, (shared, item): &mut (Vector<u32>, u32), _env| {
104                                // We have access to both child's data and shared data.
105                                // Remove element from right list.
106                                shared.retain(|v| v != item);
107                            })
108                            .fix_size(80.0, 20.0)
109                            .align_vertical(UnitPoint::CENTER),
110                    )
111                    .padding(10.0)
112                    .background(Color::rgb(0.5, 0.0, 0.5))
113                    .fix_height(50.0)
114            })
115            .with_spacing(10.),
116        )
117        .vertical()
118        .lens(lens::Identity.map(
119            // Expose shared data with children data
120            |d: &AppData| (d.right.clone(), d.right.clone()),
121            |d: &mut AppData, x: (Vector<u32>, Vector<u32>)| {
122                // If shared data was changed reflect the changes in our AppData
123                d.right = x.0
124            },
125        )),
126        1.0,
127    );
128
129    root.add_flex_child(lists, 1.0);
130
131    root.with_child(Label::new("horizontal list"))
132        .with_child(
133            Scroll::new(
134                List::new(|| {
135                    Label::new(|item: &u32, _env: &_| format!("List item #{item}"))
136                        .padding(10.0)
137                        .background(Color::rgb(0.5, 0.5, 0.0))
138                        .fix_height(50.0)
139                })
140                .horizontal()
141                .with_spacing(10.)
142                .lens(AppData::left),
143            )
144            .horizontal(),
145        )
146        .debug_paint_layout()
147}
Source

pub fn pop_front(&mut self) -> Option<A>

Remove the first element from a vector and return it.

Time: O(1)*

§Examples
let mut vec = vector![1, 2, 3];
assert_eq!(Some(1), vec.pop_front());
assert_eq!(vector![2, 3], vec);
Source

pub fn pop_back(&mut self) -> Option<A>

Remove the last element from a vector and return it.

Time: O(1)*

§Examples
let mut vec = vector![1, 2, 3];
assert_eq!(Some(3), vec.pop_back());
assert_eq!(vector![1, 2], vec);
Source

pub fn append(&mut self, other: Vector<A>)

Append the vector other to the end of the current vector.

Time: O(log n)

§Examples
let mut vec = vector![1, 2, 3];
vec.append(vector![7, 8, 9]);
assert_eq!(vector![1, 2, 3, 7, 8, 9], vec);
Source

pub fn retain<F>(&mut self, f: F)
where F: FnMut(&A) -> bool,

Retain only the elements specified by the predicate.

Remove all elements for which the provided function f returns false from the vector.

Time: O(n)

Examples found in repository?
examples/invalidation.rs (lines 78-85)
70    fn event(&mut self, ctx: &mut EventCtx, ev: &Event, data: &mut Vector<Circle>, _env: &Env) {
71        if let Event::MouseDown(ev) = ev {
72            if ev.mods.shift() {
73                data.push_back(Circle {
74                    pos: ev.pos,
75                    time: Instant::now(),
76                });
77            } else if ev.mods.ctrl() {
78                data.retain(|c| {
79                    if (c.pos - ev.pos).hypot() > RADIUS {
80                        true
81                    } else {
82                        ctx.request_paint_rect(kurbo::Circle::new(c.pos, RADIUS).bounding_box());
83                        false
84                    }
85                });
86            } else {
87                // Move the circle to a new location, invalidating the old locations. The new location
88                // will be invalidated during AnimFrame.
89                for c in data.iter() {
90                    ctx.request_paint_rect(kurbo::Circle::new(c.pos, RADIUS).bounding_box());
91                }
92                data.clear();
93                data.push_back(Circle {
94                    pos: ev.pos,
95                    time: Instant::now(),
96                });
97            }
98            ctx.request_anim_frame();
99        } else if let Event::AnimFrame(_) = ev {
100            for c in &*data {
101                ctx.request_paint_rect(kurbo::Circle::new(c.pos, RADIUS).bounding_box());
102            }
103            if !data.is_empty() {
104                ctx.request_anim_frame();
105            }
106        }
107    }
More examples
Hide additional examples
examples/list.rs (line 106)
53fn ui_builder() -> impl Widget<AppData> {
54    let mut root = Flex::column();
55
56    // Build a button to add children to both lists
57    root.add_child(
58        Button::new("Add")
59            .on_click(|_, data: &mut AppData, _| {
60                // Add child to left list
61                data.l_index += 1;
62                data.left.push_back(data.l_index as u32);
63
64                // Add child to right list
65                data.r_index += 1;
66                data.right.push_back(data.r_index as u32);
67            })
68            .fix_height(30.0)
69            .expand_width(),
70    );
71
72    let mut lists = Flex::row().cross_axis_alignment(CrossAxisAlignment::Start);
73
74    // Build a simple list
75    lists.add_flex_child(
76        Scroll::new(List::new(|| {
77            Label::new(|item: &u32, _env: &_| format!("List item #{item}"))
78                .align_vertical(UnitPoint::LEFT)
79                .padding(10.0)
80                .expand()
81                .height(50.0)
82                .background(Color::rgb(0.5, 0.5, 0.5))
83        }))
84        .vertical()
85        .lens(AppData::left),
86        1.0,
87    );
88
89    // Build a list with shared data
90    lists.add_flex_child(
91        Scroll::new(
92            List::new(|| {
93                Flex::row()
94                    .with_child(
95                        Label::new(|(_, item): &(Vector<u32>, u32), _env: &_| {
96                            format!("List item #{item}")
97                        })
98                        .align_vertical(UnitPoint::LEFT),
99                    )
100                    .with_flex_spacer(1.0)
101                    .with_child(
102                        Button::new("Delete")
103                            .on_click(|_ctx, (shared, item): &mut (Vector<u32>, u32), _env| {
104                                // We have access to both child's data and shared data.
105                                // Remove element from right list.
106                                shared.retain(|v| v != item);
107                            })
108                            .fix_size(80.0, 20.0)
109                            .align_vertical(UnitPoint::CENTER),
110                    )
111                    .padding(10.0)
112                    .background(Color::rgb(0.5, 0.0, 0.5))
113                    .fix_height(50.0)
114            })
115            .with_spacing(10.),
116        )
117        .vertical()
118        .lens(lens::Identity.map(
119            // Expose shared data with children data
120            |d: &AppData| (d.right.clone(), d.right.clone()),
121            |d: &mut AppData, x: (Vector<u32>, Vector<u32>)| {
122                // If shared data was changed reflect the changes in our AppData
123                d.right = x.0
124            },
125        )),
126        1.0,
127    );
128
129    root.add_flex_child(lists, 1.0);
130
131    root.with_child(Label::new("horizontal list"))
132        .with_child(
133            Scroll::new(
134                List::new(|| {
135                    Label::new(|item: &u32, _env: &_| format!("List item #{item}"))
136                        .padding(10.0)
137                        .background(Color::rgb(0.5, 0.5, 0.0))
138                        .fix_height(50.0)
139                })
140                .horizontal()
141                .with_spacing(10.)
142                .lens(AppData::left),
143            )
144            .horizontal(),
145        )
146        .debug_paint_layout()
147}
Source

pub fn split_at(self, index: usize) -> (Vector<A>, Vector<A>)

Split a vector at a given index.

Split a vector at a given index, consuming the vector and returning a pair of the left hand side and the right hand side of the split.

Time: O(log n)

§Examples
let mut vec = vector![1, 2, 3, 7, 8, 9];
let (left, right) = vec.split_at(3);
assert_eq!(vector![1, 2, 3], left);
assert_eq!(vector![7, 8, 9], right);
Source

pub fn split_off(&mut self, index: usize) -> Vector<A>

Split a vector at a given index.

Split a vector at a given index, leaving the left hand side in the current vector and returning a new vector containing the right hand side.

Time: O(log n)

§Examples
let mut left = vector![1, 2, 3, 7, 8, 9];
let right = left.split_off(3);
assert_eq!(vector![1, 2, 3], left);
assert_eq!(vector![7, 8, 9], right);
Source

pub fn skip(&self, count: usize) -> Vector<A>

Construct a vector with count elements removed from the start of the current vector.

Time: O(log n)

Source

pub fn take(&self, count: usize) -> Vector<A>

Construct a vector of the first count elements from the current vector.

Time: O(log n)

Source

pub fn truncate(&mut self, len: usize)

Truncate a vector to the given size.

Discards all elements in the vector beyond the given length.

Panics if the new length is greater than the current length.

Time: O(log n)

Source

pub fn slice<R>(&mut self, range: R) -> Vector<A>
where R: RangeBounds<usize>,

Extract a slice from a vector.

Remove the elements from start_index until end_index in the current vector and return the removed slice as a new vector.

Time: O(log n)

Source

pub fn insert(&mut self, index: usize, value: A)

Insert an element into a vector.

Insert an element at position index, shifting all elements after it to the right.

§Performance Note

While push_front and push_back are heavily optimised operations, insert in the middle of a vector requires a split, a push, and an append. Thus, if you want to insert many elements at the same location, instead of inserting them one by one, you should rather create a new vector containing the elements to insert, split the vector at the insertion point, and append the left hand, the new vector and the right hand in order.

Time: O(log n)

Source

pub fn remove(&mut self, index: usize) -> A

Remove an element from a vector.

Remove the element from position ‘index’, shifting all elements after it to the left, and return the removed element.

§Performance Note

While pop_front and pop_back are heavily optimised operations, remove in the middle of a vector requires a split, a pop, and an append. Thus, if you want to remove many elements from the same location, instead of removeing them one by one, it is much better to use slice.

Time: O(log n)

Examples found in repository?
examples/tabs.rs (line 54)
49    fn remove_tab(&mut self, idx: usize) {
50        if idx >= self.tab_labels.len() {
51            tracing::warn!("Attempt to remove non existent tab at index {}", idx)
52        } else {
53            self.removed_tabs += 1;
54            self.tab_labels.remove(idx);
55        }
56    }
Source

pub fn insert_ord(&mut self, item: A)
where A: Ord,

Insert an element into a sorted vector.

Insert an element into a vector in sorted order, assuming the vector is already in sorted order.

Time: O(log n)

§Examples
let mut vec = vector![1, 2, 3, 7, 8, 9];
vec.insert_ord(5);
assert_eq!(vector![1, 2, 3, 5, 7, 8, 9], vec);
Source

pub fn sort(&mut self)
where A: Ord,

Sort a vector.

Time: O(n log n)

§Examples
let mut vec = vector![3, 2, 5, 4, 1];
vec.sort();
assert_eq!(vector![1, 2, 3, 4, 5], vec);
Source

pub fn sort_by<F>(&mut self, cmp: F)
where F: Fn(&A, &A) -> Ordering,

Sort a vector using a comparator function.

Time: O(n log n)

§Examples
let mut vec = vector![3, 2, 5, 4, 1];
vec.sort_by(|left, right| left.cmp(right));
assert_eq!(vector![1, 2, 3, 4, 5], vec);

Trait Implementations§

Source§

impl<'a, A> Add for &'a Vector<A>
where A: Clone,

Source§

fn add(self, other: &'a Vector<A>) -> <&'a Vector<A> as Add>::Output

Concatenate two vectors.

Time: O(log n)

Source§

type Output = Vector<A>

The resulting type after applying the + operator.
Source§

impl<A> Add for Vector<A>
where A: Clone,

Source§

fn add(self, other: Vector<A>) -> <Vector<A> as Add>::Output

Concatenate two vectors.

Time: O(log n)

Source§

type Output = Vector<A>

The resulting type after applying the + operator.
Source§

impl<A> Clone for Vector<A>
where A: Clone,

Source§

fn clone(&self) -> Vector<A>

Clone a vector.

Time: O(1), or O(n) with a very small, bounded n for an inline vector.

1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl<T: Data> Data for Vector<T>

Source§

fn same(&self, other: &Self) -> bool

Determine whether two values are the same. Read more
Source§

impl<A> Debug for Vector<A>
where A: Clone + Debug,

Source§

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

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

impl<A> Default for Vector<A>
where A: Clone,

Source§

fn default() -> Vector<A>

Returns the “default value” for a type. Read more
Source§

impl<A> Extend<A> for Vector<A>
where A: Clone,

Source§

fn extend<I>(&mut self, iter: I)
where I: IntoIterator<Item = A>,

Add values to the end of a vector by consuming an iterator.

Time: O(n)

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<'a, A> From<&'a [A]> for Vector<A>
where A: Clone,

Source§

fn from(slice: &[A]) -> Vector<A>

Converts to this type from the input type.
Source§

impl<'a, A> From<&'a Vec<A>> for Vector<A>
where A: Clone,

Source§

fn from(vec: &Vec<A>) -> Vector<A>

Create a vector from a std::vec::Vec.

Time: O(n)

Source§

impl<'s, 'a, A, OA> From<&'s Vector<&'a A>> for Vector<OA>
where A: ToOwned<Owned = OA>, OA: Borrow<A> + Clone,

Source§

fn from(vec: &Vector<&A>) -> Vector<OA>

Converts to this type from the input type.
Source§

impl<'a, A, S> From<&'a Vector<A>> for HashSet<A, S>
where A: Hash + Eq + Clone, S: BuildHasher + Default,

Source§

fn from(vector: &Vector<A>) -> HashSet<A, S>

Converts to this type from the input type.
Source§

impl<A> From<Vec<A>> for Vector<A>
where A: Clone,

Source§

fn from(vec: Vec<A>) -> Vector<A>

Create a vector from a std::vec::Vec.

Time: O(n)

Source§

impl<A, S> From<Vector<A>> for HashSet<A, S>
where A: Hash + Eq + Clone, S: BuildHasher + Default,

Source§

fn from(vector: Vector<A>) -> HashSet<A, S>

Converts to this type from the input type.
Source§

impl<A> FromIterator<A> for Vector<A>
where A: Clone,

Source§

fn from_iter<I>(iter: I) -> Vector<A>
where I: IntoIterator<Item = A>,

Create a vector from an iterator.

Time: O(n)

Source§

impl<A> Hash for Vector<A>
where A: Clone + Hash,

Source§

fn hash<H>(&self, state: &mut H)
where H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<A> Index<usize> for Vector<A>
where A: Clone,

Source§

fn index(&self, index: usize) -> &<Vector<A> as Index<usize>>::Output

Get a reference to the value at index index in the vector.

Time: O(log n)

Source§

type Output = A

The returned type after indexing.
Source§

impl<A> IndexMut<usize> for Vector<A>
where A: Clone,

Source§

fn index_mut( &mut self, index: usize, ) -> &mut <Vector<A> as Index<usize>>::Output

Get a mutable reference to the value at index index in the vector.

Time: O(log n)

Source§

impl<'a, A> IntoIterator for &'a Vector<A>
where A: Clone,

Source§

type Item = &'a A

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, A>

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

fn into_iter(self) -> <&'a Vector<A> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
Source§

impl<A> IntoIterator for Vector<A>
where A: Clone,

Source§

type Item = A

The type of the elements being iterated over.
Source§

type IntoIter = ConsumingIter<A>

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

fn into_iter(self) -> <Vector<A> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
Source§

impl<T: Data> ListIter<T> for Vector<T>

Source§

fn for_each(&self, cb: impl FnMut(&T, usize))

Iterate over each data child.
Source§

fn for_each_mut(&mut self, cb: impl FnMut(&mut T, usize))

Iterate over each data child. Keep track of changed data and update self.
Source§

fn data_len(&self) -> usize

Return data length.
Source§

impl<A> Ord for Vector<A>
where A: Clone + Ord,

Source§

fn cmp(&self, other: &Vector<A>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<A> PartialEq for Vector<A>
where A: Clone + PartialEq,

Source§

default fn eq(&self, other: &Vector<A>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<A> PartialEq for Vector<A>
where A: Clone + Eq,

Source§

fn eq(&self, other: &Vector<A>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<A> PartialOrd for Vector<A>
where A: Clone + PartialOrd,

Source§

fn partial_cmp(&self, other: &Vector<A>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<A> Sum for Vector<A>
where A: Clone,

Source§

fn sum<I>(it: I) -> Vector<A>
where I: Iterator<Item = Vector<A>>,

Takes an iterator and generates Self from the elements by “summing up” the items.
Source§

impl<A> Eq for Vector<A>
where A: Clone + Eq,

Auto Trait Implementations§

§

impl<A> Freeze for Vector<A>

§

impl<A> RefUnwindSafe for Vector<A>
where A: RefUnwindSafe,

§

impl<A> Send for Vector<A>
where A: Send + Sync,

§

impl<A> Sync for Vector<A>
where A: Sync + Send,

§

impl<A> Unpin for Vector<A>
where A: Unpin,

§

impl<A> UnwindSafe for Vector<A>

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> AnyEq for T
where T: Any + PartialEq,

Source§

fn equals(&self, other: &(dyn Any + 'static)) -> bool

Source§

fn as_any(&self) -> &(dyn Any + 'static)

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> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> RoundFrom<T> for T

Source§

fn round_from(x: T) -> T

Performs the conversion.
Source§

impl<T, U> RoundInto<U> for T
where U: RoundFrom<T>,

Source§

fn round_into(self) -> U

Performs the conversion.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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<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.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more