pub struct BoxShadow(pub Vec<ShadowStyle>);
Expand description
List of shadows to draw for a Node
.
Draw order is determined implicitly from the vector of ShadowStyle
s, back-to-front.
Tuple Fields§
§0: Vec<ShadowStyle>
Implementations§
Source§impl BoxShadow
impl BoxShadow
Sourcepub fn new(
color: Color,
x_offset: Val,
y_offset: Val,
spread_radius: Val,
blur_radius: Val,
) -> BoxShadow
pub fn new( color: Color, x_offset: Val, y_offset: Val, spread_radius: Val, blur_radius: Val, ) -> BoxShadow
A single drop shadow
Examples found in repository?
242fn box_shadow_node_bundle(
243 size: Vec2,
244 offset: Vec2,
245 spread: f32,
246 blur: f32,
247 border_radius: BorderRadius,
248) -> impl Bundle {
249 (
250 Node {
251 width: Val::Px(size.x),
252 height: Val::Px(size.y),
253 border: UiRect::all(Val::Px(4.)),
254 ..default()
255 },
256 BorderColor(LIGHT_SKY_BLUE.into()),
257 border_radius,
258 BackgroundColor(DEEP_SKY_BLUE.into()),
259 BoxShadow::new(
260 Color::BLACK.with_alpha(0.8),
261 Val::Percent(offset.x),
262 Val::Percent(offset.y),
263 Val::Percent(spread),
264 Val::Px(blur),
265 ),
266 )
267}
More examples
262 pub fn setup(mut commands: Commands) {
263 commands.spawn((Camera2d, StateScoped(super::Scene::BoxShadow)));
264
265 commands
266 .spawn((
267 Node {
268 width: Val::Percent(100.0),
269 height: Val::Percent(100.0),
270 padding: UiRect::all(Val::Px(30.)),
271 column_gap: Val::Px(200.),
272 flex_wrap: FlexWrap::Wrap,
273 ..default()
274 },
275 BackgroundColor(GREEN.into()),
276 StateScoped(super::Scene::BoxShadow),
277 ))
278 .with_children(|commands| {
279 let example_nodes = [
280 (
281 Vec2::splat(100.),
282 Vec2::ZERO,
283 10.,
284 0.,
285 BorderRadius::bottom_right(Val::Px(10.)),
286 ),
287 (Vec2::new(200., 50.), Vec2::ZERO, 10., 0., BorderRadius::MAX),
288 (
289 Vec2::new(100., 50.),
290 Vec2::ZERO,
291 10.,
292 10.,
293 BorderRadius::ZERO,
294 ),
295 (
296 Vec2::splat(100.),
297 Vec2::splat(20.),
298 10.,
299 10.,
300 BorderRadius::bottom_right(Val::Px(10.)),
301 ),
302 (
303 Vec2::splat(100.),
304 Vec2::splat(50.),
305 0.,
306 10.,
307 BorderRadius::ZERO,
308 ),
309 (
310 Vec2::new(50., 100.),
311 Vec2::splat(10.),
312 0.,
313 10.,
314 BorderRadius::MAX,
315 ),
316 ];
317
318 for (size, offset, spread, blur, border_radius) in example_nodes {
319 commands.spawn((
320 Node {
321 width: Val::Px(size.x),
322 height: Val::Px(size.y),
323 border: UiRect::all(Val::Px(2.)),
324 ..default()
325 },
326 BorderColor(WHITE.into()),
327 border_radius,
328 BackgroundColor(BLUE.into()),
329 BoxShadow::new(
330 Color::BLACK.with_alpha(0.9),
331 Val::Percent(offset.x),
332 Val::Percent(offset.y),
333 Val::Percent(spread),
334 Val::Px(blur),
335 ),
336 ));
337 }
338 });
339 }
Methods from Deref<Target = Vec<ShadowStyle>>§
1.0.0 · Sourcepub fn capacity(&self) -> usize
pub fn capacity(&self) -> usize
Returns the total number of elements the vector can hold without reallocating.
§Examples
let mut vec: Vec<i32> = Vec::with_capacity(10);
vec.push(42);
assert!(vec.capacity() >= 10);
A vector with zero-sized elements will always have a capacity of usize::MAX:
#[derive(Clone)]
struct ZeroSized;
fn main() {
assert_eq!(std::mem::size_of::<ZeroSized>(), 0);
let v = vec![ZeroSized; 0];
assert_eq!(v.capacity(), usize::MAX);
}
1.0.0 · Sourcepub fn reserve(&mut self, additional: usize)
pub fn reserve(&mut self, additional: usize)
Reserves capacity for at least additional
more elements to be inserted
in the given Vec<T>
. The collection may reserve more space to
speculatively avoid frequent reallocations. After calling reserve
,
capacity will be greater than or equal to self.len() + additional
.
Does nothing if capacity is already sufficient.
§Panics
Panics if the new capacity exceeds isize::MAX
bytes.
§Examples
let mut vec = vec![1];
vec.reserve(10);
assert!(vec.capacity() >= 11);
1.0.0 · Sourcepub fn reserve_exact(&mut self, additional: usize)
pub fn reserve_exact(&mut self, additional: usize)
Reserves the minimum capacity for at least additional
more elements to
be inserted in the given Vec<T>
. Unlike reserve
, this will not
deliberately over-allocate to speculatively avoid frequent allocations.
After calling reserve_exact
, capacity will be greater than or equal to
self.len() + additional
. Does nothing if the capacity is already
sufficient.
Note that the allocator may give the collection more space than it
requests. Therefore, capacity can not be relied upon to be precisely
minimal. Prefer reserve
if future insertions are expected.
§Panics
Panics if the new capacity exceeds isize::MAX
bytes.
§Examples
let mut vec = vec![1];
vec.reserve_exact(10);
assert!(vec.capacity() >= 11);
1.57.0 · Sourcepub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
Tries to reserve capacity for at least additional
more elements to be inserted
in the given Vec<T>
. The collection may reserve more space to speculatively avoid
frequent reallocations. After calling try_reserve
, capacity will be
greater than or equal to self.len() + additional
if it returns
Ok(())
. Does nothing if capacity is already sufficient. This method
preserves the contents even if an error occurs.
§Errors
If the capacity overflows, or the allocator reports a failure, then an error is returned.
§Examples
use std::collections::TryReserveError;
fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
let mut output = Vec::new();
// Pre-reserve the memory, exiting if we can't
output.try_reserve(data.len())?;
// Now we know this can't OOM in the middle of our complex work
output.extend(data.iter().map(|&val| {
val * 2 + 5 // very complicated
}));
Ok(output)
}
1.57.0 · Sourcepub fn try_reserve_exact(
&mut self,
additional: usize,
) -> Result<(), TryReserveError>
pub fn try_reserve_exact( &mut self, additional: usize, ) -> Result<(), TryReserveError>
Tries to reserve the minimum capacity for at least additional
elements to be inserted in the given Vec<T>
. Unlike try_reserve
,
this will not deliberately over-allocate to speculatively avoid frequent
allocations. After calling try_reserve_exact
, capacity will be greater
than or equal to self.len() + additional
if it returns Ok(())
.
Does nothing if the capacity is already sufficient.
Note that the allocator may give the collection more space than it
requests. Therefore, capacity can not be relied upon to be precisely
minimal. Prefer try_reserve
if future insertions are expected.
§Errors
If the capacity overflows, or the allocator reports a failure, then an error is returned.
§Examples
use std::collections::TryReserveError;
fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
let mut output = Vec::new();
// Pre-reserve the memory, exiting if we can't
output.try_reserve_exact(data.len())?;
// Now we know this can't OOM in the middle of our complex work
output.extend(data.iter().map(|&val| {
val * 2 + 5 // very complicated
}));
Ok(output)
}
1.0.0 · Sourcepub fn shrink_to_fit(&mut self)
pub fn shrink_to_fit(&mut self)
Shrinks the capacity of the vector as much as possible.
The behavior of this method depends on the allocator, which may either shrink the vector
in-place or reallocate. The resulting vector might still have some excess capacity, just as
is the case for with_capacity
. See Allocator::shrink
for more details.
§Examples
let mut vec = Vec::with_capacity(10);
vec.extend([1, 2, 3]);
assert!(vec.capacity() >= 10);
vec.shrink_to_fit();
assert!(vec.capacity() >= 3);
1.56.0 · Sourcepub fn shrink_to(&mut self, min_capacity: usize)
pub fn shrink_to(&mut self, min_capacity: usize)
Shrinks the capacity of the vector with a lower bound.
The capacity will remain at least as large as both the length and the supplied value.
If the current capacity is less than the lower limit, this is a no-op.
§Examples
let mut vec = Vec::with_capacity(10);
vec.extend([1, 2, 3]);
assert!(vec.capacity() >= 10);
vec.shrink_to(4);
assert!(vec.capacity() >= 4);
vec.shrink_to(0);
assert!(vec.capacity() >= 3);
1.0.0 · Sourcepub fn truncate(&mut self, len: usize)
pub fn truncate(&mut self, len: usize)
Shortens the vector, keeping the first len
elements and dropping
the rest.
If len
is greater or equal to the vector’s current length, this has
no effect.
The drain
method can emulate truncate
, but causes the excess
elements to be returned instead of dropped.
Note that this method has no effect on the allocated capacity of the vector.
§Examples
Truncating a five element vector to two elements:
let mut vec = vec![1, 2, 3, 4, 5];
vec.truncate(2);
assert_eq!(vec, [1, 2]);
No truncation occurs when len
is greater than the vector’s current
length:
let mut vec = vec![1, 2, 3];
vec.truncate(8);
assert_eq!(vec, [1, 2, 3]);
Truncating when len == 0
is equivalent to calling the clear
method.
let mut vec = vec![1, 2, 3];
vec.truncate(0);
assert_eq!(vec, []);
1.7.0 · Sourcepub fn as_slice(&self) -> &[T]
pub fn as_slice(&self) -> &[T]
Extracts a slice containing the entire vector.
Equivalent to &s[..]
.
§Examples
use std::io::{self, Write};
let buffer = vec![1, 2, 3, 5, 8];
io::sink().write(buffer.as_slice()).unwrap();
Examples found in repository?
181fn prepare_instance_buffers(
182 mut commands: Commands,
183 query: Query<(Entity, &InstanceMaterialData)>,
184 render_device: Res<RenderDevice>,
185) {
186 for (entity, instance_data) in &query {
187 let buffer = render_device.create_buffer_with_data(&BufferInitDescriptor {
188 label: Some("instance data buffer"),
189 contents: bytemuck::cast_slice(instance_data.as_slice()),
190 usage: BufferUsages::VERTEX | BufferUsages::COPY_DST,
191 });
192 commands.entity(entity).insert(InstanceBuffer {
193 buffer,
194 length: instance_data.len(),
195 });
196 }
197}
More examples
70fn update(
71 time: Res<Time>,
72 material_handles: Res<CustomMaterialHandle>,
73 mut materials: ResMut<Assets<CustomMaterial>>,
74 mut buffers: ResMut<Assets<ShaderStorageBuffer>>,
75) {
76 let material = materials.get_mut(&material_handles.0).unwrap();
77
78 let buffer = buffers.get_mut(&material.colors).unwrap();
79 buffer.set_data(
80 (0..5)
81 .map(|i| {
82 let t = time.elapsed_secs() * 5.0;
83 [
84 ops::sin(t + i as f32) / 2.0 + 0.5,
85 ops::sin(t + i as f32 + 2.0) / 2.0 + 0.5,
86 ops::sin(t + i as f32 + 4.0) / 2.0 + 0.5,
87 1.0,
88 ]
89 })
90 .collect::<Vec<[f32; 4]>>()
91 .as_slice(),
92 );
93}
43 async fn load(
44 &self,
45 reader: &mut dyn Reader,
46 _settings: &(),
47 load_context: &mut LoadContext<'_>,
48 ) -> Result<Self::Asset, Self::Error> {
49 let compressed_path = load_context.path();
50 let file_name = compressed_path
51 .file_name()
52 .ok_or(GzAssetLoaderError::IndeterminateFilePath)?
53 .to_string_lossy();
54 let uncompressed_file_name = file_name
55 .strip_suffix(".gz")
56 .ok_or(GzAssetLoaderError::IndeterminateFilePath)?;
57 let contained_path = compressed_path.join(uncompressed_file_name);
58
59 let mut bytes_compressed = Vec::new();
60
61 reader.read_to_end(&mut bytes_compressed).await?;
62
63 let mut decoder = GzDecoder::new(bytes_compressed.as_slice());
64
65 let mut bytes_uncompressed = Vec::new();
66
67 decoder.read_to_end(&mut bytes_uncompressed)?;
68
69 // Now that we have decompressed the asset, let's pass it back to the
70 // context to continue loading
71
72 let mut reader = VecReader::new(bytes_uncompressed);
73
74 let uncompressed = load_context
75 .loader()
76 .with_unknown_type()
77 .immediate()
78 .with_reader(&mut reader)
79 .load(contained_path)
80 .await?;
81
82 Ok(GzAsset { uncompressed })
83 }
1.7.0 · Sourcepub fn as_mut_slice(&mut self) -> &mut [T]
pub fn as_mut_slice(&mut self) -> &mut [T]
Extracts a mutable slice of the entire vector.
Equivalent to &mut s[..]
.
§Examples
use std::io::{self, Read};
let mut buffer = vec![0; 3];
io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
1.37.0 · Sourcepub fn as_ptr(&self) -> *const T
pub fn as_ptr(&self) -> *const T
Returns a raw pointer to the vector’s buffer, or a dangling raw pointer valid for zero sized reads if the vector didn’t allocate.
The caller must ensure that the vector outlives the pointer this function returns, or else it will end up dangling. Modifying the vector may cause its buffer to be reallocated, which would also make any pointers to it invalid.
The caller must also ensure that the memory the pointer (non-transitively) points to
is never written to (except inside an UnsafeCell
) using this pointer or any pointer
derived from it. If you need to mutate the contents of the slice, use as_mut_ptr
.
This method guarantees that for the purpose of the aliasing model, this method
does not materialize a reference to the underlying slice, and thus the returned pointer
will remain valid when mixed with other calls to as_ptr
, as_mut_ptr
,
and as_non_null
.
Note that calling other methods that materialize mutable references to the slice,
or mutable references to specific elements you are planning on accessing through this pointer,
as well as writing to those elements, may still invalidate this pointer.
See the second example below for how this guarantee can be used.
§Examples
let x = vec![1, 2, 4];
let x_ptr = x.as_ptr();
unsafe {
for i in 0..x.len() {
assert_eq!(*x_ptr.add(i), 1 << i);
}
}
Due to the aliasing guarantee, the following code is legal:
unsafe {
let mut v = vec![0, 1, 2];
let ptr1 = v.as_ptr();
let _ = ptr1.read();
let ptr2 = v.as_mut_ptr().offset(2);
ptr2.write(2);
// Notably, the write to `ptr2` did *not* invalidate `ptr1`
// because it mutated a different element:
let _ = ptr1.read();
}
1.37.0 · Sourcepub fn as_mut_ptr(&mut self) -> *mut T
pub fn as_mut_ptr(&mut self) -> *mut T
Returns a raw mutable pointer to the vector’s buffer, or a dangling raw pointer valid for zero sized reads if the vector didn’t allocate.
The caller must ensure that the vector outlives the pointer this function returns, or else it will end up dangling. Modifying the vector may cause its buffer to be reallocated, which would also make any pointers to it invalid.
This method guarantees that for the purpose of the aliasing model, this method
does not materialize a reference to the underlying slice, and thus the returned pointer
will remain valid when mixed with other calls to as_ptr
, as_mut_ptr
,
and as_non_null
.
Note that calling other methods that materialize references to the slice,
or references to specific elements you are planning on accessing through this pointer,
may still invalidate this pointer.
See the second example below for how this guarantee can be used.
§Examples
// Allocate vector big enough for 4 elements.
let size = 4;
let mut x: Vec<i32> = Vec::with_capacity(size);
let x_ptr = x.as_mut_ptr();
// Initialize elements via raw pointer writes, then set length.
unsafe {
for i in 0..size {
*x_ptr.add(i) = i as i32;
}
x.set_len(size);
}
assert_eq!(&*x, &[0, 1, 2, 3]);
Due to the aliasing guarantee, the following code is legal:
unsafe {
let mut v = vec![0];
let ptr1 = v.as_mut_ptr();
ptr1.write(1);
let ptr2 = v.as_mut_ptr();
ptr2.write(2);
// Notably, the write to `ptr2` did *not* invalidate `ptr1`:
ptr1.write(3);
}
Examples found in repository?
200fn to_owning_ptrs(components: &mut [Vec<u64>]) -> Vec<OwningPtr<Aligned>> {
201 components
202 .iter_mut()
203 .map(|data| {
204 let ptr = data.as_mut_ptr();
205 // SAFETY:
206 // - Pointers are guaranteed to be non-null
207 // - Memory pointed to won't be dropped until `components` is dropped
208 unsafe {
209 let non_null = NonNull::new_unchecked(ptr.cast());
210 OwningPtr::new(non_null)
211 }
212 })
213 .collect()
214}
Sourcepub fn as_non_null(&mut self) -> NonNull<T>
🔬This is a nightly-only experimental API. (box_vec_non_null
)
pub fn as_non_null(&mut self) -> NonNull<T>
box_vec_non_null
)Returns a NonNull
pointer to the vector’s buffer, or a dangling
NonNull
pointer valid for zero sized reads if the vector didn’t allocate.
The caller must ensure that the vector outlives the pointer this function returns, or else it will end up dangling. Modifying the vector may cause its buffer to be reallocated, which would also make any pointers to it invalid.
This method guarantees that for the purpose of the aliasing model, this method
does not materialize a reference to the underlying slice, and thus the returned pointer
will remain valid when mixed with other calls to as_ptr
, as_mut_ptr
,
and as_non_null
.
Note that calling other methods that materialize references to the slice,
or references to specific elements you are planning on accessing through this pointer,
may still invalidate this pointer.
See the second example below for how this guarantee can be used.
§Examples
#![feature(box_vec_non_null)]
// Allocate vector big enough for 4 elements.
let size = 4;
let mut x: Vec<i32> = Vec::with_capacity(size);
let x_ptr = x.as_non_null();
// Initialize elements via raw pointer writes, then set length.
unsafe {
for i in 0..size {
x_ptr.add(i).write(i as i32);
}
x.set_len(size);
}
assert_eq!(&*x, &[0, 1, 2, 3]);
Due to the aliasing guarantee, the following code is legal:
#![feature(box_vec_non_null)]
unsafe {
let mut v = vec![0];
let ptr1 = v.as_non_null();
ptr1.write(1);
let ptr2 = v.as_non_null();
ptr2.write(2);
// Notably, the write to `ptr2` did *not* invalidate `ptr1`:
ptr1.write(3);
}
Sourcepub fn allocator(&self) -> &A
🔬This is a nightly-only experimental API. (allocator_api
)
pub fn allocator(&self) -> &A
allocator_api
)Returns a reference to the underlying allocator.
1.0.0 · Sourcepub unsafe fn set_len(&mut self, new_len: usize)
pub unsafe fn set_len(&mut self, new_len: usize)
Forces the length of the vector to new_len
.
This is a low-level operation that maintains none of the normal
invariants of the type. Normally changing the length of a vector
is done using one of the safe operations instead, such as
truncate
, resize
, extend
, or clear
.
§Safety
new_len
must be less than or equal tocapacity()
.- The elements at
old_len..new_len
must be initialized.
§Examples
See spare_capacity_mut()
for an example with safe
initialization of capacity elements and use of this method.
set_len()
can be useful for situations in which the vector
is serving as a buffer for other code, particularly over FFI:
pub fn get_dictionary(&self) -> Option<Vec<u8>> {
// Per the FFI method's docs, "32768 bytes is always enough".
let mut dict = Vec::with_capacity(32_768);
let mut dict_length = 0;
// SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
// 1. `dict_length` elements were initialized.
// 2. `dict_length` <= the capacity (32_768)
// which makes `set_len` safe to call.
unsafe {
// Make the FFI call...
let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
if r == Z_OK {
// ...and update the length to what was initialized.
dict.set_len(dict_length);
Some(dict)
} else {
None
}
}
}
While the following example is sound, there is a memory leak since
the inner vectors were not freed prior to the set_len
call:
let mut vec = vec![vec![1, 0, 0],
vec![0, 1, 0],
vec![0, 0, 1]];
// SAFETY:
// 1. `old_len..0` is empty so no elements need to be initialized.
// 2. `0 <= capacity` always holds whatever `capacity` is.
unsafe {
vec.set_len(0);
}
Normally, here, one would use clear
instead to correctly drop
the contents and thus not leak memory.
1.0.0 · Sourcepub fn swap_remove(&mut self, index: usize) -> T
pub fn swap_remove(&mut self, index: usize) -> T
Removes an element from the vector and returns it.
The removed element is replaced by the last element of the vector.
This does not preserve ordering of the remaining elements, but is O(1).
If you need to preserve the element order, use remove
instead.
§Panics
Panics if index
is out of bounds.
§Examples
let mut v = vec!["foo", "bar", "baz", "qux"];
assert_eq!(v.swap_remove(1), "bar");
assert_eq!(v, ["foo", "qux", "baz"]);
assert_eq!(v.swap_remove(0), "foo");
assert_eq!(v, ["baz", "qux"]);
1.0.0 · Sourcepub fn insert(&mut self, index: usize, element: T)
pub fn insert(&mut self, index: usize, element: T)
Inserts an element at position index
within the vector, shifting all
elements after it to the right.
§Panics
Panics if index > len
.
§Examples
let mut vec = vec!['a', 'b', 'c'];
vec.insert(1, 'd');
assert_eq!(vec, ['a', 'd', 'b', 'c']);
vec.insert(4, 'e');
assert_eq!(vec, ['a', 'd', 'b', 'c', 'e']);
§Time complexity
Takes O(Vec::len
) time. All items after the insertion index must be
shifted to the right. In the worst case, all elements are shifted when
the insertion index is 0.
1.0.0 · Sourcepub fn remove(&mut self, index: usize) -> T
pub fn remove(&mut self, index: usize) -> T
Removes and returns the element at position index
within the vector,
shifting all elements after it to the left.
Note: Because this shifts over the remaining elements, it has a
worst-case performance of O(n). If you don’t need the order of elements
to be preserved, use swap_remove
instead. If you’d like to remove
elements from the beginning of the Vec
, consider using
VecDeque::pop_front
instead.
§Panics
Panics if index
is out of bounds.
§Examples
let mut v = vec!['a', 'b', 'c'];
assert_eq!(v.remove(1), 'b');
assert_eq!(v, ['a', 'c']);
1.0.0 · Sourcepub fn retain<F>(&mut self, f: F)
pub fn retain<F>(&mut self, f: F)
Retains only the elements specified by the predicate.
In other words, remove all elements e
for which f(&e)
returns false
.
This method operates in place, visiting each element exactly once in the
original order, and preserves the order of the retained elements.
§Examples
let mut vec = vec![1, 2, 3, 4];
vec.retain(|&x| x % 2 == 0);
assert_eq!(vec, [2, 4]);
Because the elements are visited exactly once in the original order, external state may be used to decide which elements to keep.
let mut vec = vec![1, 2, 3, 4, 5];
let keep = [false, true, true, false, true];
let mut iter = keep.iter();
vec.retain(|_| *iter.next().unwrap());
assert_eq!(vec, [2, 3, 5]);
Examples found in repository?
196fn update_loading_data(
197 mut loading_data: ResMut<LoadingData>,
198 mut loading_state: ResMut<LoadingState>,
199 asset_server: Res<AssetServer>,
200 pipelines_ready: Res<PipelinesReady>,
201) {
202 if !loading_data.loading_assets.is_empty() || !pipelines_ready.0 {
203 // If we are still loading assets / pipelines are not fully compiled,
204 // we reset the confirmation frame count.
205 loading_data.confirmation_frames_count = 0;
206
207 loading_data.loading_assets.retain(|asset| {
208 asset_server
209 .get_recursive_dependency_load_state(asset)
210 .is_none_or(|state| !state.is_loaded())
211 });
212
213 // If there are no more assets being monitored, and pipelines
214 // are compiled, then start counting confirmation frames.
215 // Once enough confirmations have passed, everything will be
216 // considered to be fully loaded.
217 } else {
218 loading_data.confirmation_frames_count += 1;
219 if loading_data.confirmation_frames_count == loading_data.confirmation_frames_target {
220 *loading_state = LoadingState::LevelReady;
221 }
222 }
223}
1.61.0 · Sourcepub fn retain_mut<F>(&mut self, f: F)
pub fn retain_mut<F>(&mut self, f: F)
Retains only the elements specified by the predicate, passing a mutable reference to it.
In other words, remove all elements e
such that f(&mut e)
returns false
.
This method operates in place, visiting each element exactly once in the
original order, and preserves the order of the retained elements.
§Examples
let mut vec = vec![1, 2, 3, 4];
vec.retain_mut(|x| if *x <= 3 {
*x += 1;
true
} else {
false
});
assert_eq!(vec, [2, 3, 4]);
1.16.0 · Sourcepub fn dedup_by_key<F, K>(&mut self, key: F)
pub fn dedup_by_key<F, K>(&mut self, key: F)
Removes all but the first of consecutive elements in the vector that resolve to the same key.
If the vector is sorted, this removes all duplicates.
§Examples
let mut vec = vec![10, 20, 21, 30, 20];
vec.dedup_by_key(|i| *i / 10);
assert_eq!(vec, [10, 20, 30, 20]);
1.16.0 · Sourcepub fn dedup_by<F>(&mut self, same_bucket: F)
pub fn dedup_by<F>(&mut self, same_bucket: F)
Removes all but the first of consecutive elements in the vector satisfying a given equality relation.
The same_bucket
function is passed references to two elements from the vector and
must determine if the elements compare equal. The elements are passed in opposite order
from their order in the slice, so if same_bucket(a, b)
returns true
, a
is removed.
If the vector is sorted, this removes all duplicates.
§Examples
let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1.0.0 · Sourcepub fn push(&mut self, value: T)
pub fn push(&mut self, value: T)
Appends an element to the back of a collection.
§Panics
Panics if the new capacity exceeds isize::MAX
bytes.
§Examples
let mut vec = vec![1, 2];
vec.push(3);
assert_eq!(vec, [1, 2, 3]);
§Time complexity
Takes amortized O(1) time. If the vector’s length would exceed its capacity after the push, O(capacity) time is taken to copy the vector’s elements to a larger allocation. This expensive operation is offset by the capacity O(1) insertions it allows.
Examples found in repository?
22 pub fn add_schedule(mut self, label: impl ScheduleLabel) -> SteppingPlugin {
23 self.schedule_labels.push(label.intern());
24 self
25 }
26
27 /// Set the location of the stepping UI when activated
28 pub fn at(self, left: Val, top: Val) -> SteppingPlugin {
29 SteppingPlugin { top, left, ..self }
30 }
31}
32
33impl Plugin for SteppingPlugin {
34 fn build(&self, app: &mut App) {
35 app.add_systems(Startup, build_stepping_hint);
36 if cfg!(not(feature = "bevy_debug_stepping")) {
37 return;
38 }
39
40 // create and insert our debug schedule into the main schedule order.
41 // We need an independent schedule so we have access to all other
42 // schedules through the `Stepping` resource
43 app.init_schedule(DebugSchedule);
44 let mut order = app.world_mut().resource_mut::<MainScheduleOrder>();
45 order.insert_after(Update, DebugSchedule);
46
47 // create our stepping resource
48 let mut stepping = Stepping::new();
49 for label in &self.schedule_labels {
50 stepping.add_schedule(*label);
51 }
52 app.insert_resource(stepping);
53
54 // add our startup & stepping systems
55 app.insert_resource(State {
56 ui_top: self.top,
57 ui_left: self.left,
58 systems: Vec::new(),
59 })
60 .add_systems(
61 DebugSchedule,
62 (
63 build_ui.run_if(not(initialized)),
64 handle_input,
65 update_ui.run_if(initialized),
66 )
67 .chain(),
68 );
69 }
70}
71
72/// Struct for maintaining stepping state
73#[derive(Resource, Debug)]
74struct State {
75 // vector of schedule/node id -> text index offset
76 systems: Vec<(InternedScheduleLabel, NodeId, usize)>,
77
78 // ui positioning
79 ui_top: Val,
80 ui_left: Val,
81}
82
83/// condition to check if the stepping UI has been constructed
84fn initialized(state: Res<State>) -> bool {
85 !state.systems.is_empty()
86}
87
88const FONT_COLOR: Color = Color::srgb(0.2, 0.2, 0.2);
89const FONT_BOLD: &str = "fonts/FiraSans-Bold.ttf";
90
91#[derive(Component)]
92struct SteppingUi;
93
94/// Construct the stepping UI elements from the [`Schedules`] resource.
95///
96/// This system may run multiple times before constructing the UI as all of the
97/// data may not be available on the first run of the system. This happens if
98/// one of the stepping schedules has not yet been run.
99fn build_ui(
100 mut commands: Commands,
101 asset_server: Res<AssetServer>,
102 schedules: Res<Schedules>,
103 mut stepping: ResMut<Stepping>,
104 mut state: ResMut<State>,
105) {
106 let mut text_spans = Vec::new();
107 let mut always_run = Vec::new();
108
109 let Ok(schedule_order) = stepping.schedules() else {
110 return;
111 };
112
113 // go through the stepping schedules and construct a list of systems for
114 // each label
115 for label in schedule_order {
116 let schedule = schedules.get(*label).unwrap();
117 text_spans.push((
118 TextSpan(format!("{label:?}\n")),
119 TextFont {
120 font: asset_server.load(FONT_BOLD),
121 ..default()
122 },
123 TextColor(FONT_COLOR),
124 ));
125
126 // grab the list of systems in the schedule, in the order the
127 // single-threaded executor would run them.
128 let Ok(systems) = schedule.systems() else {
129 return;
130 };
131
132 for (node_id, system) in systems {
133 // skip bevy default systems; we don't want to step those
134 if system.name().starts_with("bevy") {
135 always_run.push((*label, node_id));
136 continue;
137 }
138
139 // Add an entry to our systems list so we can find where to draw
140 // the cursor when the stepping cursor is at this system
141 // we add plus 1 to account for the empty root span
142 state.systems.push((*label, node_id, text_spans.len() + 1));
143
144 // Add a text section for displaying the cursor for this system
145 text_spans.push((
146 TextSpan::new(" "),
147 TextFont::default(),
148 TextColor(FONT_COLOR),
149 ));
150
151 // add the name of the system to the ui
152 text_spans.push((
153 TextSpan(format!("{}\n", system.name())),
154 TextFont::default(),
155 TextColor(FONT_COLOR),
156 ));
157 }
158 }
159
160 for (label, node) in always_run.drain(..) {
161 stepping.always_run_node(label, node);
162 }
163
164 commands.spawn((
165 Text::default(),
166 SteppingUi,
167 Node {
168 position_type: PositionType::Absolute,
169 top: state.ui_top,
170 left: state.ui_left,
171 padding: UiRect::all(Val::Px(10.0)),
172 ..default()
173 },
174 BackgroundColor(Color::srgba(1.0, 1.0, 1.0, 0.33)),
175 Visibility::Hidden,
176 Children::spawn(text_spans),
177 ));
178}
More examples
63 fn specialize(
64 _pipeline: &MaterialPipeline<Self>,
65 descriptor: &mut RenderPipelineDescriptor,
66 _layout: &MeshVertexBufferLayoutRef,
67 key: MaterialPipelineKey<Self>,
68 ) -> Result<(), SpecializedMeshPipelineError> {
69 if key.bind_group_data.is_red {
70 let fragment = descriptor.fragment.as_mut().unwrap();
71 fragment.shader_defs.push("IS_RED".into());
72 }
73 Ok(())
74 }
122 fn specialize(
123 _pipeline: &MaterialPipeline<Self>,
124 descriptor: &mut RenderPipelineDescriptor,
125 _layout: &MeshVertexBufferLayoutRef,
126 key: MaterialPipelineKey<Self>,
127 ) -> Result<(), SpecializedMeshPipelineError> {
128 let fragment = descriptor.fragment.as_mut().unwrap();
129 fragment.shader_defs.push(ShaderDefVal::Bool(
130 "PARTY_MODE".to_string(),
131 key.bind_group_data.party_mode,
132 ));
133 Ok(())
134 }
108fn send_and_receive_param_set(
109 mut param_set: ParamSet<(EventReader<DebugEvent>, EventWriter<DebugEvent>)>,
110 frame_count: Res<FrameCount>,
111) {
112 println!(
113 "Sending and receiving events for frame {} with a `ParamSet`",
114 frame_count.0
115 );
116
117 // We must collect the events to resend, because we can't access the writer while we're iterating over the reader.
118 let mut events_to_resend = Vec::new();
119
120 // This is p0, as the first parameter in the `ParamSet` is the reader.
121 for event in param_set.p0().read() {
122 if event.resend_from_param_set {
123 events_to_resend.push(event.clone());
124 }
125 }
126
127 // This is p1, as the second parameter in the `ParamSet` is the writer.
128 for mut event in events_to_resend {
129 event.times_sent += 1;
130 param_set.p1().write(event);
131 }
132}
133
134/// A system that both sends and receives events using a [`Local`] [`EventCursor`].
135fn send_and_receive_manual_event_reader(
136 // The `Local` `SystemParam` stores state inside the system itself, rather than in the world.
137 // `EventCursor<T>` is the internal state of `EventReader<T>`, which tracks which events have been seen.
138 mut local_event_reader: Local<EventCursor<DebugEvent>>,
139 // We can access the `Events` resource mutably, allowing us to both read and write its contents.
140 mut events: ResMut<Events<DebugEvent>>,
141 frame_count: Res<FrameCount>,
142) {
143 println!(
144 "Sending and receiving events for frame {} with a `Local<EventCursor>",
145 frame_count.0
146 );
147
148 // We must collect the events to resend, because we can't mutate events while we're iterating over the events.
149 let mut events_to_resend = Vec::new();
150
151 for event in local_event_reader.read(&events) {
152 if event.resend_from_local_event_reader {
153 // For simplicity, we're cloning the event.
154 // In this case, since we have mutable access to the `Events` resource,
155 // we could also just mutate the event in-place,
156 // or drain the event queue into our `events_to_resend` vector.
157 events_to_resend.push(event.clone());
158 }
159 }
160
161 for mut event in events_to_resend {
162 event.times_sent += 1;
163 events.send(event);
164 }
165}
131fn load_level_1(
132 mut commands: Commands,
133 mut loading_data: ResMut<LoadingData>,
134 asset_server: Res<AssetServer>,
135) {
136 // Spawn the camera.
137 commands.spawn((
138 Camera3d::default(),
139 Transform::from_xyz(155.0, 155.0, 155.0).looking_at(Vec3::new(0.0, 40.0, 0.0), Vec3::Y),
140 LevelComponents,
141 ));
142
143 // Save the asset into the `loading_assets` vector.
144 let fox = asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/animated/Fox.glb"));
145 loading_data.loading_assets.push(fox.clone().into());
146 // Spawn the fox.
147 commands.spawn((
148 SceneRoot(fox.clone()),
149 Transform::from_xyz(0.0, 0.0, 0.0),
150 LevelComponents,
151 ));
152
153 // Spawn the light.
154 commands.spawn((
155 DirectionalLight {
156 shadows_enabled: true,
157 ..default()
158 },
159 Transform::from_xyz(3.0, 3.0, 2.0).looking_at(Vec3::ZERO, Vec3::Y),
160 LevelComponents,
161 ));
162}
163
164fn load_level_2(
165 mut commands: Commands,
166 mut loading_data: ResMut<LoadingData>,
167 asset_server: Res<AssetServer>,
168) {
169 // Spawn the camera.
170 commands.spawn((
171 Camera3d::default(),
172 Transform::from_xyz(1.0, 1.0, 1.0).looking_at(Vec3::new(0.0, 0.2, 0.0), Vec3::Y),
173 LevelComponents,
174 ));
175
176 // Spawn the helmet.
177 let helmet_scene = asset_server
178 .load(GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf"));
179 loading_data
180 .loading_assets
181 .push(helmet_scene.clone().into());
182 commands.spawn((SceneRoot(helmet_scene.clone()), LevelComponents));
183
184 // Spawn the light.
185 commands.spawn((
186 DirectionalLight {
187 shadows_enabled: true,
188 ..default()
189 },
190 Transform::from_xyz(3.0, 3.0, 2.0).looking_at(Vec3::ZERO, Vec3::Y),
191 LevelComponents,
192 ));
193}
48fn bounce_ray(mut ray: Ray3d, ray_cast: &mut MeshRayCast, gizmos: &mut Gizmos, color: Color) {
49 let mut intersections = Vec::with_capacity(MAX_BOUNCES + 1);
50 intersections.push((ray.origin, Color::srgb(30.0, 0.0, 0.0)));
51
52 for i in 0..MAX_BOUNCES {
53 // Cast the ray and get the first hit
54 let Some((_, hit)) = ray_cast
55 .cast_ray(ray, &MeshRayCastSettings::default())
56 .first()
57 else {
58 break;
59 };
60
61 // Draw the point of intersection and add it to the list
62 let brightness = 1.0 + 10.0 * (1.0 - i as f32 / MAX_BOUNCES as f32);
63 intersections.push((hit.point, Color::BLACK.mix(&color, brightness)));
64 gizmos.sphere(hit.point, 0.005, Color::BLACK.mix(&color, brightness * 2.0));
65
66 // Reflect the ray off of the surface
67 ray.direction = Dir3::new(ray.direction.reflect(hit.normal)).unwrap();
68 ray.origin = hit.point + ray.direction * 1e-6;
69 }
70 gizmos.linestrip_gradient(intersections);
71}
- examples/testbed/helpers.rs
- examples/shader/custom_shader_instancing.rs
- examples/3d/load_gltf_extras.rs
- examples/ecs/relationships.rs
- examples/stress_tests/many_cubes.rs
- examples/stress_tests/many_sprites.rs
- examples/shader/texture_binding_array.rs
- examples/games/contributors.rs
- examples/stress_tests/many_text2d.rs
- examples/math/cubic_splines.rs
- examples/shader/custom_render_phase.rs
- examples/math/custom_primitives.rs
- examples/stress_tests/transform_hierarchy.rs
- examples/2d/mesh2d_manual.rs
- examples/stress_tests/bevymark.rs
- examples/shader/specialized_mesh_pipeline.rs
- examples/ui/display_and_visibility.rs
- examples/ecs/dynamic.rs
Sourcepub fn push_within_capacity(&mut self, value: T) -> Result<(), T>
🔬This is a nightly-only experimental API. (vec_push_within_capacity
)
pub fn push_within_capacity(&mut self, value: T) -> Result<(), T>
vec_push_within_capacity
)Appends an element if there is sufficient spare capacity, otherwise an error is returned with the element.
Unlike push
this method will not reallocate when there’s insufficient capacity.
The caller should use reserve
or try_reserve
to ensure that there is enough capacity.
§Examples
A manual, panic-free alternative to FromIterator
:
#![feature(vec_push_within_capacity)]
use std::collections::TryReserveError;
fn from_iter_fallible<T>(iter: impl Iterator<Item=T>) -> Result<Vec<T>, TryReserveError> {
let mut vec = Vec::new();
for value in iter {
if let Err(value) = vec.push_within_capacity(value) {
vec.try_reserve(1)?;
// this cannot fail, the previous line either returned or added at least 1 free slot
let _ = vec.push_within_capacity(value);
}
}
Ok(vec)
}
assert_eq!(from_iter_fallible(0..100), Ok(Vec::from_iter(0..100)));
§Time complexity
Takes O(1) time.
1.0.0 · Sourcepub fn pop(&mut self) -> Option<T>
pub fn pop(&mut self) -> Option<T>
Removes the last element from a vector and returns it, or None
if it
is empty.
If you’d like to pop the first element, consider using
VecDeque::pop_front
instead.
§Examples
let mut vec = vec![1, 2, 3];
assert_eq!(vec.pop(), Some(3));
assert_eq!(vec, [1, 2]);
§Time complexity
Takes O(1) time.
Examples found in repository?
392fn handle_keypress(
393 keyboard: Res<ButtonInput<KeyCode>>,
394 mut spline_mode: ResMut<SplineMode>,
395 mut cycling_mode: ResMut<CyclingMode>,
396 mut control_points: ResMut<ControlPoints>,
397) {
398 // S => change spline mode
399 if keyboard.just_pressed(KeyCode::KeyS) {
400 *spline_mode = match *spline_mode {
401 SplineMode::Hermite => SplineMode::Cardinal,
402 SplineMode::Cardinal => SplineMode::B,
403 SplineMode::B => SplineMode::Hermite,
404 }
405 }
406
407 // C => change cycling mode
408 if keyboard.just_pressed(KeyCode::KeyC) {
409 *cycling_mode = match *cycling_mode {
410 CyclingMode::NotCyclic => CyclingMode::Cyclic,
411 CyclingMode::Cyclic => CyclingMode::NotCyclic,
412 }
413 }
414
415 // R => remove last control point
416 if keyboard.just_pressed(KeyCode::KeyR) {
417 control_points.points_and_tangents.pop();
418 }
419}
More examples
263fn spawn_right_panel(
264 parent: &mut ChildSpawnerCommands,
265 text_font: TextFont,
266 palette: &[Color; 4],
267 mut target_ids: Vec<Entity>,
268) {
269 let spawn_buttons = |parent: &mut ChildSpawnerCommands, target_id| {
270 spawn_button::<Display>(parent, text_font.clone(), target_id);
271 spawn_button::<Visibility>(parent, text_font.clone(), target_id);
272 };
273 parent
274 .spawn((
275 Node {
276 padding: UiRect::all(Val::Px(10.)),
277 ..default()
278 },
279 BackgroundColor(Color::WHITE),
280 ))
281 .with_children(|parent| {
282 parent
283 .spawn((
284 Node {
285 width: Val::Px(500.),
286 height: Val::Px(500.),
287 flex_direction: FlexDirection::Column,
288 align_items: AlignItems::FlexEnd,
289 justify_content: JustifyContent::SpaceBetween,
290 padding: UiRect {
291 left: Val::Px(5.),
292 top: Val::Px(5.),
293 ..default()
294 },
295 ..default()
296 },
297 BackgroundColor(palette[0]),
298 Outline {
299 width: Val::Px(4.),
300 color: DARK_CYAN.into(),
301 offset: Val::Px(10.),
302 },
303 ))
304 .with_children(|parent| {
305 spawn_buttons(parent, target_ids.pop().unwrap());
306
307 parent
308 .spawn((
309 Node {
310 width: Val::Px(400.),
311 height: Val::Px(400.),
312 flex_direction: FlexDirection::Column,
313 align_items: AlignItems::FlexEnd,
314 justify_content: JustifyContent::SpaceBetween,
315 padding: UiRect {
316 left: Val::Px(5.),
317 top: Val::Px(5.),
318 ..default()
319 },
320 ..default()
321 },
322 BackgroundColor(palette[1]),
323 ))
324 .with_children(|parent| {
325 spawn_buttons(parent, target_ids.pop().unwrap());
326
327 parent
328 .spawn((
329 Node {
330 width: Val::Px(300.),
331 height: Val::Px(300.),
332 flex_direction: FlexDirection::Column,
333 align_items: AlignItems::FlexEnd,
334 justify_content: JustifyContent::SpaceBetween,
335 padding: UiRect {
336 left: Val::Px(5.),
337 top: Val::Px(5.),
338 ..default()
339 },
340 ..default()
341 },
342 BackgroundColor(palette[2]),
343 ))
344 .with_children(|parent| {
345 spawn_buttons(parent, target_ids.pop().unwrap());
346
347 parent
348 .spawn((
349 Node {
350 width: Val::Px(200.),
351 height: Val::Px(200.),
352 align_items: AlignItems::FlexStart,
353 justify_content: JustifyContent::SpaceBetween,
354 flex_direction: FlexDirection::Column,
355 padding: UiRect {
356 left: Val::Px(5.),
357 top: Val::Px(5.),
358 ..default()
359 },
360 ..default()
361 },
362 BackgroundColor(palette[3]),
363 ))
364 .with_children(|parent| {
365 spawn_buttons(parent, target_ids.pop().unwrap());
366
367 parent.spawn(Node {
368 width: Val::Px(100.),
369 height: Val::Px(100.),
370 ..default()
371 });
372 });
373 });
374 });
375 });
376 });
377}
1.86.0 · Sourcepub fn pop_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T>
pub fn pop_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T>
Removes and returns the last element from a vector if the predicate
returns true
, or None
if the predicate returns false or the vector
is empty (the predicate will not be called in that case).
§Examples
let mut vec = vec![1, 2, 3, 4];
let pred = |x: &mut i32| *x % 2 == 0;
assert_eq!(vec.pop_if(pred), Some(4));
assert_eq!(vec, [1, 2, 3]);
assert_eq!(vec.pop_if(pred), None);
1.6.0 · Sourcepub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A> ⓘwhere
R: RangeBounds<usize>,
pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A> ⓘwhere
R: RangeBounds<usize>,
Removes the subslice indicated by the given range from the vector, returning a double-ended iterator over the removed subslice.
If the iterator is dropped before being fully consumed, it drops the remaining removed elements.
The returned iterator keeps a mutable borrow on the vector to optimize its implementation.
§Panics
Panics if the starting point is greater than the end point or if the end point is greater than the length of the vector.
§Leaking
If the returned iterator goes out of scope without being dropped (due to
mem::forget
, for example), the vector may have lost and leaked
elements arbitrarily, including elements outside the range.
§Examples
let mut v = vec![1, 2, 3];
let u: Vec<_> = v.drain(1..).collect();
assert_eq!(v, &[1]);
assert_eq!(u, &[2, 3]);
// A full range clears the vector, like `clear()` does
v.drain(..);
assert_eq!(v, &[]);
Examples found in repository?
99fn build_ui(
100 mut commands: Commands,
101 asset_server: Res<AssetServer>,
102 schedules: Res<Schedules>,
103 mut stepping: ResMut<Stepping>,
104 mut state: ResMut<State>,
105) {
106 let mut text_spans = Vec::new();
107 let mut always_run = Vec::new();
108
109 let Ok(schedule_order) = stepping.schedules() else {
110 return;
111 };
112
113 // go through the stepping schedules and construct a list of systems for
114 // each label
115 for label in schedule_order {
116 let schedule = schedules.get(*label).unwrap();
117 text_spans.push((
118 TextSpan(format!("{label:?}\n")),
119 TextFont {
120 font: asset_server.load(FONT_BOLD),
121 ..default()
122 },
123 TextColor(FONT_COLOR),
124 ));
125
126 // grab the list of systems in the schedule, in the order the
127 // single-threaded executor would run them.
128 let Ok(systems) = schedule.systems() else {
129 return;
130 };
131
132 for (node_id, system) in systems {
133 // skip bevy default systems; we don't want to step those
134 if system.name().starts_with("bevy") {
135 always_run.push((*label, node_id));
136 continue;
137 }
138
139 // Add an entry to our systems list so we can find where to draw
140 // the cursor when the stepping cursor is at this system
141 // we add plus 1 to account for the empty root span
142 state.systems.push((*label, node_id, text_spans.len() + 1));
143
144 // Add a text section for displaying the cursor for this system
145 text_spans.push((
146 TextSpan::new(" "),
147 TextFont::default(),
148 TextColor(FONT_COLOR),
149 ));
150
151 // add the name of the system to the ui
152 text_spans.push((
153 TextSpan(format!("{}\n", system.name())),
154 TextFont::default(),
155 TextColor(FONT_COLOR),
156 ));
157 }
158 }
159
160 for (label, node) in always_run.drain(..) {
161 stepping.always_run_node(label, node);
162 }
163
164 commands.spawn((
165 Text::default(),
166 SteppingUi,
167 Node {
168 position_type: PositionType::Absolute,
169 top: state.ui_top,
170 left: state.ui_left,
171 padding: UiRect::all(Val::Px(10.0)),
172 ..default()
173 },
174 BackgroundColor(Color::srgba(1.0, 1.0, 1.0, 0.33)),
175 Visibility::Hidden,
176 Children::spawn(text_spans),
177 ));
178}
1.0.0 · Sourcepub fn clear(&mut self)
pub fn clear(&mut self)
Clears the vector, removing all values.
Note that this method has no effect on the allocated capacity of the vector.
§Examples
let mut v = vec![1, 2, 3];
v.clear();
assert!(v.is_empty());
1.0.0 · Sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Returns the number of elements in the vector, also referred to as its ‘length’.
§Examples
let a = vec![1, 2, 3];
assert_eq!(a.len(), 3);
Examples found in repository?
134 fn new() -> Self {
135 let shapes = Shape::list_all_shapes();
136
137 let n_shapes = shapes.len();
138
139 let translations =
140 (0..n_shapes).map(|i| (i as f32 - n_shapes as f32 / 2.0) * DISTANCE_BETWEEN_SHAPES);
141
142 SampledShapes(shapes.into_iter().zip(translations).collect())
143 }
144}
145
146/// Enum listing the shapes that can be sampled
147#[derive(Clone, Copy)]
148enum Shape {
149 Cuboid,
150 Sphere,
151 Capsule,
152 Cylinder,
153 Tetrahedron,
154 Triangle,
155}
156struct ShapeMeshBuilder {
157 shape: Shape,
158}
159
160impl Shape {
161 /// Return a vector containing all implemented shapes
162 fn list_all_shapes() -> Vec<Shape> {
163 vec![
164 Shape::Cuboid,
165 Shape::Sphere,
166 Shape::Capsule,
167 Shape::Cylinder,
168 Shape::Tetrahedron,
169 Shape::Triangle,
170 ]
171 }
172}
173
174impl ShapeSample for Shape {
175 type Output = Vec3;
176 fn sample_interior<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec3 {
177 match self {
178 Shape::Cuboid => CUBOID.sample_interior(rng),
179 Shape::Sphere => SPHERE.sample_interior(rng),
180 Shape::Capsule => CAPSULE_3D.sample_interior(rng),
181 Shape::Cylinder => CYLINDER.sample_interior(rng),
182 Shape::Tetrahedron => TETRAHEDRON.sample_interior(rng),
183 Shape::Triangle => TRIANGLE_3D.sample_interior(rng),
184 }
185 }
186
187 fn sample_boundary<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::Output {
188 match self {
189 Shape::Cuboid => CUBOID.sample_boundary(rng),
190 Shape::Sphere => SPHERE.sample_boundary(rng),
191 Shape::Capsule => CAPSULE_3D.sample_boundary(rng),
192 Shape::Cylinder => CYLINDER.sample_boundary(rng),
193 Shape::Tetrahedron => TETRAHEDRON.sample_boundary(rng),
194 Shape::Triangle => TRIANGLE_3D.sample_boundary(rng),
195 }
196 }
197}
198
199impl Meshable for Shape {
200 type Output = ShapeMeshBuilder;
201
202 fn mesh(&self) -> Self::Output {
203 ShapeMeshBuilder { shape: *self }
204 }
205}
206
207impl MeshBuilder for ShapeMeshBuilder {
208 fn build(&self) -> Mesh {
209 match self.shape {
210 Shape::Cuboid => CUBOID.mesh().into(),
211 Shape::Sphere => SPHERE.mesh().into(),
212 Shape::Capsule => CAPSULE_3D.mesh().into(),
213 Shape::Cylinder => CYLINDER.mesh().into(),
214 Shape::Tetrahedron => TETRAHEDRON.mesh().into(),
215 Shape::Triangle => TRIANGLE_3D.mesh().into(),
216 }
217 }
218}
219
220/// The source of randomness used by this example.
221#[derive(Resource)]
222struct RandomSource(ChaCha8Rng);
223
224/// A container for the handle storing the mesh used to display sampled points as spheres.
225#[derive(Resource)]
226struct PointMesh(Handle<Mesh>);
227
228/// A container for the handle storing the material used to display sampled points.
229#[derive(Resource)]
230struct PointMaterial {
231 interior: Handle<StandardMaterial>,
232 boundary: Handle<StandardMaterial>,
233}
234
235/// Marker component for sampled points.
236#[derive(Component)]
237struct SamplePoint;
238
239/// Component for animating the spawn animation of lights.
240#[derive(Component)]
241struct SpawningPoint {
242 progress: f32,
243}
244
245/// Marker component for lights which should change intensity.
246#[derive(Component)]
247struct DespawningPoint {
248 progress: f32,
249}
250
251/// Marker component for lights which should change intensity.
252#[derive(Component)]
253struct FireflyLights;
254
255/// The pressed state of the mouse, used for camera motion.
256#[derive(Resource)]
257struct MousePressed(bool);
258
259/// Camera movement component.
260#[derive(Component)]
261struct CameraRig {
262 /// Rotation around the vertical axis of the camera (radians).
263 /// Positive changes makes the camera look more from the right.
264 pub yaw: f32,
265 /// Rotation around the horizontal axis of the camera (radians) (-pi/2; pi/2).
266 /// Positive looks down from above.
267 pub pitch: f32,
268 /// Distance from the center, smaller distance causes more zoom.
269 pub distance: f32,
270 /// Location in 3D space at which the camera is looking and around which it is orbiting.
271 pub target: Vec3,
272}
273
274fn setup(
275 mut commands: Commands,
276 mut meshes: ResMut<Assets<Mesh>>,
277 mut materials: ResMut<Assets<StandardMaterial>>,
278 shapes: Res<SampledShapes>,
279) {
280 // Use seeded rng and store it in a resource; this makes the random output reproducible.
281 let seeded_rng = ChaCha8Rng::seed_from_u64(4); // Chosen by a fair die roll, guaranteed to be random.
282 commands.insert_resource(RandomSource(seeded_rng));
283
284 // Make a plane for establishing space.
285 commands.spawn((
286 Mesh3d(meshes.add(Plane3d::default().mesh().size(20.0, 20.0))),
287 MeshMaterial3d(materials.add(StandardMaterial {
288 base_color: Color::srgb(0.3, 0.5, 0.3),
289 perceptual_roughness: 0.95,
290 metallic: 0.0,
291 ..default()
292 })),
293 Transform::from_xyz(0.0, -2.5, 0.0),
294 ));
295
296 let shape_material = materials.add(StandardMaterial {
297 base_color: Color::srgba(0.2, 0.1, 0.6, 0.3),
298 reflectance: 0.0,
299 alpha_mode: AlphaMode::Blend,
300 cull_mode: None,
301 ..default()
302 });
303
304 // Spawn shapes to be sampled
305 for (shape, translation) in shapes.0.iter() {
306 // The sampled shape shown transparently:
307 commands.spawn((
308 Mesh3d(meshes.add(shape.mesh())),
309 MeshMaterial3d(shape_material.clone()),
310 Transform::from_translation(*translation),
311 ));
312
313 // Lights which work as the bulk lighting of the fireflies:
314 commands.spawn((
315 PointLight {
316 range: 4.0,
317 radius: 0.6,
318 intensity: 1.0,
319 shadows_enabled: false,
320 color: Color::LinearRgba(INSIDE_POINT_COLOR),
321 ..default()
322 },
323 Transform::from_translation(*translation),
324 FireflyLights,
325 ));
326 }
327
328 // Global light:
329 commands.spawn((
330 PointLight {
331 color: SKY_COLOR,
332 intensity: 2_000.0,
333 shadows_enabled: false,
334 ..default()
335 },
336 Transform::from_xyz(4.0, 8.0, 4.0),
337 ));
338
339 // A camera:
340 commands.spawn((
341 Camera3d::default(),
342 Camera {
343 hdr: true, // HDR is required for bloom
344 clear_color: ClearColorConfig::Custom(SKY_COLOR),
345 ..default()
346 },
347 Tonemapping::TonyMcMapface,
348 Transform::from_xyz(-2.0, 3.0, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
349 Bloom::NATURAL,
350 CameraRig {
351 yaw: 0.56,
352 pitch: 0.45,
353 distance: 8.0,
354 target: Vec3::ZERO,
355 },
356 ));
357
358 // Store the mesh and material for sample points in resources:
359 commands.insert_resource(PointMesh(
360 meshes.add(Sphere::new(0.03).mesh().ico(1).unwrap()),
361 ));
362 commands.insert_resource(PointMaterial {
363 interior: materials.add(StandardMaterial {
364 base_color: Color::BLACK,
365 reflectance: 0.05,
366 emissive: 2.5 * INSIDE_POINT_COLOR,
367 ..default()
368 }),
369 boundary: materials.add(StandardMaterial {
370 base_color: Color::BLACK,
371 reflectance: 0.05,
372 emissive: 1.5 * BOUNDARY_POINT_COLOR,
373 ..default()
374 }),
375 });
376
377 // Instructions for the example:
378 commands.spawn((
379 Text::new(
380 "Controls:\n\
381 M: Toggle between sampling boundary and interior.\n\
382 A: Toggle automatic spawning & despawning of points.\n\
383 R: Restart (erase all samples).\n\
384 S: Add one random sample.\n\
385 D: Add 100 random samples.\n\
386 Rotate camera by holding left mouse and panning.\n\
387 Zoom camera by scrolling via mouse or +/-.\n\
388 Move camera by L/R arrow keys.\n\
389 Tab: Toggle this text",
390 ),
391 Node {
392 position_type: PositionType::Absolute,
393 top: Val::Px(12.0),
394 left: Val::Px(12.0),
395 ..default()
396 },
397 ));
398
399 // No points are scheduled to spawn initially.
400 commands.insert_resource(SpawnQueue(0));
401
402 // No points have been spawned initially.
403 commands.insert_resource(PointCounter(0));
404
405 // The mode starts with interior points.
406 commands.insert_resource(SamplingMode::Interior);
407
408 // Points spawn automatically by default.
409 commands.insert_resource(SpawningMode::Automatic);
410
411 // Starting mouse-pressed state is false.
412 commands.insert_resource(MousePressed(false));
413}
414
415// Handle user inputs from the keyboard:
416fn handle_keypress(
417 mut commands: Commands,
418 keyboard: Res<ButtonInput<KeyCode>>,
419 mut mode: ResMut<SamplingMode>,
420 mut spawn_mode: ResMut<SpawningMode>,
421 samples: Query<Entity, With<SamplePoint>>,
422 shapes: Res<SampledShapes>,
423 mut spawn_queue: ResMut<SpawnQueue>,
424 mut counter: ResMut<PointCounter>,
425 mut text_menus: Query<&mut Visibility, With<Text>>,
426 mut camera_rig: Single<&mut CameraRig>,
427) {
428 // R => restart, deleting all samples
429 if keyboard.just_pressed(KeyCode::KeyR) {
430 // Don't forget to zero out the counter!
431 counter.0 = 0;
432 for entity in &samples {
433 commands.entity(entity).despawn();
434 }
435 }
436
437 // S => sample once
438 if keyboard.just_pressed(KeyCode::KeyS) {
439 spawn_queue.0 += 1;
440 }
441
442 // D => sample a hundred
443 if keyboard.just_pressed(KeyCode::KeyD) {
444 spawn_queue.0 += 100;
445 }
446
447 // M => toggle mode between interior and boundary.
448 if keyboard.just_pressed(KeyCode::KeyM) {
449 match *mode {
450 SamplingMode::Interior => *mode = SamplingMode::Boundary,
451 SamplingMode::Boundary => *mode = SamplingMode::Interior,
452 }
453 }
454
455 // A => toggle spawning mode between automatic and manual.
456 if keyboard.just_pressed(KeyCode::KeyA) {
457 match *spawn_mode {
458 SpawningMode::Manual => *spawn_mode = SpawningMode::Automatic,
459 SpawningMode::Automatic => *spawn_mode = SpawningMode::Manual,
460 }
461 }
462
463 // Tab => toggle help menu.
464 if keyboard.just_pressed(KeyCode::Tab) {
465 for mut visibility in text_menus.iter_mut() {
466 *visibility = match *visibility {
467 Visibility::Hidden => Visibility::Visible,
468 _ => Visibility::Hidden,
469 };
470 }
471 }
472
473 // +/- => zoom camera.
474 if keyboard.just_pressed(KeyCode::NumpadSubtract) || keyboard.just_pressed(KeyCode::Minus) {
475 camera_rig.distance += MAX_CAMERA_DISTANCE / 15.0;
476 camera_rig.distance = camera_rig
477 .distance
478 .clamp(MIN_CAMERA_DISTANCE, MAX_CAMERA_DISTANCE);
479 }
480
481 if keyboard.just_pressed(KeyCode::NumpadAdd) {
482 camera_rig.distance -= MAX_CAMERA_DISTANCE / 15.0;
483 camera_rig.distance = camera_rig
484 .distance
485 .clamp(MIN_CAMERA_DISTANCE, MAX_CAMERA_DISTANCE);
486 }
487
488 // Arrows => Move camera focus
489 let left = keyboard.just_pressed(KeyCode::ArrowLeft);
490 let right = keyboard.just_pressed(KeyCode::ArrowRight);
491
492 if left || right {
493 let mut closest = 0;
494 let mut closest_distance = f32::MAX;
495 for (i, (_, position)) in shapes.0.iter().enumerate() {
496 let distance = camera_rig.target.distance(*position);
497 if distance < closest_distance {
498 closest = i;
499 closest_distance = distance;
500 }
501 }
502 if closest > 0 && left {
503 camera_rig.target = shapes.0[closest - 1].1;
504 }
505 if closest < shapes.0.len() - 1 && right {
506 camera_rig.target = shapes.0[closest + 1].1;
507 }
508 }
509}
More examples
260fn parse_query<Q: QueryData>(
261 str: &str,
262 builder: &mut QueryBuilder<Q>,
263 components: &HashMap<String, ComponentId>,
264) {
265 let str = str.split(',');
266 str.for_each(|term| {
267 let sub_terms: Vec<_> = term.split("||").collect();
268 if sub_terms.len() == 1 {
269 parse_term(sub_terms[0], builder, components);
270 } else {
271 builder.or(|b| {
272 sub_terms
273 .iter()
274 .for_each(|term| parse_term(term, b, components));
275 });
276 }
277 });
278}
112fn animate_sprite(
113 time: Res<Time>,
114 texture_atlases: Res<Assets<TextureAtlasLayout>>,
115 mut query: Query<(&mut AnimationTimer, &mut Sprite)>,
116) {
117 for (mut timer, mut sprite) in query.iter_mut() {
118 timer.tick(time.delta());
119 if timer.just_finished() {
120 let Some(atlas) = &mut sprite.texture_atlas else {
121 continue;
122 };
123 let texture_atlas = texture_atlases.get(&atlas.layout).unwrap();
124 atlas.index = (atlas.index + 1) % texture_atlas.textures.len();
125 }
126 }
127}
181fn prepare_instance_buffers(
182 mut commands: Commands,
183 query: Query<(Entity, &InstanceMaterialData)>,
184 render_device: Res<RenderDevice>,
185) {
186 for (entity, instance_data) in &query {
187 let buffer = render_device.create_buffer_with_data(&BufferInitDescriptor {
188 label: Some("instance data buffer"),
189 contents: bytemuck::cast_slice(instance_data.as_slice()),
190 usage: BufferUsages::VERTEX | BufferUsages::COPY_DST,
191 });
192 commands.entity(entity).insert(InstanceBuffer {
193 buffer,
194 length: instance_data.len(),
195 });
196 }
197}
167fn print_counts(
168 time: Res<Time>,
169 mut timer: Local<PrintingTimer>,
170 texts: Query<&ViewVisibility, With<Text2d>>,
171 atlases: Res<FontAtlasSets>,
172 font: Res<FontHandle>,
173) {
174 timer.tick(time.delta());
175 if !timer.just_finished() {
176 return;
177 }
178
179 let num_atlases = atlases
180 .get(font.0.id())
181 .map(|set| set.iter().map(|atlas| atlas.1.len()).sum())
182 .unwrap_or(0);
183
184 let visible_texts = texts.iter().filter(|visibility| visibility.get()).count();
185
186 info!(
187 "Texts: {} Visible: {} Atlases: {}",
188 texts.iter().count(),
189 visible_texts,
190 num_atlases
191 );
192}
176fn cycle_cursor_icon(
177 mut commands: Commands,
178 window: Single<Entity, With<Window>>,
179 input: Res<ButtonInput<MouseButton>>,
180 mut index: Local<usize>,
181 cursor_icons: Res<CursorIcons>,
182) {
183 if input.just_pressed(MouseButton::Left) {
184 *index = (*index + 1) % cursor_icons.0.len();
185 commands
186 .entity(*window)
187 .insert(cursor_icons.0[*index].clone());
188 } else if input.just_pressed(MouseButton::Right) {
189 *index = if *index == 0 {
190 cursor_icons.0.len() - 1
191 } else {
192 *index - 1
193 };
194 commands
195 .entity(*window)
196 .insert(cursor_icons.0[*index].clone());
197 }
198}
- examples/asset/custom_asset.rs
- examples/ui/font_atlas_debug.rs
- examples/stress_tests/many_cubes.rs
- examples/2d/mesh2d_manual.rs
- examples/games/contributors.rs
- examples/stress_tests/many_foxes.rs
- examples/games/stepping.rs
- examples/stress_tests/transform_hierarchy.rs
- examples/animation/animation_masks.rs
- examples/animation/animated_mesh_control.rs
- examples/stress_tests/bevymark.rs
1.0.0 · Sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Returns true
if the vector contains no elements.
§Examples
let mut v = Vec::new();
assert!(v.is_empty());
v.push(1);
assert!(!v.is_empty());
Examples found in repository?
More examples
196fn update_loading_data(
197 mut loading_data: ResMut<LoadingData>,
198 mut loading_state: ResMut<LoadingState>,
199 asset_server: Res<AssetServer>,
200 pipelines_ready: Res<PipelinesReady>,
201) {
202 if !loading_data.loading_assets.is_empty() || !pipelines_ready.0 {
203 // If we are still loading assets / pipelines are not fully compiled,
204 // we reset the confirmation frame count.
205 loading_data.confirmation_frames_count = 0;
206
207 loading_data.loading_assets.retain(|asset| {
208 asset_server
209 .get_recursive_dependency_load_state(asset)
210 .is_none_or(|state| !state.is_loaded())
211 });
212
213 // If there are no more assets being monitored, and pipelines
214 // are compiled, then start counting confirmation frames.
215 // Once enough confirmations have passed, everything will be
216 // considered to be fully loaded.
217 } else {
218 loading_data.confirmation_frames_count += 1;
219 if loading_data.confirmation_frames_count == loading_data.confirmation_frames_target {
220 *loading_state = LoadingState::LevelReady;
221 }
222 }
223}
472fn update(
473 images_to_save: Query<&ImageToSave>,
474 receiver: Res<MainWorldReceiver>,
475 mut images: ResMut<Assets<Image>>,
476 mut scene_controller: ResMut<SceneController>,
477 mut app_exit_writer: EventWriter<AppExit>,
478 mut file_number: Local<u32>,
479) {
480 if let SceneState::Render(n) = scene_controller.state {
481 if n < 1 {
482 // We don't want to block the main world on this,
483 // so we use try_recv which attempts to receive without blocking
484 let mut image_data = Vec::new();
485 while let Ok(data) = receiver.try_recv() {
486 // image generation could be faster than saving to fs,
487 // that's why use only last of them
488 image_data = data;
489 }
490 if !image_data.is_empty() {
491 for image in images_to_save.iter() {
492 // Fill correct data from channel to image
493 let img_bytes = images.get_mut(image.id()).unwrap();
494
495 // We need to ensure that this works regardless of the image dimensions
496 // If the image became wider when copying from the texture to the buffer,
497 // then the data is reduced to its original size when copying from the buffer to the image.
498 let row_bytes = img_bytes.width() as usize
499 * img_bytes.texture_descriptor.format.pixel_size();
500 let aligned_row_bytes = RenderDevice::align_copy_bytes_per_row(row_bytes);
501 if row_bytes == aligned_row_bytes {
502 img_bytes.data.as_mut().unwrap().clone_from(&image_data);
503 } else {
504 // shrink data to original image size
505 img_bytes.data = Some(
506 image_data
507 .chunks(aligned_row_bytes)
508 .take(img_bytes.height() as usize)
509 .flat_map(|row| &row[..row_bytes.min(row.len())])
510 .cloned()
511 .collect(),
512 );
513 }
514
515 // Create RGBA Image Buffer
516 let img = match img_bytes.clone().try_into_dynamic() {
517 Ok(img) => img.to_rgba8(),
518 Err(e) => panic!("Failed to create image buffer {e:?}"),
519 };
520
521 // Prepare directory for images, test_images in bevy folder is used here for example
522 // You should choose the path depending on your needs
523 let images_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("test_images");
524 info!("Saving image to: {images_dir:?}");
525 std::fs::create_dir_all(&images_dir).unwrap();
526
527 // Choose filename starting from 000.png
528 let image_path = images_dir.join(format!("{:03}.png", file_number.deref()));
529 *file_number.deref_mut() += 1;
530
531 // Finally saving image to file, this heavy blocking operation is kept here
532 // for example simplicity, but in real app you should move it to a separate task
533 if let Err(e) = img.save(image_path) {
534 panic!("Failed to save image: {e}");
535 };
536 }
537 if scene_controller.single_image {
538 app_exit_writer.write(AppExit::Success);
539 }
540 }
541 } else {
542 // clears channel for skipped frames
543 while receiver.try_recv().is_ok() {}
544 scene_controller.state = SceneState::Render(n - 1);
545 }
546 }
547}
1.4.0 · Sourcepub fn split_off(&mut self, at: usize) -> Vec<T, A>where
A: Clone,
pub fn split_off(&mut self, at: usize) -> Vec<T, A>where
A: Clone,
Splits the collection into two at the given index.
Returns a newly allocated vector containing the elements in the range
[at, len)
. After the call, the original vector will be left containing
the elements [0, at)
with its previous capacity unchanged.
- If you want to take ownership of the entire contents and capacity of
the vector, see
mem::take
ormem::replace
. - If you don’t need the returned vector at all, see
Vec::truncate
. - If you want to take ownership of an arbitrary subslice, or you don’t
necessarily want to store the removed items in a vector, see
Vec::drain
.
§Panics
Panics if at > len
.
§Examples
let mut vec = vec!['a', 'b', 'c'];
let vec2 = vec.split_off(1);
assert_eq!(vec, ['a']);
assert_eq!(vec2, ['b', 'c']);
1.33.0 · Sourcepub fn resize_with<F>(&mut self, new_len: usize, f: F)where
F: FnMut() -> T,
pub fn resize_with<F>(&mut self, new_len: usize, f: F)where
F: FnMut() -> T,
Resizes the Vec
in-place so that len
is equal to new_len
.
If new_len
is greater than len
, the Vec
is extended by the
difference, with each additional slot filled with the result of
calling the closure f
. The return values from f
will end up
in the Vec
in the order they have been generated.
If new_len
is less than len
, the Vec
is simply truncated.
This method uses a closure to create new values on every push. If
you’d rather Clone
a given value, use Vec::resize
. If you
want to use the Default
trait to generate values, you can
pass Default::default
as the second argument.
§Panics
Panics if the new capacity exceeds isize::MAX
bytes.
§Examples
let mut vec = vec![1, 2, 3];
vec.resize_with(5, Default::default);
assert_eq!(vec, [1, 2, 3, 0, 0]);
let mut vec = vec![];
let mut p = 1;
vec.resize_with(4, || { p *= 2; p });
assert_eq!(vec, [2, 4, 8, 16]);
1.60.0 · Sourcepub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>]
pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>]
Returns the remaining spare capacity of the vector as a slice of
MaybeUninit<T>
.
The returned slice can be used to fill the vector with data (e.g. by
reading from a file) before marking the data as initialized using the
set_len
method.
§Examples
// Allocate vector big enough for 10 elements.
let mut v = Vec::with_capacity(10);
// Fill in the first 3 elements.
let uninit = v.spare_capacity_mut();
uninit[0].write(0);
uninit[1].write(1);
uninit[2].write(2);
// Mark the first 3 elements of the vector as being initialized.
unsafe {
v.set_len(3);
}
assert_eq!(&v, &[0, 1, 2]);
Sourcepub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>])
🔬This is a nightly-only experimental API. (vec_split_at_spare
)
pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>])
vec_split_at_spare
)Returns vector content as a slice of T
, along with the remaining spare
capacity of the vector as a slice of MaybeUninit<T>
.
The returned spare capacity slice can be used to fill the vector with data
(e.g. by reading from a file) before marking the data as initialized using
the set_len
method.
Note that this is a low-level API, which should be used with care for
optimization purposes. If you need to append data to a Vec
you can use push
, extend
, extend_from_slice
,
extend_from_within
, insert
, append
, resize
or
resize_with
, depending on your exact needs.
§Examples
#![feature(vec_split_at_spare)]
let mut v = vec![1, 1, 2];
// Reserve additional space big enough for 10 elements.
v.reserve(10);
let (init, uninit) = v.split_at_spare_mut();
let sum = init.iter().copied().sum::<u32>();
// Fill in the next 4 elements.
uninit[0].write(sum);
uninit[1].write(sum * 2);
uninit[2].write(sum * 3);
uninit[3].write(sum * 4);
// Mark the 4 elements of the vector as being initialized.
unsafe {
let len = v.len();
v.set_len(len + 4);
}
assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
1.5.0 · Sourcepub fn resize(&mut self, new_len: usize, value: T)
pub fn resize(&mut self, new_len: usize, value: T)
Resizes the Vec
in-place so that len
is equal to new_len
.
If new_len
is greater than len
, the Vec
is extended by the
difference, with each additional slot filled with value
.
If new_len
is less than len
, the Vec
is simply truncated.
This method requires T
to implement Clone
,
in order to be able to clone the passed value.
If you need more flexibility (or want to rely on Default
instead of
Clone
), use Vec::resize_with
.
If you only need to resize to a smaller size, use Vec::truncate
.
§Panics
Panics if the new capacity exceeds isize::MAX
bytes.
§Examples
let mut vec = vec!["hello"];
vec.resize(3, "world");
assert_eq!(vec, ["hello", "world", "world"]);
let mut vec = vec!['a', 'b', 'c', 'd'];
vec.resize(2, '_');
assert_eq!(vec, ['a', 'b']);
Examples found in repository?
51fn main() {
52 let mut world = World::new();
53 let mut lines = std::io::stdin().lines();
54 let mut component_names = HashMap::<String, ComponentId>::new();
55 let mut component_info = HashMap::<ComponentId, ComponentInfo>::new();
56
57 println!("{PROMPT}");
58 loop {
59 print!("\n> ");
60 let _ = std::io::stdout().flush();
61 let Some(Ok(line)) = lines.next() else {
62 return;
63 };
64
65 if line.is_empty() {
66 return;
67 };
68
69 let Some((first, rest)) = line.trim().split_once(|c: char| c.is_whitespace()) else {
70 match &line.chars().next() {
71 Some('c') => println!("{COMPONENT_PROMPT}"),
72 Some('s') => println!("{ENTITY_PROMPT}"),
73 Some('q') => println!("{QUERY_PROMPT}"),
74 _ => println!("{PROMPT}"),
75 }
76 continue;
77 };
78
79 match &first[0..1] {
80 "c" => {
81 rest.split(',').for_each(|component| {
82 let mut component = component.split_whitespace();
83 let Some(name) = component.next() else {
84 return;
85 };
86 let size = match component.next().map(str::parse) {
87 Some(Ok(size)) => size,
88 _ => 0,
89 };
90 // Register our new component to the world with a layout specified by it's size
91 // SAFETY: [u64] is Send + Sync
92 let id = world.register_component_with_descriptor(unsafe {
93 ComponentDescriptor::new_with_layout(
94 name.to_string(),
95 StorageType::Table,
96 Layout::array::<u64>(size).unwrap(),
97 None,
98 true,
99 ComponentCloneBehavior::Default,
100 )
101 });
102 let Some(info) = world.components().get_info(id) else {
103 return;
104 };
105 component_names.insert(name.to_string(), id);
106 component_info.insert(id, info.clone());
107 println!("Component {} created with id: {}", name, id.index());
108 });
109 }
110 "s" => {
111 let mut to_insert_ids = Vec::new();
112 let mut to_insert_data = Vec::new();
113 rest.split(',').for_each(|component| {
114 let mut component = component.split_whitespace();
115 let Some(name) = component.next() else {
116 return;
117 };
118
119 // Get the id for the component with the given name
120 let Some(&id) = component_names.get(name) else {
121 println!("Component {name} does not exist");
122 return;
123 };
124
125 // Calculate the length for the array based on the layout created for this component id
126 let info = world.components().get_info(id).unwrap();
127 let len = info.layout().size() / size_of::<u64>();
128 let mut values: Vec<u64> = component
129 .take(len)
130 .filter_map(|value| value.parse::<u64>().ok())
131 .collect();
132 values.resize(len, 0);
133
134 // Collect the id and array to be inserted onto our entity
135 to_insert_ids.push(id);
136 to_insert_data.push(values);
137 });
138
139 let mut entity = world.spawn_empty();
140
141 // Construct an `OwningPtr` for each component in `to_insert_data`
142 let to_insert_ptr = to_owning_ptrs(&mut to_insert_data);
143
144 // SAFETY:
145 // - Component ids have been taken from the same world
146 // - Each array is created to the layout specified in the world
147 unsafe {
148 entity.insert_by_ids(&to_insert_ids, to_insert_ptr.into_iter());
149 }
150
151 println!("Entity spawned with id: {}", entity.id());
152 }
153 "q" => {
154 let mut builder = QueryBuilder::<FilteredEntityMut>::new(&mut world);
155 parse_query(rest, &mut builder, &component_names);
156 let mut query = builder.build();
157 query.iter_mut(&mut world).for_each(|filtered_entity| {
158 let terms = filtered_entity
159 .access()
160 .try_iter_component_access()
161 .unwrap()
162 .map(|component_access| {
163 let id = *component_access.index();
164 let ptr = filtered_entity.get_by_id(id).unwrap();
165 let info = component_info.get(&id).unwrap();
166 let len = info.layout().size() / size_of::<u64>();
167
168 // SAFETY:
169 // - All components are created with layout [u64]
170 // - len is calculated from the component descriptor
171 let data = unsafe {
172 std::slice::from_raw_parts_mut(
173 ptr.assert_unique().as_ptr().cast::<u64>(),
174 len,
175 )
176 };
177
178 // If we have write access, increment each value once
179 if matches!(component_access, ComponentAccessKind::Exclusive(_)) {
180 data.iter_mut().for_each(|data| {
181 *data += 1;
182 });
183 }
184
185 format!("{}: {:?}", info.name(), data[0..len].to_vec())
186 })
187 .collect::<Vec<_>>()
188 .join(", ");
189
190 println!("{}: {}", filtered_entity.id(), terms);
191 });
192 }
193 _ => continue,
194 }
195 }
196}
1.6.0 · Sourcepub fn extend_from_slice(&mut self, other: &[T])
pub fn extend_from_slice(&mut self, other: &[T])
Clones and appends all elements in a slice to the Vec
.
Iterates over the slice other
, clones each element, and then appends
it to this Vec
. The other
slice is traversed in-order.
Note that this function is the same as extend
,
except that it also works with slice elements that are Clone but not Copy.
If Rust gets specialization this function may be deprecated.
§Examples
let mut vec = vec![1];
vec.extend_from_slice(&[2, 3, 4]);
assert_eq!(vec, [1, 2, 3, 4]);
Examples found in repository?
402 fn build(&self) -> Mesh {
403 let radius = self.heart.radius;
404 // The curved parts of each wing (half) of the heart have an angle of `PI * 1.25` or 225°
405 let wing_angle = PI * 1.25;
406
407 // We create buffers for the vertices, their normals and UVs, as well as the indices used to connect the vertices.
408 let mut vertices = Vec::with_capacity(2 * self.resolution);
409 let mut uvs = Vec::with_capacity(2 * self.resolution);
410 let mut indices = Vec::with_capacity(6 * self.resolution - 9);
411 // Since the heart is flat, we know all the normals are identical already.
412 let normals = vec![[0f32, 0f32, 1f32]; 2 * self.resolution];
413
414 // The point in the middle of the two curved parts of the heart
415 vertices.push([0.0; 3]);
416 uvs.push([0.5, 0.5]);
417
418 // The left wing of the heart, starting from the point in the middle.
419 for i in 1..self.resolution {
420 let angle = (i as f32 / self.resolution as f32) * wing_angle;
421 let (sin, cos) = ops::sin_cos(angle);
422 vertices.push([radius * (cos - 1.0), radius * sin, 0.0]);
423 uvs.push([0.5 - (cos - 1.0) / 4., 0.5 - sin / 2.]);
424 }
425
426 // The bottom tip of the heart
427 vertices.push([0.0, radius * (-1. - SQRT_2), 0.0]);
428 uvs.push([0.5, 1.]);
429
430 // The right wing of the heart, starting from the bottom most point and going towards the middle point.
431 for i in 0..self.resolution - 1 {
432 let angle = (i as f32 / self.resolution as f32) * wing_angle - PI / 4.;
433 let (sin, cos) = ops::sin_cos(angle);
434 vertices.push([radius * (cos + 1.0), radius * sin, 0.0]);
435 uvs.push([0.5 - (cos + 1.0) / 4., 0.5 - sin / 2.]);
436 }
437
438 // This is where we build all the triangles from the points created above.
439 // Each triangle has one corner on the middle point with the other two being adjacent points on the perimeter of the heart.
440 for i in 2..2 * self.resolution as u32 {
441 indices.extend_from_slice(&[i - 1, i, 0]);
442 }
443
444 // Here, the actual `Mesh` is created. We set the indices, vertices, normals and UVs created above and specify the topology of the mesh.
445 Mesh::new(
446 bevy::render::mesh::PrimitiveTopology::TriangleList,
447 RenderAssetUsages::default(),
448 )
449 .with_inserted_indices(bevy::render::mesh::Indices::U32(indices))
450 .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, vertices)
451 .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
452 .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs)
453 }
More examples
48fn star(
49 mut commands: Commands,
50 // We will add a new Mesh for the star being created
51 mut meshes: ResMut<Assets<Mesh>>,
52) {
53 // Let's define the mesh for the object we want to draw: a nice star.
54 // We will specify here what kind of topology is used to define the mesh,
55 // that is, how triangles are built from the vertices. We will use a
56 // triangle list, meaning that each vertex of the triangle has to be
57 // specified. We set `RenderAssetUsages::RENDER_WORLD`, meaning this mesh
58 // will not be accessible in future frames from the `meshes` resource, in
59 // order to save on memory once it has been uploaded to the GPU.
60 let mut star = Mesh::new(
61 PrimitiveTopology::TriangleList,
62 RenderAssetUsages::RENDER_WORLD,
63 );
64
65 // Vertices need to have a position attribute. We will use the following
66 // vertices (I hope you can spot the star in the schema).
67 //
68 // 1
69 //
70 // 10 2
71 // 9 0 3
72 // 8 4
73 // 6
74 // 7 5
75 //
76 // These vertices are specified in 3D space.
77 let mut v_pos = vec![[0.0, 0.0, 0.0]];
78 for i in 0..10 {
79 // The angle between each vertex is 1/10 of a full rotation.
80 let a = i as f32 * PI / 5.0;
81 // The radius of inner vertices (even indices) is 100. For outer vertices (odd indices) it's 200.
82 let r = (1 - i % 2) as f32 * 100.0 + 100.0;
83 // Add the vertex position.
84 v_pos.push([r * ops::sin(a), r * ops::cos(a), 0.0]);
85 }
86 // Set the position attribute
87 star.insert_attribute(Mesh::ATTRIBUTE_POSITION, v_pos);
88 // And a RGB color attribute as well. A built-in `Mesh::ATTRIBUTE_COLOR` exists, but we
89 // use a custom vertex attribute here for demonstration purposes.
90 let mut v_color: Vec<u32> = vec![LinearRgba::BLACK.as_u32()];
91 v_color.extend_from_slice(&[LinearRgba::from(YELLOW).as_u32(); 10]);
92 star.insert_attribute(
93 MeshVertexAttribute::new("Vertex_Color", 1, VertexFormat::Uint32),
94 v_color,
95 );
96
97 // Now, we specify the indices of the vertex that are going to compose the
98 // triangles in our star. Vertices in triangles have to be specified in CCW
99 // winding (that will be the front face, colored). Since we are using
100 // triangle list, we will specify each triangle as 3 vertices
101 // First triangle: 0, 2, 1
102 // Second triangle: 0, 3, 2
103 // Third triangle: 0, 4, 3
104 // etc
105 // Last triangle: 0, 1, 10
106 let mut indices = vec![0, 1, 10];
107 for i in 2..=10 {
108 indices.extend_from_slice(&[0, i, i - 1]);
109 }
110 star.insert_indices(Indices::U32(indices));
111
112 // We can now spawn the entities for the star and the camera
113 commands.spawn((
114 // We use a marker component to identify the custom colored meshes
115 ColoredMesh2d,
116 // The `Handle<Mesh>` needs to be wrapped in a `Mesh2d` for 2D rendering
117 Mesh2d(meshes.add(star)),
118 ));
119
120 commands.spawn(Camera2d);
121}
1.53.0 · Sourcepub fn extend_from_within<R>(&mut self, src: R)where
R: RangeBounds<usize>,
pub fn extend_from_within<R>(&mut self, src: R)where
R: RangeBounds<usize>,
Given a range src
, clones a slice of elements in that range and appends it to the end.
src
must be a range that can form a valid subslice of the Vec
.
§Panics
Panics if starting index is greater than the end index or if the index is greater than the length of the vector.
§Examples
let mut characters = vec!['a', 'b', 'c', 'd', 'e'];
characters.extend_from_within(2..);
assert_eq!(characters, ['a', 'b', 'c', 'd', 'e', 'c', 'd', 'e']);
let mut numbers = vec![0, 1, 2, 3, 4];
numbers.extend_from_within(..2);
assert_eq!(numbers, [0, 1, 2, 3, 4, 0, 1]);
let mut strings = vec![String::from("hello"), String::from("world"), String::from("!")];
strings.extend_from_within(1..=2);
assert_eq!(strings, ["hello", "world", "!", "world", "!"]);
1.21.0 · Sourcepub fn splice<R, I>(
&mut self,
range: R,
replace_with: I,
) -> Splice<'_, <I as IntoIterator>::IntoIter, A> ⓘ
pub fn splice<R, I>( &mut self, range: R, replace_with: I, ) -> Splice<'_, <I as IntoIterator>::IntoIter, A> ⓘ
Creates a splicing iterator that replaces the specified range in the vector
with the given replace_with
iterator and yields the removed items.
replace_with
does not need to be the same length as range
.
range
is removed even if the Splice
iterator is not consumed before it is dropped.
It is unspecified how many elements are removed from the vector
if the Splice
value is leaked.
The input iterator replace_with
is only consumed when the Splice
value is dropped.
This is optimal if:
- The tail (elements in the vector after
range
) is empty, - or
replace_with
yields fewer or equal elements thanrange
’s length - or the lower bound of its
size_hint()
is exact.
Otherwise, a temporary vector is allocated and the tail is moved twice.
§Panics
Panics if the starting point is greater than the end point or if the end point is greater than the length of the vector.
§Examples
let mut v = vec![1, 2, 3, 4];
let new = [7, 8, 9];
let u: Vec<_> = v.splice(1..3, new).collect();
assert_eq!(v, [1, 7, 8, 9, 4]);
assert_eq!(u, [2, 3]);
Using splice
to insert new items into a vector efficiently at a specific position
indicated by an empty range:
let mut v = vec![1, 5];
let new = [2, 3, 4];
v.splice(1..1, new);
assert_eq!(v, [1, 2, 3, 4, 5]);
1.87.0 · Sourcepub fn extract_if<F, R>(
&mut self,
range: R,
filter: F,
) -> ExtractIf<'_, T, F, A> ⓘ
pub fn extract_if<F, R>( &mut self, range: R, filter: F, ) -> ExtractIf<'_, T, F, A> ⓘ
Creates an iterator which uses a closure to determine if element in the range should be removed.
If the closure returns true, then the element is removed and yielded. If the closure returns false, the element will remain in the vector and will not be yielded by the iterator.
Only elements that fall in the provided range are considered for extraction, but any elements after the range will still have to be moved if any element has been extracted.
If the returned ExtractIf
is not exhausted, e.g. because it is dropped without iterating
or the iteration short-circuits, then the remaining elements will be retained.
Use retain
with a negated predicate if you do not need the returned iterator.
Using this method is equivalent to the following code:
let mut i = range.start;
while i < min(vec.len(), range.end) {
if some_predicate(&mut vec[i]) {
let val = vec.remove(i);
// your code here
} else {
i += 1;
}
}
But extract_if
is easier to use. extract_if
is also more efficient,
because it can backshift the elements of the array in bulk.
Note that extract_if
also lets you mutate the elements passed to the filter closure,
regardless of whether you choose to keep or remove them.
§Panics
If range
is out of bounds.
§Examples
Splitting an array into evens and odds, reusing the original allocation:
let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
let evens = numbers.extract_if(.., |x| *x % 2 == 0).collect::<Vec<_>>();
let odds = numbers;
assert_eq!(evens, vec![2, 4, 6, 8, 14]);
assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
Using the range argument to only process a part of the vector:
let mut items = vec![0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2];
let ones = items.extract_if(7.., |x| *x == 1).collect::<Vec<_>>();
assert_eq!(items, vec![0, 0, 0, 0, 0, 0, 0, 2, 2, 2]);
assert_eq!(ones.len(), 3);
Methods from Deref<Target = [T]>§
1.0.0 · Sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Returns true
if the slice has a length of 0.
§Examples
let a = [1, 2, 3];
assert!(!a.is_empty());
let b: &[i32] = &[];
assert!(b.is_empty());
1.0.0 · Sourcepub fn first(&self) -> Option<&T>
pub fn first(&self) -> Option<&T>
Returns the first element of the slice, or None
if it is empty.
§Examples
let v = [10, 40, 30];
assert_eq!(Some(&10), v.first());
let w: &[i32] = &[];
assert_eq!(None, w.first());
1.0.0 · Sourcepub fn first_mut(&mut self) -> Option<&mut T>
pub fn first_mut(&mut self) -> Option<&mut T>
Returns a mutable reference to the first element of the slice, or None
if it is empty.
§Examples
let x = &mut [0, 1, 2];
if let Some(first) = x.first_mut() {
*first = 5;
}
assert_eq!(x, &[5, 1, 2]);
let y: &mut [i32] = &mut [];
assert_eq!(None, y.first_mut());
1.5.0 · Sourcepub fn split_first(&self) -> Option<(&T, &[T])>
pub fn split_first(&self) -> Option<(&T, &[T])>
Returns the first and all the rest of the elements of the slice, or None
if it is empty.
§Examples
let x = &[0, 1, 2];
if let Some((first, elements)) = x.split_first() {
assert_eq!(first, &0);
assert_eq!(elements, &[1, 2]);
}
1.5.0 · Sourcepub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])>
pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])>
Returns the first and all the rest of the elements of the slice, or None
if it is empty.
§Examples
let x = &mut [0, 1, 2];
if let Some((first, elements)) = x.split_first_mut() {
*first = 3;
elements[0] = 4;
elements[1] = 5;
}
assert_eq!(x, &[3, 4, 5]);
1.5.0 · Sourcepub fn split_last(&self) -> Option<(&T, &[T])>
pub fn split_last(&self) -> Option<(&T, &[T])>
Returns the last and all the rest of the elements of the slice, or None
if it is empty.
§Examples
let x = &[0, 1, 2];
if let Some((last, elements)) = x.split_last() {
assert_eq!(last, &2);
assert_eq!(elements, &[0, 1]);
}
1.5.0 · Sourcepub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])>
pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])>
Returns the last and all the rest of the elements of the slice, or None
if it is empty.
§Examples
let x = &mut [0, 1, 2];
if let Some((last, elements)) = x.split_last_mut() {
*last = 3;
elements[0] = 4;
elements[1] = 5;
}
assert_eq!(x, &[4, 5, 3]);
1.0.0 · Sourcepub fn last(&self) -> Option<&T>
pub fn last(&self) -> Option<&T>
Returns the last element of the slice, or None
if it is empty.
§Examples
let v = [10, 40, 30];
assert_eq!(Some(&30), v.last());
let w: &[i32] = &[];
assert_eq!(None, w.last());
1.0.0 · Sourcepub fn last_mut(&mut self) -> Option<&mut T>
pub fn last_mut(&mut self) -> Option<&mut T>
Returns a mutable reference to the last item in the slice, or None
if it is empty.
§Examples
let x = &mut [0, 1, 2];
if let Some(last) = x.last_mut() {
*last = 10;
}
assert_eq!(x, &[0, 1, 10]);
let y: &mut [i32] = &mut [];
assert_eq!(None, y.last_mut());
1.77.0 · Sourcepub fn first_chunk<const N: usize>(&self) -> Option<&[T; N]>
pub fn first_chunk<const N: usize>(&self) -> Option<&[T; N]>
Returns an array reference to the first N
items in the slice.
If the slice is not at least N
in length, this will return None
.
§Examples
let u = [10, 40, 30];
assert_eq!(Some(&[10, 40]), u.first_chunk::<2>());
let v: &[i32] = &[10];
assert_eq!(None, v.first_chunk::<2>());
let w: &[i32] = &[];
assert_eq!(Some(&[]), w.first_chunk::<0>());
1.77.0 · Sourcepub fn first_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>
pub fn first_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>
Returns a mutable array reference to the first N
items in the slice.
If the slice is not at least N
in length, this will return None
.
§Examples
let x = &mut [0, 1, 2];
if let Some(first) = x.first_chunk_mut::<2>() {
first[0] = 5;
first[1] = 4;
}
assert_eq!(x, &[5, 4, 2]);
assert_eq!(None, x.first_chunk_mut::<4>());
1.77.0 · Sourcepub fn split_first_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>
pub fn split_first_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>
Returns an array reference to the first N
items in the slice and the remaining slice.
If the slice is not at least N
in length, this will return None
.
§Examples
let x = &[0, 1, 2];
if let Some((first, elements)) = x.split_first_chunk::<2>() {
assert_eq!(first, &[0, 1]);
assert_eq!(elements, &[2]);
}
assert_eq!(None, x.split_first_chunk::<4>());
1.77.0 · Sourcepub fn split_first_chunk_mut<const N: usize>(
&mut self,
) -> Option<(&mut [T; N], &mut [T])>
pub fn split_first_chunk_mut<const N: usize>( &mut self, ) -> Option<(&mut [T; N], &mut [T])>
Returns a mutable array reference to the first N
items in the slice and the remaining
slice.
If the slice is not at least N
in length, this will return None
.
§Examples
let x = &mut [0, 1, 2];
if let Some((first, elements)) = x.split_first_chunk_mut::<2>() {
first[0] = 3;
first[1] = 4;
elements[0] = 5;
}
assert_eq!(x, &[3, 4, 5]);
assert_eq!(None, x.split_first_chunk_mut::<4>());
1.77.0 · Sourcepub fn split_last_chunk<const N: usize>(&self) -> Option<(&[T], &[T; N])>
pub fn split_last_chunk<const N: usize>(&self) -> Option<(&[T], &[T; N])>
Returns an array reference to the last N
items in the slice and the remaining slice.
If the slice is not at least N
in length, this will return None
.
§Examples
let x = &[0, 1, 2];
if let Some((elements, last)) = x.split_last_chunk::<2>() {
assert_eq!(elements, &[0]);
assert_eq!(last, &[1, 2]);
}
assert_eq!(None, x.split_last_chunk::<4>());
1.77.0 · Sourcepub fn split_last_chunk_mut<const N: usize>(
&mut self,
) -> Option<(&mut [T], &mut [T; N])>
pub fn split_last_chunk_mut<const N: usize>( &mut self, ) -> Option<(&mut [T], &mut [T; N])>
Returns a mutable array reference to the last N
items in the slice and the remaining
slice.
If the slice is not at least N
in length, this will return None
.
§Examples
let x = &mut [0, 1, 2];
if let Some((elements, last)) = x.split_last_chunk_mut::<2>() {
last[0] = 3;
last[1] = 4;
elements[0] = 5;
}
assert_eq!(x, &[5, 3, 4]);
assert_eq!(None, x.split_last_chunk_mut::<4>());
1.77.0 · Sourcepub fn last_chunk<const N: usize>(&self) -> Option<&[T; N]>
pub fn last_chunk<const N: usize>(&self) -> Option<&[T; N]>
Returns an array reference to the last N
items in the slice.
If the slice is not at least N
in length, this will return None
.
§Examples
let u = [10, 40, 30];
assert_eq!(Some(&[40, 30]), u.last_chunk::<2>());
let v: &[i32] = &[10];
assert_eq!(None, v.last_chunk::<2>());
let w: &[i32] = &[];
assert_eq!(Some(&[]), w.last_chunk::<0>());
1.77.0 · Sourcepub fn last_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>
pub fn last_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>
Returns a mutable array reference to the last N
items in the slice.
If the slice is not at least N
in length, this will return None
.
§Examples
let x = &mut [0, 1, 2];
if let Some(last) = x.last_chunk_mut::<2>() {
last[0] = 10;
last[1] = 20;
}
assert_eq!(x, &[0, 10, 20]);
assert_eq!(None, x.last_chunk_mut::<4>());
1.0.0 · Sourcepub fn get<I>(&self, index: I) -> Option<&<I as SliceIndex<[T]>>::Output>where
I: SliceIndex<[T]>,
pub fn get<I>(&self, index: I) -> Option<&<I as SliceIndex<[T]>>::Output>where
I: SliceIndex<[T]>,
Returns a reference to an element or subslice depending on the type of index.
- If given a position, returns a reference to the element at that
position or
None
if out of bounds. - If given a range, returns the subslice corresponding to that range,
or
None
if out of bounds.
§Examples
let v = [10, 40, 30];
assert_eq!(Some(&40), v.get(1));
assert_eq!(Some(&[10, 40][..]), v.get(0..2));
assert_eq!(None, v.get(3));
assert_eq!(None, v.get(0..4));
1.0.0 · Sourcepub fn get_mut<I>(
&mut self,
index: I,
) -> Option<&mut <I as SliceIndex<[T]>>::Output>where
I: SliceIndex<[T]>,
pub fn get_mut<I>(
&mut self,
index: I,
) -> Option<&mut <I as SliceIndex<[T]>>::Output>where
I: SliceIndex<[T]>,
1.0.0 · Sourcepub unsafe fn get_unchecked<I>(
&self,
index: I,
) -> &<I as SliceIndex<[T]>>::Outputwhere
I: SliceIndex<[T]>,
pub unsafe fn get_unchecked<I>(
&self,
index: I,
) -> &<I as SliceIndex<[T]>>::Outputwhere
I: SliceIndex<[T]>,
Returns a reference to an element or subslice, without doing bounds checking.
For a safe alternative see get
.
§Safety
Calling this method with an out-of-bounds index is undefined behavior even if the resulting reference is not used.
You can think of this like .get(index).unwrap_unchecked()
. It’s UB
to call .get_unchecked(len)
, even if you immediately convert to a
pointer. And it’s UB to call .get_unchecked(..len + 1)
,
.get_unchecked(..=len)
, or similar.
§Examples
let x = &[1, 2, 4];
unsafe {
assert_eq!(x.get_unchecked(1), &2);
}
1.0.0 · Sourcepub unsafe fn get_unchecked_mut<I>(
&mut self,
index: I,
) -> &mut <I as SliceIndex<[T]>>::Outputwhere
I: SliceIndex<[T]>,
pub unsafe fn get_unchecked_mut<I>(
&mut self,
index: I,
) -> &mut <I as SliceIndex<[T]>>::Outputwhere
I: SliceIndex<[T]>,
Returns a mutable reference to an element or subslice, without doing bounds checking.
For a safe alternative see get_mut
.
§Safety
Calling this method with an out-of-bounds index is undefined behavior even if the resulting reference is not used.
You can think of this like .get_mut(index).unwrap_unchecked()
. It’s
UB to call .get_unchecked_mut(len)
, even if you immediately convert
to a pointer. And it’s UB to call .get_unchecked_mut(..len + 1)
,
.get_unchecked_mut(..=len)
, or similar.
§Examples
let x = &mut [1, 2, 4];
unsafe {
let elem = x.get_unchecked_mut(1);
*elem = 13;
}
assert_eq!(x, &[1, 13, 4]);
1.0.0 · Sourcepub fn as_ptr(&self) -> *const T
pub fn as_ptr(&self) -> *const T
Returns a raw pointer to the slice’s buffer.
The caller must ensure that the slice outlives the pointer this function returns, or else it will end up dangling.
The caller must also ensure that the memory the pointer (non-transitively) points to
is never written to (except inside an UnsafeCell
) using this pointer or any pointer
derived from it. If you need to mutate the contents of the slice, use as_mut_ptr
.
Modifying the container referenced by this slice may cause its buffer to be reallocated, which would also make any pointers to it invalid.
§Examples
let x = &[1, 2, 4];
let x_ptr = x.as_ptr();
unsafe {
for i in 0..x.len() {
assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
}
}
1.0.0 · Sourcepub fn as_mut_ptr(&mut self) -> *mut T
pub fn as_mut_ptr(&mut self) -> *mut T
Returns an unsafe mutable pointer to the slice’s buffer.
The caller must ensure that the slice outlives the pointer this function returns, or else it will end up dangling.
Modifying the container referenced by this slice may cause its buffer to be reallocated, which would also make any pointers to it invalid.
§Examples
let x = &mut [1, 2, 4];
let x_ptr = x.as_mut_ptr();
unsafe {
for i in 0..x.len() {
*x_ptr.add(i) += 2;
}
}
assert_eq!(x, &[3, 4, 6]);
1.48.0 · Sourcepub fn as_ptr_range(&self) -> Range<*const T> ⓘ
pub fn as_ptr_range(&self) -> Range<*const T> ⓘ
Returns the two raw pointers spanning the slice.
The returned range is half-open, which means that the end pointer points one past the last element of the slice. This way, an empty slice is represented by two equal pointers, and the difference between the two pointers represents the size of the slice.
See as_ptr
for warnings on using these pointers. The end pointer
requires extra caution, as it does not point to a valid element in the
slice.
This function is useful for interacting with foreign interfaces which use two pointers to refer to a range of elements in memory, as is common in C++.
It can also be useful to check if a pointer to an element refers to an element of this slice:
let a = [1, 2, 3];
let x = &a[1] as *const _;
let y = &5 as *const _;
assert!(a.as_ptr_range().contains(&x));
assert!(!a.as_ptr_range().contains(&y));
1.48.0 · Sourcepub fn as_mut_ptr_range(&mut self) -> Range<*mut T> ⓘ
pub fn as_mut_ptr_range(&mut self) -> Range<*mut T> ⓘ
Returns the two unsafe mutable pointers spanning the slice.
The returned range is half-open, which means that the end pointer points one past the last element of the slice. This way, an empty slice is represented by two equal pointers, and the difference between the two pointers represents the size of the slice.
See as_mut_ptr
for warnings on using these pointers. The end
pointer requires extra caution, as it does not point to a valid element
in the slice.
This function is useful for interacting with foreign interfaces which use two pointers to refer to a range of elements in memory, as is common in C++.
Sourcepub fn as_array<const N: usize>(&self) -> Option<&[T; N]>
🔬This is a nightly-only experimental API. (slice_as_array
)
pub fn as_array<const N: usize>(&self) -> Option<&[T; N]>
slice_as_array
)Gets a reference to the underlying array.
If N
is not exactly equal to the length of self
, then this method returns None
.
Sourcepub fn as_mut_array<const N: usize>(&mut self) -> Option<&mut [T; N]>
🔬This is a nightly-only experimental API. (slice_as_array
)
pub fn as_mut_array<const N: usize>(&mut self) -> Option<&mut [T; N]>
slice_as_array
)Gets a mutable reference to the slice’s underlying array.
If N
is not exactly equal to the length of self
, then this method returns None
.
1.0.0 · Sourcepub fn swap(&mut self, a: usize, b: usize)
pub fn swap(&mut self, a: usize, b: usize)
Swaps two elements in the slice.
If a
equals to b
, it’s guaranteed that elements won’t change value.
§Arguments
- a - The index of the first element
- b - The index of the second element
§Panics
Panics if a
or b
are out of bounds.
§Examples
let mut v = ["a", "b", "c", "d", "e"];
v.swap(2, 4);
assert!(v == ["a", "b", "e", "d", "c"]);
Sourcepub unsafe fn swap_unchecked(&mut self, a: usize, b: usize)
🔬This is a nightly-only experimental API. (slice_swap_unchecked
)
pub unsafe fn swap_unchecked(&mut self, a: usize, b: usize)
slice_swap_unchecked
)Swaps two elements in the slice, without doing bounds checking.
For a safe alternative see swap
.
§Arguments
- a - The index of the first element
- b - The index of the second element
§Safety
Calling this method with an out-of-bounds index is undefined behavior.
The caller has to ensure that a < self.len()
and b < self.len()
.
§Examples
#![feature(slice_swap_unchecked)]
let mut v = ["a", "b", "c", "d"];
// SAFETY: we know that 1 and 3 are both indices of the slice
unsafe { v.swap_unchecked(1, 3) };
assert!(v == ["a", "d", "c", "b"]);
1.0.0 · Sourcepub fn reverse(&mut self)
pub fn reverse(&mut self)
Reverses the order of elements in the slice, in place.
§Examples
let mut v = [1, 2, 3];
v.reverse();
assert!(v == [3, 2, 1]);
1.0.0 · Sourcepub fn iter(&self) -> Iter<'_, T> ⓘ
pub fn iter(&self) -> Iter<'_, T> ⓘ
Returns an iterator over the slice.
The iterator yields all items from start to end.
§Examples
let x = &[1, 2, 4];
let mut iterator = x.iter();
assert_eq!(iterator.next(), Some(&1));
assert_eq!(iterator.next(), Some(&2));
assert_eq!(iterator.next(), Some(&4));
assert_eq!(iterator.next(), None);
1.0.0 · Sourcepub fn iter_mut(&mut self) -> IterMut<'_, T> ⓘ
pub fn iter_mut(&mut self) -> IterMut<'_, T> ⓘ
Returns an iterator that allows modifying each value.
The iterator yields all items from start to end.
§Examples
let x = &mut [1, 2, 4];
for elem in x.iter_mut() {
*elem += 2;
}
assert_eq!(x, &[3, 4, 6]);
1.0.0 · Sourcepub fn windows(&self, size: usize) -> Windows<'_, T> ⓘ
pub fn windows(&self, size: usize) -> Windows<'_, T> ⓘ
Returns an iterator over all contiguous windows of length
size
. The windows overlap. If the slice is shorter than
size
, the iterator returns no values.
§Panics
Panics if size
is zero.
§Examples
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.windows(3);
assert_eq!(iter.next().unwrap(), &['l', 'o', 'r']);
assert_eq!(iter.next().unwrap(), &['o', 'r', 'e']);
assert_eq!(iter.next().unwrap(), &['r', 'e', 'm']);
assert!(iter.next().is_none());
If the slice is shorter than size
:
let slice = ['f', 'o', 'o'];
let mut iter = slice.windows(4);
assert!(iter.next().is_none());
Because the Iterator trait cannot represent the required lifetimes,
there is no windows_mut
analog to windows
;
[0,1,2].windows_mut(2).collect()
would violate the rules of references
(though a LendingIterator analog is possible). You can sometimes use
Cell::as_slice_of_cells
in
conjunction with windows
instead:
use std::cell::Cell;
let mut array = ['R', 'u', 's', 't', ' ', '2', '0', '1', '5'];
let slice = &mut array[..];
let slice_of_cells: &[Cell<char>] = Cell::from_mut(slice).as_slice_of_cells();
for w in slice_of_cells.windows(3) {
Cell::swap(&w[0], &w[2]);
}
assert_eq!(array, ['s', 't', ' ', '2', '0', '1', '5', 'u', 'R']);
1.0.0 · Sourcepub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T> ⓘ
pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T> ⓘ
Returns an iterator over chunk_size
elements of the slice at a time, starting at the
beginning of the slice.
The chunks are slices and do not overlap. If chunk_size
does not divide the length of the
slice, then the last chunk will not have length chunk_size
.
See chunks_exact
for a variant of this iterator that returns chunks of always exactly
chunk_size
elements, and rchunks
for the same iterator but starting at the end of the
slice.
§Panics
Panics if chunk_size
is zero.
§Examples
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.chunks(2);
assert_eq!(iter.next().unwrap(), &['l', 'o']);
assert_eq!(iter.next().unwrap(), &['r', 'e']);
assert_eq!(iter.next().unwrap(), &['m']);
assert!(iter.next().is_none());
1.0.0 · Sourcepub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T> ⓘ
pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T> ⓘ
Returns an iterator over chunk_size
elements of the slice at a time, starting at the
beginning of the slice.
The chunks are mutable slices, and do not overlap. If chunk_size
does not divide the
length of the slice, then the last chunk will not have length chunk_size
.
See chunks_exact_mut
for a variant of this iterator that returns chunks of always
exactly chunk_size
elements, and rchunks_mut
for the same iterator but starting at
the end of the slice.
§Panics
Panics if chunk_size
is zero.
§Examples
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;
for chunk in v.chunks_mut(2) {
for elem in chunk.iter_mut() {
*elem += count;
}
count += 1;
}
assert_eq!(v, &[1, 1, 2, 2, 3]);
1.31.0 · Sourcepub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T> ⓘ
pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T> ⓘ
Returns an iterator over chunk_size
elements of the slice at a time, starting at the
beginning of the slice.
The chunks are slices and do not overlap. If chunk_size
does not divide the length of the
slice, then the last up to chunk_size-1
elements will be omitted and can be retrieved
from the remainder
function of the iterator.
Due to each chunk having exactly chunk_size
elements, the compiler can often optimize the
resulting code better than in the case of chunks
.
See chunks
for a variant of this iterator that also returns the remainder as a smaller
chunk, and rchunks_exact
for the same iterator but starting at the end of the slice.
§Panics
Panics if chunk_size
is zero.
§Examples
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.chunks_exact(2);
assert_eq!(iter.next().unwrap(), &['l', 'o']);
assert_eq!(iter.next().unwrap(), &['r', 'e']);
assert!(iter.next().is_none());
assert_eq!(iter.remainder(), &['m']);
1.31.0 · Sourcepub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T> ⓘ
pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T> ⓘ
Returns an iterator over chunk_size
elements of the slice at a time, starting at the
beginning of the slice.
The chunks are mutable slices, and do not overlap. If chunk_size
does not divide the
length of the slice, then the last up to chunk_size-1
elements will be omitted and can be
retrieved from the into_remainder
function of the iterator.
Due to each chunk having exactly chunk_size
elements, the compiler can often optimize the
resulting code better than in the case of chunks_mut
.
See chunks_mut
for a variant of this iterator that also returns the remainder as a
smaller chunk, and rchunks_exact_mut
for the same iterator but starting at the end of
the slice.
§Panics
Panics if chunk_size
is zero.
§Examples
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;
for chunk in v.chunks_exact_mut(2) {
for elem in chunk.iter_mut() {
*elem += count;
}
count += 1;
}
assert_eq!(v, &[1, 1, 2, 2, 0]);
Sourcepub unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]]
🔬This is a nightly-only experimental API. (slice_as_chunks
)
pub unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]]
slice_as_chunks
)Splits the slice into a slice of N
-element arrays,
assuming that there’s no remainder.
§Safety
This may only be called when
- The slice splits exactly into
N
-element chunks (akaself.len() % N == 0
). N != 0
.
§Examples
#![feature(slice_as_chunks)]
let slice: &[char] = &['l', 'o', 'r', 'e', 'm', '!'];
let chunks: &[[char; 1]] =
// SAFETY: 1-element chunks never have remainder
unsafe { slice.as_chunks_unchecked() };
assert_eq!(chunks, &[['l'], ['o'], ['r'], ['e'], ['m'], ['!']]);
let chunks: &[[char; 3]] =
// SAFETY: The slice length (6) is a multiple of 3
unsafe { slice.as_chunks_unchecked() };
assert_eq!(chunks, &[['l', 'o', 'r'], ['e', 'm', '!']]);
// These would be unsound:
// let chunks: &[[_; 5]] = slice.as_chunks_unchecked() // The slice length is not a multiple of 5
// let chunks: &[[_; 0]] = slice.as_chunks_unchecked() // Zero-length chunks are never allowed
Sourcepub fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T])
🔬This is a nightly-only experimental API. (slice_as_chunks
)
pub fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T])
slice_as_chunks
)Splits the slice into a slice of N
-element arrays,
starting at the beginning of the slice,
and a remainder slice with length strictly less than N
.
§Panics
Panics if N
is zero. This check will most probably get changed to a compile time
error before this method gets stabilized.
§Examples
#![feature(slice_as_chunks)]
let slice = ['l', 'o', 'r', 'e', 'm'];
let (chunks, remainder) = slice.as_chunks();
assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]);
assert_eq!(remainder, &['m']);
If you expect the slice to be an exact multiple, you can combine
let
-else
with an empty slice pattern:
#![feature(slice_as_chunks)]
let slice = ['R', 'u', 's', 't'];
let (chunks, []) = slice.as_chunks::<2>() else {
panic!("slice didn't have even length")
};
assert_eq!(chunks, &[['R', 'u'], ['s', 't']]);
Sourcepub fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]])
🔬This is a nightly-only experimental API. (slice_as_chunks
)
pub fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]])
slice_as_chunks
)Splits the slice into a slice of N
-element arrays,
starting at the end of the slice,
and a remainder slice with length strictly less than N
.
§Panics
Panics if N
is zero. This check will most probably get changed to a compile time
error before this method gets stabilized.
§Examples
#![feature(slice_as_chunks)]
let slice = ['l', 'o', 'r', 'e', 'm'];
let (remainder, chunks) = slice.as_rchunks();
assert_eq!(remainder, &['l']);
assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]);
Sourcepub fn array_chunks<const N: usize>(&self) -> ArrayChunks<'_, T, N> ⓘ
🔬This is a nightly-only experimental API. (array_chunks
)
pub fn array_chunks<const N: usize>(&self) -> ArrayChunks<'_, T, N> ⓘ
array_chunks
)Returns an iterator over N
elements of the slice at a time, starting at the
beginning of the slice.
The chunks are array references and do not overlap. If N
does not divide the
length of the slice, then the last up to N-1
elements will be omitted and can be
retrieved from the remainder
function of the iterator.
This method is the const generic equivalent of chunks_exact
.
§Panics
Panics if N
is zero. This check will most probably get changed to a compile time
error before this method gets stabilized.
§Examples
#![feature(array_chunks)]
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.array_chunks();
assert_eq!(iter.next().unwrap(), &['l', 'o']);
assert_eq!(iter.next().unwrap(), &['r', 'e']);
assert!(iter.next().is_none());
assert_eq!(iter.remainder(), &['m']);
Sourcepub unsafe fn as_chunks_unchecked_mut<const N: usize>(
&mut self,
) -> &mut [[T; N]]
🔬This is a nightly-only experimental API. (slice_as_chunks
)
pub unsafe fn as_chunks_unchecked_mut<const N: usize>( &mut self, ) -> &mut [[T; N]]
slice_as_chunks
)Splits the slice into a slice of N
-element arrays,
assuming that there’s no remainder.
§Safety
This may only be called when
- The slice splits exactly into
N
-element chunks (akaself.len() % N == 0
). N != 0
.
§Examples
#![feature(slice_as_chunks)]
let slice: &mut [char] = &mut ['l', 'o', 'r', 'e', 'm', '!'];
let chunks: &mut [[char; 1]] =
// SAFETY: 1-element chunks never have remainder
unsafe { slice.as_chunks_unchecked_mut() };
chunks[0] = ['L'];
assert_eq!(chunks, &[['L'], ['o'], ['r'], ['e'], ['m'], ['!']]);
let chunks: &mut [[char; 3]] =
// SAFETY: The slice length (6) is a multiple of 3
unsafe { slice.as_chunks_unchecked_mut() };
chunks[1] = ['a', 'x', '?'];
assert_eq!(slice, &['L', 'o', 'r', 'a', 'x', '?']);
// These would be unsound:
// let chunks: &[[_; 5]] = slice.as_chunks_unchecked_mut() // The slice length is not a multiple of 5
// let chunks: &[[_; 0]] = slice.as_chunks_unchecked_mut() // Zero-length chunks are never allowed
Sourcepub fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T])
🔬This is a nightly-only experimental API. (slice_as_chunks
)
pub fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T])
slice_as_chunks
)Splits the slice into a slice of N
-element arrays,
starting at the beginning of the slice,
and a remainder slice with length strictly less than N
.
§Panics
Panics if N
is zero. This check will most probably get changed to a compile time
error before this method gets stabilized.
§Examples
#![feature(slice_as_chunks)]
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;
let (chunks, remainder) = v.as_chunks_mut();
remainder[0] = 9;
for chunk in chunks {
*chunk = [count; 2];
count += 1;
}
assert_eq!(v, &[1, 1, 2, 2, 9]);
Sourcepub fn as_rchunks_mut<const N: usize>(&mut self) -> (&mut [T], &mut [[T; N]])
🔬This is a nightly-only experimental API. (slice_as_chunks
)
pub fn as_rchunks_mut<const N: usize>(&mut self) -> (&mut [T], &mut [[T; N]])
slice_as_chunks
)Splits the slice into a slice of N
-element arrays,
starting at the end of the slice,
and a remainder slice with length strictly less than N
.
§Panics
Panics if N
is zero. This check will most probably get changed to a compile time
error before this method gets stabilized.
§Examples
#![feature(slice_as_chunks)]
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;
let (remainder, chunks) = v.as_rchunks_mut();
remainder[0] = 9;
for chunk in chunks {
*chunk = [count; 2];
count += 1;
}
assert_eq!(v, &[9, 1, 1, 2, 2]);
Sourcepub fn array_chunks_mut<const N: usize>(&mut self) -> ArrayChunksMut<'_, T, N> ⓘ
🔬This is a nightly-only experimental API. (array_chunks
)
pub fn array_chunks_mut<const N: usize>(&mut self) -> ArrayChunksMut<'_, T, N> ⓘ
array_chunks
)Returns an iterator over N
elements of the slice at a time, starting at the
beginning of the slice.
The chunks are mutable array references and do not overlap. If N
does not divide
the length of the slice, then the last up to N-1
elements will be omitted and
can be retrieved from the into_remainder
function of the iterator.
This method is the const generic equivalent of chunks_exact_mut
.
§Panics
Panics if N
is zero. This check will most probably get changed to a compile time
error before this method gets stabilized.
§Examples
#![feature(array_chunks)]
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;
for chunk in v.array_chunks_mut() {
*chunk = [count; 2];
count += 1;
}
assert_eq!(v, &[1, 1, 2, 2, 0]);
Sourcepub fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N> ⓘ
🔬This is a nightly-only experimental API. (array_windows
)
pub fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N> ⓘ
array_windows
)Returns an iterator over overlapping windows of N
elements of a slice,
starting at the beginning of the slice.
This is the const generic equivalent of windows
.
If N
is greater than the size of the slice, it will return no windows.
§Panics
Panics if N
is zero. This check will most probably get changed to a compile time
error before this method gets stabilized.
§Examples
#![feature(array_windows)]
let slice = [0, 1, 2, 3];
let mut iter = slice.array_windows();
assert_eq!(iter.next().unwrap(), &[0, 1]);
assert_eq!(iter.next().unwrap(), &[1, 2]);
assert_eq!(iter.next().unwrap(), &[2, 3]);
assert!(iter.next().is_none());
1.31.0 · Sourcepub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> ⓘ
pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> ⓘ
Returns an iterator over chunk_size
elements of the slice at a time, starting at the end
of the slice.
The chunks are slices and do not overlap. If chunk_size
does not divide the length of the
slice, then the last chunk will not have length chunk_size
.
See rchunks_exact
for a variant of this iterator that returns chunks of always exactly
chunk_size
elements, and chunks
for the same iterator but starting at the beginning
of the slice.
§Panics
Panics if chunk_size
is zero.
§Examples
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.rchunks(2);
assert_eq!(iter.next().unwrap(), &['e', 'm']);
assert_eq!(iter.next().unwrap(), &['o', 'r']);
assert_eq!(iter.next().unwrap(), &['l']);
assert!(iter.next().is_none());
1.31.0 · Sourcepub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T> ⓘ
pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T> ⓘ
Returns an iterator over chunk_size
elements of the slice at a time, starting at the end
of the slice.
The chunks are mutable slices, and do not overlap. If chunk_size
does not divide the
length of the slice, then the last chunk will not have length chunk_size
.
See rchunks_exact_mut
for a variant of this iterator that returns chunks of always
exactly chunk_size
elements, and chunks_mut
for the same iterator but starting at the
beginning of the slice.
§Panics
Panics if chunk_size
is zero.
§Examples
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;
for chunk in v.rchunks_mut(2) {
for elem in chunk.iter_mut() {
*elem += count;
}
count += 1;
}
assert_eq!(v, &[3, 2, 2, 1, 1]);
1.31.0 · Sourcepub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> ⓘ
pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> ⓘ
Returns an iterator over chunk_size
elements of the slice at a time, starting at the
end of the slice.
The chunks are slices and do not overlap. If chunk_size
does not divide the length of the
slice, then the last up to chunk_size-1
elements will be omitted and can be retrieved
from the remainder
function of the iterator.
Due to each chunk having exactly chunk_size
elements, the compiler can often optimize the
resulting code better than in the case of rchunks
.
See rchunks
for a variant of this iterator that also returns the remainder as a smaller
chunk, and chunks_exact
for the same iterator but starting at the beginning of the
slice.
§Panics
Panics if chunk_size
is zero.
§Examples
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.rchunks_exact(2);
assert_eq!(iter.next().unwrap(), &['e', 'm']);
assert_eq!(iter.next().unwrap(), &['o', 'r']);
assert!(iter.next().is_none());
assert_eq!(iter.remainder(), &['l']);
1.31.0 · Sourcepub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T> ⓘ
pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T> ⓘ
Returns an iterator over chunk_size
elements of the slice at a time, starting at the end
of the slice.
The chunks are mutable slices, and do not overlap. If chunk_size
does not divide the
length of the slice, then the last up to chunk_size-1
elements will be omitted and can be
retrieved from the into_remainder
function of the iterator.
Due to each chunk having exactly chunk_size
elements, the compiler can often optimize the
resulting code better than in the case of chunks_mut
.
See rchunks_mut
for a variant of this iterator that also returns the remainder as a
smaller chunk, and chunks_exact_mut
for the same iterator but starting at the beginning
of the slice.
§Panics
Panics if chunk_size
is zero.
§Examples
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;
for chunk in v.rchunks_exact_mut(2) {
for elem in chunk.iter_mut() {
*elem += count;
}
count += 1;
}
assert_eq!(v, &[0, 2, 2, 1, 1]);
1.77.0 · Sourcepub fn chunk_by<F>(&self, pred: F) -> ChunkBy<'_, T, F> ⓘ
pub fn chunk_by<F>(&self, pred: F) -> ChunkBy<'_, T, F> ⓘ
Returns an iterator over the slice producing non-overlapping runs of elements using the predicate to separate them.
The predicate is called for every pair of consecutive elements,
meaning that it is called on slice[0]
and slice[1]
,
followed by slice[1]
and slice[2]
, and so on.
§Examples
let slice = &[1, 1, 1, 3, 3, 2, 2, 2];
let mut iter = slice.chunk_by(|a, b| a == b);
assert_eq!(iter.next(), Some(&[1, 1, 1][..]));
assert_eq!(iter.next(), Some(&[3, 3][..]));
assert_eq!(iter.next(), Some(&[2, 2, 2][..]));
assert_eq!(iter.next(), None);
This method can be used to extract the sorted subslices:
let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4];
let mut iter = slice.chunk_by(|a, b| a <= b);
assert_eq!(iter.next(), Some(&[1, 1, 2, 3][..]));
assert_eq!(iter.next(), Some(&[2, 3][..]));
assert_eq!(iter.next(), Some(&[2, 3, 4][..]));
assert_eq!(iter.next(), None);
1.77.0 · Sourcepub fn chunk_by_mut<F>(&mut self, pred: F) -> ChunkByMut<'_, T, F> ⓘ
pub fn chunk_by_mut<F>(&mut self, pred: F) -> ChunkByMut<'_, T, F> ⓘ
Returns an iterator over the slice producing non-overlapping mutable runs of elements using the predicate to separate them.
The predicate is called for every pair of consecutive elements,
meaning that it is called on slice[0]
and slice[1]
,
followed by slice[1]
and slice[2]
, and so on.
§Examples
let slice = &mut [1, 1, 1, 3, 3, 2, 2, 2];
let mut iter = slice.chunk_by_mut(|a, b| a == b);
assert_eq!(iter.next(), Some(&mut [1, 1, 1][..]));
assert_eq!(iter.next(), Some(&mut [3, 3][..]));
assert_eq!(iter.next(), Some(&mut [2, 2, 2][..]));
assert_eq!(iter.next(), None);
This method can be used to extract the sorted subslices:
let slice = &mut [1, 1, 2, 3, 2, 3, 2, 3, 4];
let mut iter = slice.chunk_by_mut(|a, b| a <= b);
assert_eq!(iter.next(), Some(&mut [1, 1, 2, 3][..]));
assert_eq!(iter.next(), Some(&mut [2, 3][..]));
assert_eq!(iter.next(), Some(&mut [2, 3, 4][..]));
assert_eq!(iter.next(), None);
1.0.0 · Sourcepub fn split_at(&self, mid: usize) -> (&[T], &[T])
pub fn split_at(&self, mid: usize) -> (&[T], &[T])
Divides one slice into two at an index.
The first will contain all indices from [0, mid)
(excluding
the index mid
itself) and the second will contain all
indices from [mid, len)
(excluding the index len
itself).
§Panics
Panics if mid > len
. For a non-panicking alternative see
split_at_checked
.
§Examples
let v = ['a', 'b', 'c'];
{
let (left, right) = v.split_at(0);
assert_eq!(left, []);
assert_eq!(right, ['a', 'b', 'c']);
}
{
let (left, right) = v.split_at(2);
assert_eq!(left, ['a', 'b']);
assert_eq!(right, ['c']);
}
{
let (left, right) = v.split_at(3);
assert_eq!(left, ['a', 'b', 'c']);
assert_eq!(right, []);
}
1.0.0 · Sourcepub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T])
pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T])
Divides one mutable slice into two at an index.
The first will contain all indices from [0, mid)
(excluding
the index mid
itself) and the second will contain all
indices from [mid, len)
(excluding the index len
itself).
§Panics
Panics if mid > len
. For a non-panicking alternative see
split_at_mut_checked
.
§Examples
let mut v = [1, 0, 3, 0, 5, 6];
let (left, right) = v.split_at_mut(2);
assert_eq!(left, [1, 0]);
assert_eq!(right, [3, 0, 5, 6]);
left[1] = 2;
right[1] = 4;
assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1.79.0 · Sourcepub unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T])
pub unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T])
Divides one slice into two at an index, without doing bounds checking.
The first will contain all indices from [0, mid)
(excluding
the index mid
itself) and the second will contain all
indices from [mid, len)
(excluding the index len
itself).
For a safe alternative see split_at
.
§Safety
Calling this method with an out-of-bounds index is undefined behavior
even if the resulting reference is not used. The caller has to ensure that
0 <= mid <= self.len()
.
§Examples
let v = ['a', 'b', 'c'];
unsafe {
let (left, right) = v.split_at_unchecked(0);
assert_eq!(left, []);
assert_eq!(right, ['a', 'b', 'c']);
}
unsafe {
let (left, right) = v.split_at_unchecked(2);
assert_eq!(left, ['a', 'b']);
assert_eq!(right, ['c']);
}
unsafe {
let (left, right) = v.split_at_unchecked(3);
assert_eq!(left, ['a', 'b', 'c']);
assert_eq!(right, []);
}
1.79.0 · Sourcepub unsafe fn split_at_mut_unchecked(
&mut self,
mid: usize,
) -> (&mut [T], &mut [T])
pub unsafe fn split_at_mut_unchecked( &mut self, mid: usize, ) -> (&mut [T], &mut [T])
Divides one mutable slice into two at an index, without doing bounds checking.
The first will contain all indices from [0, mid)
(excluding
the index mid
itself) and the second will contain all
indices from [mid, len)
(excluding the index len
itself).
For a safe alternative see split_at_mut
.
§Safety
Calling this method with an out-of-bounds index is undefined behavior
even if the resulting reference is not used. The caller has to ensure that
0 <= mid <= self.len()
.
§Examples
let mut v = [1, 0, 3, 0, 5, 6];
// scoped to restrict the lifetime of the borrows
unsafe {
let (left, right) = v.split_at_mut_unchecked(2);
assert_eq!(left, [1, 0]);
assert_eq!(right, [3, 0, 5, 6]);
left[1] = 2;
right[1] = 4;
}
assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1.80.0 · Sourcepub fn split_at_checked(&self, mid: usize) -> Option<(&[T], &[T])>
pub fn split_at_checked(&self, mid: usize) -> Option<(&[T], &[T])>
Divides one slice into two at an index, returning None
if the slice is
too short.
If mid ≤ len
returns a pair of slices where the first will contain all
indices from [0, mid)
(excluding the index mid
itself) and the
second will contain all indices from [mid, len)
(excluding the index
len
itself).
Otherwise, if mid > len
, returns None
.
§Examples
let v = [1, -2, 3, -4, 5, -6];
{
let (left, right) = v.split_at_checked(0).unwrap();
assert_eq!(left, []);
assert_eq!(right, [1, -2, 3, -4, 5, -6]);
}
{
let (left, right) = v.split_at_checked(2).unwrap();
assert_eq!(left, [1, -2]);
assert_eq!(right, [3, -4, 5, -6]);
}
{
let (left, right) = v.split_at_checked(6).unwrap();
assert_eq!(left, [1, -2, 3, -4, 5, -6]);
assert_eq!(right, []);
}
assert_eq!(None, v.split_at_checked(7));
1.80.0 · Sourcepub fn split_at_mut_checked(
&mut self,
mid: usize,
) -> Option<(&mut [T], &mut [T])>
pub fn split_at_mut_checked( &mut self, mid: usize, ) -> Option<(&mut [T], &mut [T])>
Divides one mutable slice into two at an index, returning None
if the
slice is too short.
If mid ≤ len
returns a pair of slices where the first will contain all
indices from [0, mid)
(excluding the index mid
itself) and the
second will contain all indices from [mid, len)
(excluding the index
len
itself).
Otherwise, if mid > len
, returns None
.
§Examples
let mut v = [1, 0, 3, 0, 5, 6];
if let Some((left, right)) = v.split_at_mut_checked(2) {
assert_eq!(left, [1, 0]);
assert_eq!(right, [3, 0, 5, 6]);
left[1] = 2;
right[1] = 4;
}
assert_eq!(v, [1, 2, 3, 4, 5, 6]);
assert_eq!(None, v.split_at_mut_checked(7));
1.0.0 · Sourcepub fn split<F>(&self, pred: F) -> Split<'_, T, F> ⓘ
pub fn split<F>(&self, pred: F) -> Split<'_, T, F> ⓘ
Returns an iterator over subslices separated by elements that match
pred
. The matched element is not contained in the subslices.
§Examples
let slice = [10, 40, 33, 20];
let mut iter = slice.split(|num| num % 3 == 0);
assert_eq!(iter.next().unwrap(), &[10, 40]);
assert_eq!(iter.next().unwrap(), &[20]);
assert!(iter.next().is_none());
If the first element is matched, an empty slice will be the first item returned by the iterator. Similarly, if the last element in the slice is matched, an empty slice will be the last item returned by the iterator:
let slice = [10, 40, 33];
let mut iter = slice.split(|num| num % 3 == 0);
assert_eq!(iter.next().unwrap(), &[10, 40]);
assert_eq!(iter.next().unwrap(), &[]);
assert!(iter.next().is_none());
If two matched elements are directly adjacent, an empty slice will be present between them:
let slice = [10, 6, 33, 20];
let mut iter = slice.split(|num| num % 3 == 0);
assert_eq!(iter.next().unwrap(), &[10]);
assert_eq!(iter.next().unwrap(), &[]);
assert_eq!(iter.next().unwrap(), &[20]);
assert!(iter.next().is_none());
1.0.0 · Sourcepub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F> ⓘ
pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F> ⓘ
Returns an iterator over mutable subslices separated by elements that
match pred
. The matched element is not contained in the subslices.
§Examples
let mut v = [10, 40, 30, 20, 60, 50];
for group in v.split_mut(|num| *num % 3 == 0) {
group[0] = 1;
}
assert_eq!(v, [1, 40, 30, 1, 60, 1]);
1.51.0 · Sourcepub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F> ⓘ
pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F> ⓘ
Returns an iterator over subslices separated by elements that match
pred
. The matched element is contained in the end of the previous
subslice as a terminator.
§Examples
let slice = [10, 40, 33, 20];
let mut iter = slice.split_inclusive(|num| num % 3 == 0);
assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
assert_eq!(iter.next().unwrap(), &[20]);
assert!(iter.next().is_none());
If the last element of the slice is matched, that element will be considered the terminator of the preceding slice. That slice will be the last item returned by the iterator.
let slice = [3, 10, 40, 33];
let mut iter = slice.split_inclusive(|num| num % 3 == 0);
assert_eq!(iter.next().unwrap(), &[3]);
assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
assert!(iter.next().is_none());
1.51.0 · Sourcepub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F> ⓘ
pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F> ⓘ
Returns an iterator over mutable subslices separated by elements that
match pred
. The matched element is contained in the previous
subslice as a terminator.
§Examples
let mut v = [10, 40, 30, 20, 60, 50];
for group in v.split_inclusive_mut(|num| *num % 3 == 0) {
let terminator_idx = group.len()-1;
group[terminator_idx] = 1;
}
assert_eq!(v, [10, 40, 1, 20, 1, 1]);
1.27.0 · Sourcepub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F> ⓘ
pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F> ⓘ
Returns an iterator over subslices separated by elements that match
pred
, starting at the end of the slice and working backwards.
The matched element is not contained in the subslices.
§Examples
let slice = [11, 22, 33, 0, 44, 55];
let mut iter = slice.rsplit(|num| *num == 0);
assert_eq!(iter.next().unwrap(), &[44, 55]);
assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
assert_eq!(iter.next(), None);
As with split()
, if the first or last element is matched, an empty
slice will be the first (or last) item returned by the iterator.
let v = &[0, 1, 1, 2, 3, 5, 8];
let mut it = v.rsplit(|n| *n % 2 == 0);
assert_eq!(it.next().unwrap(), &[]);
assert_eq!(it.next().unwrap(), &[3, 5]);
assert_eq!(it.next().unwrap(), &[1, 1]);
assert_eq!(it.next().unwrap(), &[]);
assert_eq!(it.next(), None);
1.27.0 · Sourcepub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F> ⓘ
pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F> ⓘ
Returns an iterator over mutable subslices separated by elements that
match pred
, starting at the end of the slice and working
backwards. The matched element is not contained in the subslices.
§Examples
let mut v = [100, 400, 300, 200, 600, 500];
let mut count = 0;
for group in v.rsplit_mut(|num| *num % 3 == 0) {
count += 1;
group[0] = count;
}
assert_eq!(v, [3, 400, 300, 2, 600, 1]);
1.0.0 · Sourcepub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F> ⓘ
pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F> ⓘ
Returns an iterator over subslices separated by elements that match
pred
, limited to returning at most n
items. The matched element is
not contained in the subslices.
The last element returned, if any, will contain the remainder of the slice.
§Examples
Print the slice split once by numbers divisible by 3 (i.e., [10, 40]
,
[20, 60, 50]
):
let v = [10, 40, 30, 20, 60, 50];
for group in v.splitn(2, |num| *num % 3 == 0) {
println!("{group:?}");
}
1.0.0 · Sourcepub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F> ⓘ
pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F> ⓘ
Returns an iterator over mutable subslices separated by elements that match
pred
, limited to returning at most n
items. The matched element is
not contained in the subslices.
The last element returned, if any, will contain the remainder of the slice.
§Examples
let mut v = [10, 40, 30, 20, 60, 50];
for group in v.splitn_mut(2, |num| *num % 3 == 0) {
group[0] = 1;
}
assert_eq!(v, [1, 40, 30, 1, 60, 50]);
1.0.0 · Sourcepub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F> ⓘ
pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F> ⓘ
Returns an iterator over subslices separated by elements that match
pred
limited to returning at most n
items. This starts at the end of
the slice and works backwards. The matched element is not contained in
the subslices.
The last element returned, if any, will contain the remainder of the slice.
§Examples
Print the slice split once, starting from the end, by numbers divisible
by 3 (i.e., [50]
, [10, 40, 30, 20]
):
let v = [10, 40, 30, 20, 60, 50];
for group in v.rsplitn(2, |num| *num % 3 == 0) {
println!("{group:?}");
}
1.0.0 · Sourcepub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F> ⓘ
pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F> ⓘ
Returns an iterator over subslices separated by elements that match
pred
limited to returning at most n
items. This starts at the end of
the slice and works backwards. The matched element is not contained in
the subslices.
The last element returned, if any, will contain the remainder of the slice.
§Examples
let mut s = [10, 40, 30, 20, 60, 50];
for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
group[0] = 1;
}
assert_eq!(s, [1, 40, 30, 20, 60, 1]);
Sourcepub fn split_once<F>(&self, pred: F) -> Option<(&[T], &[T])>
🔬This is a nightly-only experimental API. (slice_split_once
)
pub fn split_once<F>(&self, pred: F) -> Option<(&[T], &[T])>
slice_split_once
)Splits the slice on the first element that matches the specified predicate.
If any matching elements are present in the slice, returns the prefix
before the match and suffix after. The matching element itself is not
included. If no elements match, returns None
.
§Examples
#![feature(slice_split_once)]
let s = [1, 2, 3, 2, 4];
assert_eq!(s.split_once(|&x| x == 2), Some((
&[1][..],
&[3, 2, 4][..]
)));
assert_eq!(s.split_once(|&x| x == 0), None);
Sourcepub fn rsplit_once<F>(&self, pred: F) -> Option<(&[T], &[T])>
🔬This is a nightly-only experimental API. (slice_split_once
)
pub fn rsplit_once<F>(&self, pred: F) -> Option<(&[T], &[T])>
slice_split_once
)Splits the slice on the last element that matches the specified predicate.
If any matching elements are present in the slice, returns the prefix
before the match and suffix after. The matching element itself is not
included. If no elements match, returns None
.
§Examples
#![feature(slice_split_once)]
let s = [1, 2, 3, 2, 4];
assert_eq!(s.rsplit_once(|&x| x == 2), Some((
&[1, 2, 3][..],
&[4][..]
)));
assert_eq!(s.rsplit_once(|&x| x == 0), None);
1.0.0 · Sourcepub fn contains(&self, x: &T) -> boolwhere
T: PartialEq,
pub fn contains(&self, x: &T) -> boolwhere
T: PartialEq,
Returns true
if the slice contains an element with the given value.
This operation is O(n).
Note that if you have a sorted slice, binary_search
may be faster.
§Examples
let v = [10, 40, 30];
assert!(v.contains(&30));
assert!(!v.contains(&50));
If you do not have a &T
, but some other value that you can compare
with one (for example, String
implements PartialEq<str>
), you can
use iter().any
:
let v = [String::from("hello"), String::from("world")]; // slice of `String`
assert!(v.iter().any(|e| e == "hello")); // search with `&str`
assert!(!v.iter().any(|e| e == "hi"));
1.0.0 · Sourcepub fn starts_with(&self, needle: &[T]) -> boolwhere
T: PartialEq,
pub fn starts_with(&self, needle: &[T]) -> boolwhere
T: PartialEq,
Returns true
if needle
is a prefix of the slice or equal to the slice.
§Examples
let v = [10, 40, 30];
assert!(v.starts_with(&[10]));
assert!(v.starts_with(&[10, 40]));
assert!(v.starts_with(&v));
assert!(!v.starts_with(&[50]));
assert!(!v.starts_with(&[10, 50]));
Always returns true
if needle
is an empty slice:
let v = &[10, 40, 30];
assert!(v.starts_with(&[]));
let v: &[u8] = &[];
assert!(v.starts_with(&[]));
1.0.0 · Sourcepub fn ends_with(&self, needle: &[T]) -> boolwhere
T: PartialEq,
pub fn ends_with(&self, needle: &[T]) -> boolwhere
T: PartialEq,
Returns true
if needle
is a suffix of the slice or equal to the slice.
§Examples
let v = [10, 40, 30];
assert!(v.ends_with(&[30]));
assert!(v.ends_with(&[40, 30]));
assert!(v.ends_with(&v));
assert!(!v.ends_with(&[50]));
assert!(!v.ends_with(&[50, 30]));
Always returns true
if needle
is an empty slice:
let v = &[10, 40, 30];
assert!(v.ends_with(&[]));
let v: &[u8] = &[];
assert!(v.ends_with(&[]));
1.51.0 · Sourcepub fn strip_prefix<P>(&self, prefix: &P) -> Option<&[T]>
pub fn strip_prefix<P>(&self, prefix: &P) -> Option<&[T]>
Returns a subslice with the prefix removed.
If the slice starts with prefix
, returns the subslice after the prefix, wrapped in Some
.
If prefix
is empty, simply returns the original slice. If prefix
is equal to the
original slice, returns an empty slice.
If the slice does not start with prefix
, returns None
.
§Examples
let v = &[10, 40, 30];
assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));
assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));
assert_eq!(v.strip_prefix(&[10, 40, 30]), Some(&[][..]));
assert_eq!(v.strip_prefix(&[50]), None);
assert_eq!(v.strip_prefix(&[10, 50]), None);
let prefix : &str = "he";
assert_eq!(b"hello".strip_prefix(prefix.as_bytes()),
Some(b"llo".as_ref()));
1.51.0 · Sourcepub fn strip_suffix<P>(&self, suffix: &P) -> Option<&[T]>
pub fn strip_suffix<P>(&self, suffix: &P) -> Option<&[T]>
Returns a subslice with the suffix removed.
If the slice ends with suffix
, returns the subslice before the suffix, wrapped in Some
.
If suffix
is empty, simply returns the original slice. If suffix
is equal to the
original slice, returns an empty slice.
If the slice does not end with suffix
, returns None
.
§Examples
let v = &[10, 40, 30];
assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));
assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));
assert_eq!(v.strip_suffix(&[10, 40, 30]), Some(&[][..]));
assert_eq!(v.strip_suffix(&[50]), None);
assert_eq!(v.strip_suffix(&[50, 30]), None);
1.0.0 · Sourcepub fn binary_search(&self, x: &T) -> Result<usize, usize>where
T: Ord,
pub fn binary_search(&self, x: &T) -> Result<usize, usize>where
T: Ord,
Binary searches this slice for a given element. If the slice is not sorted, the returned result is unspecified and meaningless.
If the value is found then Result::Ok
is returned, containing the
index of the matching element. If there are multiple matches, then any
one of the matches could be returned. The index is chosen
deterministically, but is subject to change in future versions of Rust.
If the value is not found then Result::Err
is returned, containing
the index where a matching element could be inserted while maintaining
sorted order.
See also binary_search_by
, binary_search_by_key
, and partition_point
.
§Examples
Looks up a series of four elements. The first is found, with a
uniquely determined position; the second and third are not
found; the fourth could match any position in [1, 4]
.
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
assert_eq!(s.binary_search(&13), Ok(9));
assert_eq!(s.binary_search(&4), Err(7));
assert_eq!(s.binary_search(&100), Err(13));
let r = s.binary_search(&1);
assert!(match r { Ok(1..=4) => true, _ => false, });
If you want to find that whole range of matching items, rather than
an arbitrary matching one, that can be done using partition_point
:
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
let low = s.partition_point(|x| x < &1);
assert_eq!(low, 1);
let high = s.partition_point(|x| x <= &1);
assert_eq!(high, 5);
let r = s.binary_search(&1);
assert!((low..high).contains(&r.unwrap()));
assert!(s[..low].iter().all(|&x| x < 1));
assert!(s[low..high].iter().all(|&x| x == 1));
assert!(s[high..].iter().all(|&x| x > 1));
// For something not found, the "range" of equal items is empty
assert_eq!(s.partition_point(|x| x < &11), 9);
assert_eq!(s.partition_point(|x| x <= &11), 9);
assert_eq!(s.binary_search(&11), Err(9));
If you want to insert an item to a sorted vector, while maintaining
sort order, consider using partition_point
:
let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
let num = 42;
let idx = s.partition_point(|&x| x <= num);
// If `num` is unique, `s.partition_point(|&x| x < num)` (with `<`) is equivalent to
// `s.binary_search(&num).unwrap_or_else(|x| x)`, but using `<=` will allow `insert`
// to shift less elements.
s.insert(idx, num);
assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
1.0.0 · Sourcepub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
Binary searches this slice with a comparator function.
The comparator function should return an order code that indicates
whether its argument is Less
, Equal
or Greater
the desired
target.
If the slice is not sorted or if the comparator function does not
implement an order consistent with the sort order of the underlying
slice, the returned result is unspecified and meaningless.
If the value is found then Result::Ok
is returned, containing the
index of the matching element. If there are multiple matches, then any
one of the matches could be returned. The index is chosen
deterministically, but is subject to change in future versions of Rust.
If the value is not found then Result::Err
is returned, containing
the index where a matching element could be inserted while maintaining
sorted order.
See also binary_search
, binary_search_by_key
, and partition_point
.
§Examples
Looks up a series of four elements. The first is found, with a
uniquely determined position; the second and third are not
found; the fourth could match any position in [1, 4]
.
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
let seek = 13;
assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
let seek = 4;
assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
let seek = 100;
assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
let seek = 1;
let r = s.binary_search_by(|probe| probe.cmp(&seek));
assert!(match r { Ok(1..=4) => true, _ => false, });
1.10.0 · Sourcepub fn binary_search_by_key<'a, B, F>(
&'a self,
b: &B,
f: F,
) -> Result<usize, usize>
pub fn binary_search_by_key<'a, B, F>( &'a self, b: &B, f: F, ) -> Result<usize, usize>
Binary searches this slice with a key extraction function.
Assumes that the slice is sorted by the key, for instance with
sort_by_key
using the same key extraction function.
If the slice is not sorted by the key, the returned result is
unspecified and meaningless.
If the value is found then Result::Ok
is returned, containing the
index of the matching element. If there are multiple matches, then any
one of the matches could be returned. The index is chosen
deterministically, but is subject to change in future versions of Rust.
If the value is not found then Result::Err
is returned, containing
the index where a matching element could be inserted while maintaining
sorted order.
See also binary_search
, binary_search_by
, and partition_point
.
§Examples
Looks up a series of four elements in a slice of pairs sorted by
their second elements. The first is found, with a uniquely
determined position; the second and third are not found; the
fourth could match any position in [1, 4]
.
let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
(1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
(1, 21), (2, 34), (4, 55)];
assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b), Ok(9));
assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b), Err(7));
assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13));
let r = s.binary_search_by_key(&1, |&(a, b)| b);
assert!(match r { Ok(1..=4) => true, _ => false, });
1.20.0 · Sourcepub fn sort_unstable(&mut self)where
T: Ord,
pub fn sort_unstable(&mut self)where
T: Ord,
Sorts the slice without preserving the initial order of equal elements.
This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not allocate), and O(n * log(n)) worst-case.
If the implementation of Ord
for T
does not implement a total order, the function
may panic; even if the function exits normally, the resulting order of elements in the slice
is unspecified. See also the note on panicking below.
For example |a, b| (a - b).cmp(a)
is a comparison function that is neither transitive nor
reflexive nor total, a < b < c < a
with a = 1, b = 2, c = 3
. For more information and
examples see the Ord
documentation.
All original elements will remain in the slice and any possible modifications via interior
mutability are observed in the input. Same is true if the implementation of Ord
for T
panics.
Sorting types that only implement PartialOrd
such as f32
and f64
require
additional precautions. For example, f32::NAN != f32::NAN
, which doesn’t fulfill the
reflexivity requirement of Ord
. By using an alternative comparison function with
slice::sort_unstable_by
such as f32::total_cmp
or f64::total_cmp
that defines a
total order users can sort slices containing floating-point values. Alternatively, if all
values in the slice are guaranteed to be in a subset for which PartialOrd::partial_cmp
forms a total order, it’s possible to sort the slice with sort_unstable_by(|a, b| a.partial_cmp(b).unwrap())
.
§Current implementation
The current implementation is based on ipnsort by Lukas Bergdoll and Orson Peters, which combines the fast average case of quicksort with the fast worst case of heapsort, achieving linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the expected time to sort the data is O(n * log(k)).
It is typically faster than stable sorting, except in a few special cases, e.g., when the slice is partially sorted.
§Panics
May panic if the implementation of Ord
for T
does not implement a total order, or if
the Ord
implementation panics.
§Examples
let mut v = [4, -5, 1, -3, 2];
v.sort_unstable();
assert_eq!(v, [-5, -3, 1, 2, 4]);
1.20.0 · Sourcepub fn sort_unstable_by<F>(&mut self, compare: F)
pub fn sort_unstable_by<F>(&mut self, compare: F)
Sorts the slice with a comparison function, without preserving the initial order of equal elements.
This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not allocate), and O(n * log(n)) worst-case.
If the comparison function compare
does not implement a total order, the function
may panic; even if the function exits normally, the resulting order of elements in the slice
is unspecified. See also the note on panicking below.
For example |a, b| (a - b).cmp(a)
is a comparison function that is neither transitive nor
reflexive nor total, a < b < c < a
with a = 1, b = 2, c = 3
. For more information and
examples see the Ord
documentation.
All original elements will remain in the slice and any possible modifications via interior
mutability are observed in the input. Same is true if compare
panics.
§Current implementation
The current implementation is based on ipnsort by Lukas Bergdoll and Orson Peters, which combines the fast average case of quicksort with the fast worst case of heapsort, achieving linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the expected time to sort the data is O(n * log(k)).
It is typically faster than stable sorting, except in a few special cases, e.g., when the slice is partially sorted.
§Panics
May panic if the compare
does not implement a total order, or if
the compare
itself panics.
§Examples
let mut v = [4, -5, 1, -3, 2];
v.sort_unstable_by(|a, b| a.cmp(b));
assert_eq!(v, [-5, -3, 1, 2, 4]);
// reverse sorting
v.sort_unstable_by(|a, b| b.cmp(a));
assert_eq!(v, [4, 2, 1, -3, -5]);
1.20.0 · Sourcepub fn sort_unstable_by_key<K, F>(&mut self, f: F)
pub fn sort_unstable_by_key<K, F>(&mut self, f: F)
Sorts the slice with a key extraction function, without preserving the initial order of equal elements.
This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not allocate), and O(n * log(n)) worst-case.
If the implementation of Ord
for K
does not implement a total order, the function
may panic; even if the function exits normally, the resulting order of elements in the slice
is unspecified. See also the note on panicking below.
For example |a, b| (a - b).cmp(a)
is a comparison function that is neither transitive nor
reflexive nor total, a < b < c < a
with a = 1, b = 2, c = 3
. For more information and
examples see the Ord
documentation.
All original elements will remain in the slice and any possible modifications via interior
mutability are observed in the input. Same is true if the implementation of Ord
for K
panics.
§Current implementation
The current implementation is based on ipnsort by Lukas Bergdoll and Orson Peters, which combines the fast average case of quicksort with the fast worst case of heapsort, achieving linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the expected time to sort the data is O(n * log(k)).
It is typically faster than stable sorting, except in a few special cases, e.g., when the slice is partially sorted.
§Panics
May panic if the implementation of Ord
for K
does not implement a total order, or if
the Ord
implementation panics.
§Examples
let mut v = [4i32, -5, 1, -3, 2];
v.sort_unstable_by_key(|k| k.abs());
assert_eq!(v, [1, 2, -3, 4, -5]);
1.49.0 · Sourcepub fn select_nth_unstable(
&mut self,
index: usize,
) -> (&mut [T], &mut T, &mut [T])where
T: Ord,
pub fn select_nth_unstable(
&mut self,
index: usize,
) -> (&mut [T], &mut T, &mut [T])where
T: Ord,
Reorders the slice such that the element at index
is at a sort-order position. All
elements before index
will be <=
to this value, and all elements after will be >=
to
it.
This reordering is unstable (i.e. any element that compares equal to the nth element may end up at that position), in-place (i.e. does not allocate), and runs in O(n) time. This function is also known as “kth element” in other libraries.
Returns a triple that partitions the reordered slice:
-
The unsorted subslice before
index
, whose elements all satisfyx <= self[index]
. -
The element at
index
. -
The unsorted subslice after
index
, whose elements all satisfyx >= self[index]
.
§Current implementation
The current algorithm is an introselect implementation based on ipnsort by Lukas Bergdoll
and Orson Peters, which is also the basis for sort_unstable
. The fallback algorithm is
Median of Medians using Tukey’s Ninther for pivot selection, which guarantees linear runtime
for all inputs.
§Panics
Panics when index >= len()
, and so always panics on empty slices.
May panic if the implementation of Ord
for T
does not implement a total order.
§Examples
let mut v = [-5i32, 4, 2, -3, 1];
// Find the items `<=` to the median, the median itself, and the items `>=` to it.
let (lesser, median, greater) = v.select_nth_unstable(2);
assert!(lesser == [-3, -5] || lesser == [-5, -3]);
assert_eq!(median, &mut 1);
assert!(greater == [4, 2] || greater == [2, 4]);
// We are only guaranteed the slice will be one of the following, based on the way we sort
// about the specified index.
assert!(v == [-3, -5, 1, 2, 4] ||
v == [-5, -3, 1, 2, 4] ||
v == [-3, -5, 1, 4, 2] ||
v == [-5, -3, 1, 4, 2]);
1.49.0 · Sourcepub fn select_nth_unstable_by<F>(
&mut self,
index: usize,
compare: F,
) -> (&mut [T], &mut T, &mut [T])
pub fn select_nth_unstable_by<F>( &mut self, index: usize, compare: F, ) -> (&mut [T], &mut T, &mut [T])
Reorders the slice with a comparator function such that the element at index
is at a
sort-order position. All elements before index
will be <=
to this value, and all
elements after will be >=
to it, according to the comparator function.
This reordering is unstable (i.e. any element that compares equal to the nth element may end up at that position), in-place (i.e. does not allocate), and runs in O(n) time. This function is also known as “kth element” in other libraries.
Returns a triple partitioning the reordered slice:
-
The unsorted subslice before
index
, whose elements all satisfycompare(x, self[index]).is_le()
. -
The element at
index
. -
The unsorted subslice after
index
, whose elements all satisfycompare(x, self[index]).is_ge()
.
§Current implementation
The current algorithm is an introselect implementation based on ipnsort by Lukas Bergdoll
and Orson Peters, which is also the basis for sort_unstable
. The fallback algorithm is
Median of Medians using Tukey’s Ninther for pivot selection, which guarantees linear runtime
for all inputs.
§Panics
Panics when index >= len()
, and so always panics on empty slices.
May panic if compare
does not implement a total order.
§Examples
let mut v = [-5i32, 4, 2, -3, 1];
// Find the items `>=` to the median, the median itself, and the items `<=` to it, by using
// a reversed comparator.
let (before, median, after) = v.select_nth_unstable_by(2, |a, b| b.cmp(a));
assert!(before == [4, 2] || before == [2, 4]);
assert_eq!(median, &mut 1);
assert!(after == [-3, -5] || after == [-5, -3]);
// We are only guaranteed the slice will be one of the following, based on the way we sort
// about the specified index.
assert!(v == [2, 4, 1, -5, -3] ||
v == [2, 4, 1, -3, -5] ||
v == [4, 2, 1, -5, -3] ||
v == [4, 2, 1, -3, -5]);
1.49.0 · Sourcepub fn select_nth_unstable_by_key<K, F>(
&mut self,
index: usize,
f: F,
) -> (&mut [T], &mut T, &mut [T])
pub fn select_nth_unstable_by_key<K, F>( &mut self, index: usize, f: F, ) -> (&mut [T], &mut T, &mut [T])
Reorders the slice with a key extraction function such that the element at index
is at a
sort-order position. All elements before index
will have keys <=
to the key at index
,
and all elements after will have keys >=
to it.
This reordering is unstable (i.e. any element that compares equal to the nth element may end up at that position), in-place (i.e. does not allocate), and runs in O(n) time. This function is also known as “kth element” in other libraries.
Returns a triple partitioning the reordered slice:
-
The unsorted subslice before
index
, whose elements all satisfyf(x) <= f(self[index])
. -
The element at
index
. -
The unsorted subslice after
index
, whose elements all satisfyf(x) >= f(self[index])
.
§Current implementation
The current algorithm is an introselect implementation based on ipnsort by Lukas Bergdoll
and Orson Peters, which is also the basis for sort_unstable
. The fallback algorithm is
Median of Medians using Tukey’s Ninther for pivot selection, which guarantees linear runtime
for all inputs.
§Panics
Panics when index >= len()
, meaning it always panics on empty slices.
May panic if K: Ord
does not implement a total order.
§Examples
let mut v = [-5i32, 4, 1, -3, 2];
// Find the items `<=` to the absolute median, the absolute median itself, and the items
// `>=` to it.
let (lesser, median, greater) = v.select_nth_unstable_by_key(2, |a| a.abs());
assert!(lesser == [1, 2] || lesser == [2, 1]);
assert_eq!(median, &mut -3);
assert!(greater == [4, -5] || greater == [-5, 4]);
// We are only guaranteed the slice will be one of the following, based on the way we sort
// about the specified index.
assert!(v == [1, 2, -3, 4, -5] ||
v == [1, 2, -3, -5, 4] ||
v == [2, 1, -3, 4, -5] ||
v == [2, 1, -3, -5, 4]);
Sourcepub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])where
T: PartialEq,
🔬This is a nightly-only experimental API. (slice_partition_dedup
)
pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])where
T: PartialEq,
slice_partition_dedup
)Moves all consecutive repeated elements to the end of the slice according to the
PartialEq
trait implementation.
Returns two slices. The first contains no consecutive repeated elements. The second contains all the duplicates in no specified order.
If the slice is sorted, the first returned slice contains no duplicates.
§Examples
#![feature(slice_partition_dedup)]
let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
let (dedup, duplicates) = slice.partition_dedup();
assert_eq!(dedup, [1, 2, 3, 2, 1]);
assert_eq!(duplicates, [2, 3, 1]);
Sourcepub fn partition_dedup_by<F>(&mut self, same_bucket: F) -> (&mut [T], &mut [T])
🔬This is a nightly-only experimental API. (slice_partition_dedup
)
pub fn partition_dedup_by<F>(&mut self, same_bucket: F) -> (&mut [T], &mut [T])
slice_partition_dedup
)Moves all but the first of consecutive elements to the end of the slice satisfying a given equality relation.
Returns two slices. The first contains no consecutive repeated elements. The second contains all the duplicates in no specified order.
The same_bucket
function is passed references to two elements from the slice and
must determine if the elements compare equal. The elements are passed in opposite order
from their order in the slice, so if same_bucket(a, b)
returns true
, a
is moved
at the end of the slice.
If the slice is sorted, the first returned slice contains no duplicates.
§Examples
#![feature(slice_partition_dedup)]
let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
Sourcepub fn partition_dedup_by_key<K, F>(&mut self, key: F) -> (&mut [T], &mut [T])
🔬This is a nightly-only experimental API. (slice_partition_dedup
)
pub fn partition_dedup_by_key<K, F>(&mut self, key: F) -> (&mut [T], &mut [T])
slice_partition_dedup
)Moves all but the first of consecutive elements to the end of the slice that resolve to the same key.
Returns two slices. The first contains no consecutive repeated elements. The second contains all the duplicates in no specified order.
If the slice is sorted, the first returned slice contains no duplicates.
§Examples
#![feature(slice_partition_dedup)]
let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
assert_eq!(dedup, [10, 20, 30, 20, 11]);
assert_eq!(duplicates, [21, 30, 13]);
1.26.0 · Sourcepub fn rotate_left(&mut self, mid: usize)
pub fn rotate_left(&mut self, mid: usize)
Rotates the slice in-place such that the first mid
elements of the
slice move to the end while the last self.len() - mid
elements move to
the front.
After calling rotate_left
, the element previously at index mid
will
become the first element in the slice.
§Panics
This function will panic if mid
is greater than the length of the
slice. Note that mid == self.len()
does not panic and is a no-op
rotation.
§Complexity
Takes linear (in self.len()
) time.
§Examples
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
a.rotate_left(2);
assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
Rotating a subslice:
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
a[1..5].rotate_left(1);
assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
1.26.0 · Sourcepub fn rotate_right(&mut self, k: usize)
pub fn rotate_right(&mut self, k: usize)
Rotates the slice in-place such that the first self.len() - k
elements of the slice move to the end while the last k
elements move
to the front.
After calling rotate_right
, the element previously at index
self.len() - k
will become the first element in the slice.
§Panics
This function will panic if k
is greater than the length of the
slice. Note that k == self.len()
does not panic and is a no-op
rotation.
§Complexity
Takes linear (in self.len()
) time.
§Examples
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
a.rotate_right(2);
assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
Rotating a subslice:
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
a[1..5].rotate_right(1);
assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
1.50.0 · Sourcepub fn fill(&mut self, value: T)where
T: Clone,
pub fn fill(&mut self, value: T)where
T: Clone,
Fills self
with elements by cloning value
.
§Examples
let mut buf = vec![0; 10];
buf.fill(1);
assert_eq!(buf, vec![1; 10]);
1.51.0 · Sourcepub fn fill_with<F>(&mut self, f: F)where
F: FnMut() -> T,
pub fn fill_with<F>(&mut self, f: F)where
F: FnMut() -> T,
Fills self
with elements returned by calling a closure repeatedly.
This method uses a closure to create new values. If you’d rather
Clone
a given value, use fill
. If you want to use the Default
trait to generate values, you can pass Default::default
as the
argument.
§Examples
let mut buf = vec![1; 10];
buf.fill_with(Default::default);
assert_eq!(buf, vec![0; 10]);
1.7.0 · Sourcepub fn clone_from_slice(&mut self, src: &[T])where
T: Clone,
pub fn clone_from_slice(&mut self, src: &[T])where
T: Clone,
Copies the elements from src
into self
.
The length of src
must be the same as self
.
§Panics
This function will panic if the two slices have different lengths.
§Examples
Cloning two elements from a slice into another:
let src = [1, 2, 3, 4];
let mut dst = [0, 0];
// Because the slices have to be the same length,
// we slice the source slice from four elements
// to two. It will panic if we don't do this.
dst.clone_from_slice(&src[2..]);
assert_eq!(src, [1, 2, 3, 4]);
assert_eq!(dst, [3, 4]);
Rust enforces that there can only be one mutable reference with no
immutable references to a particular piece of data in a particular
scope. Because of this, attempting to use clone_from_slice
on a
single slice will result in a compile failure:
let mut slice = [1, 2, 3, 4, 5];
slice[..2].clone_from_slice(&slice[3..]); // compile fail!
To work around this, we can use split_at_mut
to create two distinct
sub-slices from a slice:
let mut slice = [1, 2, 3, 4, 5];
{
let (left, right) = slice.split_at_mut(2);
left.clone_from_slice(&right[1..]);
}
assert_eq!(slice, [4, 5, 3, 4, 5]);
1.9.0 · Sourcepub fn copy_from_slice(&mut self, src: &[T])where
T: Copy,
pub fn copy_from_slice(&mut self, src: &[T])where
T: Copy,
Copies all elements from src
into self
, using a memcpy.
The length of src
must be the same as self
.
If T
does not implement Copy
, use clone_from_slice
.
§Panics
This function will panic if the two slices have different lengths.
§Examples
Copying two elements from a slice into another:
let src = [1, 2, 3, 4];
let mut dst = [0, 0];
// Because the slices have to be the same length,
// we slice the source slice from four elements
// to two. It will panic if we don't do this.
dst.copy_from_slice(&src[2..]);
assert_eq!(src, [1, 2, 3, 4]);
assert_eq!(dst, [3, 4]);
Rust enforces that there can only be one mutable reference with no
immutable references to a particular piece of data in a particular
scope. Because of this, attempting to use copy_from_slice
on a
single slice will result in a compile failure:
let mut slice = [1, 2, 3, 4, 5];
slice[..2].copy_from_slice(&slice[3..]); // compile fail!
To work around this, we can use split_at_mut
to create two distinct
sub-slices from a slice:
let mut slice = [1, 2, 3, 4, 5];
{
let (left, right) = slice.split_at_mut(2);
left.copy_from_slice(&right[1..]);
}
assert_eq!(slice, [4, 5, 3, 4, 5]);
1.37.0 · Sourcepub fn copy_within<R>(&mut self, src: R, dest: usize)
pub fn copy_within<R>(&mut self, src: R, dest: usize)
Copies elements from one part of the slice to another part of itself, using a memmove.
src
is the range within self
to copy from. dest
is the starting
index of the range within self
to copy to, which will have the same
length as src
. The two ranges may overlap. The ends of the two ranges
must be less than or equal to self.len()
.
§Panics
This function will panic if either range exceeds the end of the slice,
or if the end of src
is before the start.
§Examples
Copying four bytes within a slice:
let mut bytes = *b"Hello, World!";
bytes.copy_within(1..5, 8);
assert_eq!(&bytes, b"Hello, Wello!");
1.27.0 · Sourcepub fn swap_with_slice(&mut self, other: &mut [T])
pub fn swap_with_slice(&mut self, other: &mut [T])
Swaps all elements in self
with those in other
.
The length of other
must be the same as self
.
§Panics
This function will panic if the two slices have different lengths.
§Example
Swapping two elements across slices:
let mut slice1 = [0, 0];
let mut slice2 = [1, 2, 3, 4];
slice1.swap_with_slice(&mut slice2[2..]);
assert_eq!(slice1, [3, 4]);
assert_eq!(slice2, [1, 2, 0, 0]);
Rust enforces that there can only be one mutable reference to a
particular piece of data in a particular scope. Because of this,
attempting to use swap_with_slice
on a single slice will result in
a compile failure:
let mut slice = [1, 2, 3, 4, 5];
slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
To work around this, we can use split_at_mut
to create two distinct
mutable sub-slices from a slice:
let mut slice = [1, 2, 3, 4, 5];
{
let (left, right) = slice.split_at_mut(2);
left.swap_with_slice(&mut right[1..]);
}
assert_eq!(slice, [4, 5, 3, 1, 2]);
1.30.0 · Sourcepub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T])
pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T])
Transmutes the slice to a slice of another type, ensuring alignment of the types is maintained.
This method splits the slice into three distinct slices: prefix, correctly aligned middle slice of a new type, and the suffix slice. The middle part will be as big as possible under the given alignment constraint and element size.
This method has no purpose when either input element T
or output element U
are
zero-sized and will return the original slice without splitting anything.
§Safety
This method is essentially a transmute
with respect to the elements in the returned
middle slice, so all the usual caveats pertaining to transmute::<T, U>
also apply here.
§Examples
Basic usage:
unsafe {
let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
let (prefix, shorts, suffix) = bytes.align_to::<u16>();
// less_efficient_algorithm_for_bytes(prefix);
// more_efficient_algorithm_for_aligned_shorts(shorts);
// less_efficient_algorithm_for_bytes(suffix);
}
1.30.0 · Sourcepub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T])
pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T])
Transmutes the mutable slice to a mutable slice of another type, ensuring alignment of the types is maintained.
This method splits the slice into three distinct slices: prefix, correctly aligned middle slice of a new type, and the suffix slice. The middle part will be as big as possible under the given alignment constraint and element size.
This method has no purpose when either input element T
or output element U
are
zero-sized and will return the original slice without splitting anything.
§Safety
This method is essentially a transmute
with respect to the elements in the returned
middle slice, so all the usual caveats pertaining to transmute::<T, U>
also apply here.
§Examples
Basic usage:
unsafe {
let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
// less_efficient_algorithm_for_bytes(prefix);
// more_efficient_algorithm_for_aligned_shorts(shorts);
// less_efficient_algorithm_for_bytes(suffix);
}
Sourcepub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])
🔬This is a nightly-only experimental API. (portable_simd
)
pub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])
portable_simd
)Splits a slice into a prefix, a middle of aligned SIMD types, and a suffix.
This is a safe wrapper around slice::align_to
, so inherits the same
guarantees as that method.
§Panics
This will panic if the size of the SIMD type is different from
LANES
times that of the scalar.
At the time of writing, the trait restrictions on Simd<T, LANES>
keeps
that from ever happening, as only power-of-two numbers of lanes are
supported. It’s possible that, in the future, those restrictions might
be lifted in a way that would make it possible to see panics from this
method for something like LANES == 3
.
§Examples
#![feature(portable_simd)]
use core::simd::prelude::*;
let short = &[1, 2, 3];
let (prefix, middle, suffix) = short.as_simd::<4>();
assert_eq!(middle, []); // Not enough elements for anything in the middle
// They might be split in any possible way between prefix and suffix
let it = prefix.iter().chain(suffix).copied();
assert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3]);
fn basic_simd_sum(x: &[f32]) -> f32 {
use std::ops::Add;
let (prefix, middle, suffix) = x.as_simd();
let sums = f32x4::from_array([
prefix.iter().copied().sum(),
0.0,
0.0,
suffix.iter().copied().sum(),
]);
let sums = middle.iter().copied().fold(sums, f32x4::add);
sums.reduce_sum()
}
let numbers: Vec<f32> = (1..101).map(|x| x as _).collect();
assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0);
Sourcepub fn as_simd_mut<const LANES: usize>(
&mut self,
) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T])
🔬This is a nightly-only experimental API. (portable_simd
)
pub fn as_simd_mut<const LANES: usize>( &mut self, ) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T])
portable_simd
)Splits a mutable slice into a mutable prefix, a middle of aligned SIMD types, and a mutable suffix.
This is a safe wrapper around slice::align_to_mut
, so inherits the same
guarantees as that method.
This is the mutable version of slice::as_simd
; see that for examples.
§Panics
This will panic if the size of the SIMD type is different from
LANES
times that of the scalar.
At the time of writing, the trait restrictions on Simd<T, LANES>
keeps
that from ever happening, as only power-of-two numbers of lanes are
supported. It’s possible that, in the future, those restrictions might
be lifted in a way that would make it possible to see panics from this
method for something like LANES == 3
.
1.82.0 · Sourcepub fn is_sorted(&self) -> boolwhere
T: PartialOrd,
pub fn is_sorted(&self) -> boolwhere
T: PartialOrd,
Checks if the elements of this slice are sorted.
That is, for each element a
and its following element b
, a <= b
must hold. If the
slice yields exactly zero or one element, true
is returned.
Note that if Self::Item
is only PartialOrd
, but not Ord
, the above definition
implies that this function returns false
if any two consecutive items are not
comparable.
§Examples
let empty: [i32; 0] = [];
assert!([1, 2, 2, 9].is_sorted());
assert!(![1, 3, 2, 4].is_sorted());
assert!([0].is_sorted());
assert!(empty.is_sorted());
assert!(![0.0, 1.0, f32::NAN].is_sorted());
1.82.0 · Sourcepub fn is_sorted_by<'a, F>(&'a self, compare: F) -> bool
pub fn is_sorted_by<'a, F>(&'a self, compare: F) -> bool
Checks if the elements of this slice are sorted using the given comparator function.
Instead of using PartialOrd::partial_cmp
, this function uses the given compare
function to determine whether two elements are to be considered in sorted order.
§Examples
assert!([1, 2, 2, 9].is_sorted_by(|a, b| a <= b));
assert!(![1, 2, 2, 9].is_sorted_by(|a, b| a < b));
assert!([0].is_sorted_by(|a, b| true));
assert!([0].is_sorted_by(|a, b| false));
let empty: [i32; 0] = [];
assert!(empty.is_sorted_by(|a, b| false));
assert!(empty.is_sorted_by(|a, b| true));
1.82.0 · Sourcepub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> bool
pub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> bool
Checks if the elements of this slice are sorted using the given key extraction function.
Instead of comparing the slice’s elements directly, this function compares the keys of the
elements, as determined by f
. Apart from that, it’s equivalent to is_sorted
; see its
documentation for more information.
§Examples
assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
1.52.0 · Sourcepub fn partition_point<P>(&self, pred: P) -> usize
pub fn partition_point<P>(&self, pred: P) -> usize
Returns the index of the partition point according to the given predicate (the index of the first element of the second partition).
The slice is assumed to be partitioned according to the given predicate.
This means that all elements for which the predicate returns true are at the start of the slice
and all elements for which the predicate returns false are at the end.
For example, [7, 15, 3, 5, 4, 12, 6]
is partitioned under the predicate x % 2 != 0
(all odd numbers are at the start, all even at the end).
If this slice is not partitioned, the returned result is unspecified and meaningless, as this method performs a kind of binary search.
See also binary_search
, binary_search_by
, and binary_search_by_key
.
§Examples
let v = [1, 2, 3, 3, 5, 6, 7];
let i = v.partition_point(|&x| x < 5);
assert_eq!(i, 4);
assert!(v[..i].iter().all(|&x| x < 5));
assert!(v[i..].iter().all(|&x| !(x < 5)));
If all elements of the slice match the predicate, including if the slice is empty, then the length of the slice will be returned:
let a = [2, 4, 8];
assert_eq!(a.partition_point(|x| x < &100), a.len());
let a: [i32; 0] = [];
assert_eq!(a.partition_point(|x| x < &100), 0);
If you want to insert an item to a sorted vector, while maintaining sort order:
let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
let num = 42;
let idx = s.partition_point(|&x| x <= num);
s.insert(idx, num);
assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
1.87.0 · Sourcepub fn split_off<'a, R>(self: &mut &'a [T], range: R) -> Option<&'a [T]>where
R: OneSidedRange<usize>,
pub fn split_off<'a, R>(self: &mut &'a [T], range: R) -> Option<&'a [T]>where
R: OneSidedRange<usize>,
Removes the subslice corresponding to the given range and returns a reference to it.
Returns None
and does not modify the slice if the given
range is out of bounds.
Note that this method only accepts one-sided ranges such as
2..
or ..6
, but not 2..6
.
§Examples
Splitting off the first three elements of a slice:
let mut slice: &[_] = &['a', 'b', 'c', 'd'];
let mut first_three = slice.split_off(..3).unwrap();
assert_eq!(slice, &['d']);
assert_eq!(first_three, &['a', 'b', 'c']);
Splitting off the last two elements of a slice:
let mut slice: &[_] = &['a', 'b', 'c', 'd'];
let mut tail = slice.split_off(2..).unwrap();
assert_eq!(slice, &['a', 'b']);
assert_eq!(tail, &['c', 'd']);
Getting None
when range
is out of bounds:
let mut slice: &[_] = &['a', 'b', 'c', 'd'];
assert_eq!(None, slice.split_off(5..));
assert_eq!(None, slice.split_off(..5));
assert_eq!(None, slice.split_off(..=4));
let expected: &[char] = &['a', 'b', 'c', 'd'];
assert_eq!(Some(expected), slice.split_off(..4));
1.87.0 · Sourcepub fn split_off_mut<'a, R>(
self: &mut &'a mut [T],
range: R,
) -> Option<&'a mut [T]>where
R: OneSidedRange<usize>,
pub fn split_off_mut<'a, R>(
self: &mut &'a mut [T],
range: R,
) -> Option<&'a mut [T]>where
R: OneSidedRange<usize>,
Removes the subslice corresponding to the given range and returns a mutable reference to it.
Returns None
and does not modify the slice if the given
range is out of bounds.
Note that this method only accepts one-sided ranges such as
2..
or ..6
, but not 2..6
.
§Examples
Splitting off the first three elements of a slice:
let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
let mut first_three = slice.split_off_mut(..3).unwrap();
assert_eq!(slice, &mut ['d']);
assert_eq!(first_three, &mut ['a', 'b', 'c']);
Taking the last two elements of a slice:
let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
let mut tail = slice.split_off_mut(2..).unwrap();
assert_eq!(slice, &mut ['a', 'b']);
assert_eq!(tail, &mut ['c', 'd']);
Getting None
when range
is out of bounds:
let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
assert_eq!(None, slice.split_off_mut(5..));
assert_eq!(None, slice.split_off_mut(..5));
assert_eq!(None, slice.split_off_mut(..=4));
let expected: &mut [_] = &mut ['a', 'b', 'c', 'd'];
assert_eq!(Some(expected), slice.split_off_mut(..4));
1.87.0 · Sourcepub fn split_off_first<'a>(self: &mut &'a [T]) -> Option<&'a T>
pub fn split_off_first<'a>(self: &mut &'a [T]) -> Option<&'a T>
Removes the first element of the slice and returns a reference to it.
Returns None
if the slice is empty.
§Examples
let mut slice: &[_] = &['a', 'b', 'c'];
let first = slice.split_off_first().unwrap();
assert_eq!(slice, &['b', 'c']);
assert_eq!(first, &'a');
1.87.0 · Sourcepub fn split_off_first_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>
pub fn split_off_first_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>
Removes the first element of the slice and returns a mutable reference to it.
Returns None
if the slice is empty.
§Examples
let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
let first = slice.split_off_first_mut().unwrap();
*first = 'd';
assert_eq!(slice, &['b', 'c']);
assert_eq!(first, &'d');
1.87.0 · Sourcepub fn split_off_last<'a>(self: &mut &'a [T]) -> Option<&'a T>
pub fn split_off_last<'a>(self: &mut &'a [T]) -> Option<&'a T>
Removes the last element of the slice and returns a reference to it.
Returns None
if the slice is empty.
§Examples
let mut slice: &[_] = &['a', 'b', 'c'];
let last = slice.split_off_last().unwrap();
assert_eq!(slice, &['a', 'b']);
assert_eq!(last, &'c');
1.87.0 · Sourcepub fn split_off_last_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>
pub fn split_off_last_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>
Removes the last element of the slice and returns a mutable reference to it.
Returns None
if the slice is empty.
§Examples
let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
let last = slice.split_off_last_mut().unwrap();
*last = 'd';
assert_eq!(slice, &['a', 'b']);
assert_eq!(last, &'d');
1.86.0 · Sourcepub unsafe fn get_disjoint_unchecked_mut<I, const N: usize>(
&mut self,
indices: [I; N],
) -> [&mut <I as SliceIndex<[T]>>::Output; N]
pub unsafe fn get_disjoint_unchecked_mut<I, const N: usize>( &mut self, indices: [I; N], ) -> [&mut <I as SliceIndex<[T]>>::Output; N]
Returns mutable references to many indices at once, without doing any checks.
An index can be either a usize
, a Range
or a RangeInclusive
. Note
that this method takes an array, so all indices must be of the same type.
If passed an array of usize
s this method gives back an array of mutable references
to single elements, while if passed an array of ranges it gives back an array of
mutable references to slices.
For a safe alternative see get_disjoint_mut
.
§Safety
Calling this method with overlapping or out-of-bounds indices is undefined behavior even if the resulting references are not used.
§Examples
let x = &mut [1, 2, 4];
unsafe {
let [a, b] = x.get_disjoint_unchecked_mut([0, 2]);
*a *= 10;
*b *= 100;
}
assert_eq!(x, &[10, 2, 400]);
unsafe {
let [a, b] = x.get_disjoint_unchecked_mut([0..1, 1..3]);
a[0] = 8;
b[0] = 88;
b[1] = 888;
}
assert_eq!(x, &[8, 88, 888]);
unsafe {
let [a, b] = x.get_disjoint_unchecked_mut([1..=2, 0..=0]);
a[0] = 11;
a[1] = 111;
b[0] = 1;
}
assert_eq!(x, &[1, 11, 111]);
1.86.0 · Sourcepub fn get_disjoint_mut<I, const N: usize>(
&mut self,
indices: [I; N],
) -> Result<[&mut <I as SliceIndex<[T]>>::Output; N], GetDisjointMutError>
pub fn get_disjoint_mut<I, const N: usize>( &mut self, indices: [I; N], ) -> Result<[&mut <I as SliceIndex<[T]>>::Output; N], GetDisjointMutError>
Returns mutable references to many indices at once.
An index can be either a usize
, a Range
or a RangeInclusive
. Note
that this method takes an array, so all indices must be of the same type.
If passed an array of usize
s this method gives back an array of mutable references
to single elements, while if passed an array of ranges it gives back an array of
mutable references to slices.
Returns an error if any index is out-of-bounds, or if there are overlapping indices. An empty range is not considered to overlap if it is located at the beginning or at the end of another range, but is considered to overlap if it is located in the middle.
This method does a O(n^2) check to check that there are no overlapping indices, so be careful when passing many indices.
§Examples
let v = &mut [1, 2, 3];
if let Ok([a, b]) = v.get_disjoint_mut([0, 2]) {
*a = 413;
*b = 612;
}
assert_eq!(v, &[413, 2, 612]);
if let Ok([a, b]) = v.get_disjoint_mut([0..1, 1..3]) {
a[0] = 8;
b[0] = 88;
b[1] = 888;
}
assert_eq!(v, &[8, 88, 888]);
if let Ok([a, b]) = v.get_disjoint_mut([1..=2, 0..=0]) {
a[0] = 11;
a[1] = 111;
b[0] = 1;
}
assert_eq!(v, &[1, 11, 111]);
Sourcepub fn element_offset(&self, element: &T) -> Option<usize>
🔬This is a nightly-only experimental API. (substr_range
)
pub fn element_offset(&self, element: &T) -> Option<usize>
substr_range
)Returns the index that an element reference points to.
Returns None
if element
does not point to the start of an element within the slice.
This method is useful for extending slice iterators like slice::split
.
Note that this uses pointer arithmetic and does not compare elements.
To find the index of an element via comparison, use
.iter().position()
instead.
§Panics
Panics if T
is zero-sized.
§Examples
Basic usage:
#![feature(substr_range)]
let nums: &[u32] = &[1, 7, 1, 1];
let num = &nums[2];
assert_eq!(num, &1);
assert_eq!(nums.element_offset(num), Some(2));
Returning None
with an unaligned element:
#![feature(substr_range)]
let arr: &[[u32; 2]] = &[[0, 1], [2, 3]];
let flat_arr: &[u32] = arr.as_flattened();
let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap();
let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap();
assert_eq!(ok_elm, &[0, 1]);
assert_eq!(weird_elm, &[1, 2]);
assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0
assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1
Sourcepub fn subslice_range(&self, subslice: &[T]) -> Option<Range<usize>>
🔬This is a nightly-only experimental API. (substr_range
)
pub fn subslice_range(&self, subslice: &[T]) -> Option<Range<usize>>
substr_range
)Returns the range of indices that a subslice points to.
Returns None
if subslice
does not point within the slice or if it is not aligned with the
elements in the slice.
This method does not compare elements. Instead, this method finds the location in the slice that
subslice
was obtained from. To find the index of a subslice via comparison, instead use
.windows()
.position()
.
This method is useful for extending slice iterators like slice::split
.
Note that this may return a false positive (either Some(0..0)
or Some(self.len()..self.len())
)
if subslice
has a length of zero and points to the beginning or end of another, separate, slice.
§Panics
Panics if T
is zero-sized.
§Examples
Basic usage:
#![feature(substr_range)]
let nums = &[0, 5, 10, 0, 0, 5];
let mut iter = nums
.split(|t| *t == 0)
.map(|n| nums.subslice_range(n).unwrap());
assert_eq!(iter.next(), Some(0..0));
assert_eq!(iter.next(), Some(1..3));
assert_eq!(iter.next(), Some(4..4));
assert_eq!(iter.next(), Some(5..6));
1.0.0 · Sourcepub fn sort(&mut self)where
T: Ord,
pub fn sort(&mut self)where
T: Ord,
Sorts the slice, preserving initial order of equal elements.
This sort is stable (i.e., does not reorder equal elements) and O(n * log(n)) worst-case.
If the implementation of Ord
for T
does not implement a total order, the function
may panic; even if the function exits normally, the resulting order of elements in the slice
is unspecified. See also the note on panicking below.
When applicable, unstable sorting is preferred because it is generally faster than stable
sorting and it doesn’t allocate auxiliary memory. See
sort_unstable
. The exception are partially sorted slices, which
may be better served with slice::sort
.
Sorting types that only implement PartialOrd
such as f32
and f64
require
additional precautions. For example, f32::NAN != f32::NAN
, which doesn’t fulfill the
reflexivity requirement of Ord
. By using an alternative comparison function with
slice::sort_by
such as f32::total_cmp
or f64::total_cmp
that defines a total
order users can sort slices containing floating-point values. Alternatively, if all values
in the slice are guaranteed to be in a subset for which PartialOrd::partial_cmp
forms a
total order, it’s possible to sort the slice with sort_by(|a, b| a.partial_cmp(b).unwrap())
.
§Current implementation
The current implementation is based on driftsort by Orson Peters and Lukas Bergdoll, which combines the fast average case of quicksort with the fast worst case and partial run detection of mergesort, achieving linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the expected time to sort the data is O(n * log(k)).
The auxiliary memory allocation behavior depends on the input length. Short slices are
handled without allocation, medium sized slices allocate self.len()
and beyond that it
clamps at self.len() / 2
.
§Panics
May panic if the implementation of Ord
for T
does not implement a total order, or if
the Ord
implementation itself panics.
All safe functions on slices preserve the invariant that even if the function panics, all
original elements will remain in the slice and any possible modifications via interior
mutability are observed in the input. This ensures that recovery code (for instance inside
of a Drop
or following a catch_unwind
) will still have access to all the original
elements. For instance, if the slice belongs to a Vec
, the Vec::drop
method will be able
to dispose of all contained elements.
§Examples
let mut v = [4, -5, 1, -3, 2];
v.sort();
assert_eq!(v, [-5, -3, 1, 2, 4]);
1.0.0 · Sourcepub fn sort_by<F>(&mut self, compare: F)
pub fn sort_by<F>(&mut self, compare: F)
Sorts the slice with a comparison function, preserving initial order of equal elements.
This sort is stable (i.e., does not reorder equal elements) and O(n * log(n)) worst-case.
If the comparison function compare
does not implement a total order, the function may
panic; even if the function exits normally, the resulting order of elements in the slice is
unspecified. See also the note on panicking below.
For example |a, b| (a - b).cmp(a)
is a comparison function that is neither transitive nor
reflexive nor total, a < b < c < a
with a = 1, b = 2, c = 3
. For more information and
examples see the Ord
documentation.
§Current implementation
The current implementation is based on driftsort by Orson Peters and Lukas Bergdoll, which combines the fast average case of quicksort with the fast worst case and partial run detection of mergesort, achieving linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the expected time to sort the data is O(n * log(k)).
The auxiliary memory allocation behavior depends on the input length. Short slices are
handled without allocation, medium sized slices allocate self.len()
and beyond that it
clamps at self.len() / 2
.
§Panics
May panic if compare
does not implement a total order, or if compare
itself panics.
All safe functions on slices preserve the invariant that even if the function panics, all
original elements will remain in the slice and any possible modifications via interior
mutability are observed in the input. This ensures that recovery code (for instance inside
of a Drop
or following a catch_unwind
) will still have access to all the original
elements. For instance, if the slice belongs to a Vec
, the Vec::drop
method will be able
to dispose of all contained elements.
§Examples
let mut v = [4, -5, 1, -3, 2];
v.sort_by(|a, b| a.cmp(b));
assert_eq!(v, [-5, -3, 1, 2, 4]);
// reverse sorting
v.sort_by(|a, b| b.cmp(a));
assert_eq!(v, [4, 2, 1, -3, -5]);
1.7.0 · Sourcepub fn sort_by_key<K, F>(&mut self, f: F)
pub fn sort_by_key<K, F>(&mut self, f: F)
Sorts the slice with a key extraction function, preserving initial order of equal elements.
This sort is stable (i.e., does not reorder equal elements) and O(m * n * log(n)) worst-case, where the key function is O(m).
If the implementation of Ord
for K
does not implement a total order, the function
may panic; even if the function exits normally, the resulting order of elements in the slice
is unspecified. See also the note on panicking below.
§Current implementation
The current implementation is based on driftsort by Orson Peters and Lukas Bergdoll, which combines the fast average case of quicksort with the fast worst case and partial run detection of mergesort, achieving linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the expected time to sort the data is O(n * log(k)).
The auxiliary memory allocation behavior depends on the input length. Short slices are
handled without allocation, medium sized slices allocate self.len()
and beyond that it
clamps at self.len() / 2
.
§Panics
May panic if the implementation of Ord
for K
does not implement a total order, or if
the Ord
implementation or the key-function f
panics.
All safe functions on slices preserve the invariant that even if the function panics, all
original elements will remain in the slice and any possible modifications via interior
mutability are observed in the input. This ensures that recovery code (for instance inside
of a Drop
or following a catch_unwind
) will still have access to all the original
elements. For instance, if the slice belongs to a Vec
, the Vec::drop
method will be able
to dispose of all contained elements.
§Examples
let mut v = [4i32, -5, 1, -3, 2];
v.sort_by_key(|k| k.abs());
assert_eq!(v, [1, 2, -3, 4, -5]);
1.34.0 · Sourcepub fn sort_by_cached_key<K, F>(&mut self, f: F)
pub fn sort_by_cached_key<K, F>(&mut self, f: F)
Sorts the slice with a key extraction function, preserving initial order of equal elements.
This sort is stable (i.e., does not reorder equal elements) and O(m * n + n * log(n)) worst-case, where the key function is O(m).
During sorting, the key function is called at most once per element, by using temporary storage to remember the results of key evaluation. The order of calls to the key function is unspecified and may change in future versions of the standard library.
If the implementation of Ord
for K
does not implement a total order, the function
may panic; even if the function exits normally, the resulting order of elements in the slice
is unspecified. See also the note on panicking below.
For simple key functions (e.g., functions that are property accesses or basic operations),
sort_by_key
is likely to be faster.
§Current implementation
The current implementation is based on instruction-parallel-network sort by Lukas Bergdoll, which combines the fast average case of randomized quicksort with the fast worst case of heapsort, while achieving linear time on fully sorted and reversed inputs. And O(k * log(n)) where k is the number of distinct elements in the input. It leverages superscalar out-of-order execution capabilities commonly found in CPUs, to efficiently perform the operation.
In the worst case, the algorithm allocates temporary storage in a Vec<(K, usize)>
the
length of the slice.
§Panics
May panic if the implementation of Ord
for K
does not implement a total order, or if
the Ord
implementation panics.
All safe functions on slices preserve the invariant that even if the function panics, all
original elements will remain in the slice and any possible modifications via interior
mutability are observed in the input. This ensures that recovery code (for instance inside
of a Drop
or following a catch_unwind
) will still have access to all the original
elements. For instance, if the slice belongs to a Vec
, the Vec::drop
method will be able
to dispose of all contained elements.
§Examples
let mut v = [4i32, -5, 1, -3, 2, 10];
// Strings are sorted by lexicographical order.
v.sort_by_cached_key(|k| k.to_string());
assert_eq!(v, [-3, -5, 1, 10, 2, 4]);
1.0.0 · Sourcepub fn to_vec(&self) -> Vec<T>where
T: Clone,
pub fn to_vec(&self) -> Vec<T>where
T: Clone,
Copies self
into a new Vec
.
§Examples
let s = [10, 40, 30];
let x = s.to_vec();
// Here, `s` and `x` can be modified independently.
Examples found in repository?
597fn readback_indirect_parameters(
598 mut indirect_parameters_staging_buffers: ResMut<IndirectParametersStagingBuffers>,
599 saved_indirect_parameters: Res<SavedIndirectParameters>,
600 gpu_preprocessing_support: Res<GpuPreprocessingSupport>,
601) {
602 // If culling isn't supported on this platform, note that, and bail.
603 if gpu_preprocessing_support.max_supported_mode != GpuPreprocessingMode::Culling {
604 saved_indirect_parameters
605 .lock()
606 .unwrap()
607 .occlusion_culling_supported = false;
608 return;
609 }
610
611 // Grab the staging buffers.
612 let (Some(data_buffer), Some(batch_sets_buffer)) = (
613 indirect_parameters_staging_buffers.data.take(),
614 indirect_parameters_staging_buffers.batch_sets.take(),
615 ) else {
616 return;
617 };
618
619 // Read the GPU buffers back.
620 let saved_indirect_parameters_0 = (**saved_indirect_parameters).clone();
621 let saved_indirect_parameters_1 = (**saved_indirect_parameters).clone();
622 readback_buffer::<IndirectParametersIndexed>(data_buffer, move |indirect_parameters| {
623 saved_indirect_parameters_0.lock().unwrap().data = indirect_parameters.to_vec();
624 });
625 readback_buffer::<u32>(batch_sets_buffer, move |indirect_parameters_count| {
626 saved_indirect_parameters_1.lock().unwrap().count = indirect_parameters_count[0];
627 });
628}
More examples
156 fn bind_group_layout_entries(_: &RenderDevice, _: bool) -> Vec<BindGroupLayoutEntry>
157 where
158 Self: Sized,
159 {
160 BindGroupLayoutEntries::with_indices(
161 // The layout entries will only be visible in the fragment stage
162 ShaderStages::FRAGMENT,
163 (
164 // Screen texture
165 //
166 // @group(2) @binding(0) var textures: binding_array<texture_2d<f32>>;
167 (
168 0,
169 texture_2d(TextureSampleType::Float { filterable: true })
170 .count(NonZero::<u32>::new(MAX_TEXTURE_COUNT as u32).unwrap()),
171 ),
172 // Sampler
173 //
174 // @group(2) @binding(1) var nearest_sampler: sampler;
175 //
176 // Note: as with textures, multiple samplers can also be bound
177 // onto one binding slot:
178 //
179 // ```
180 // sampler(SamplerBindingType::Filtering)
181 // .count(NonZero::<u32>::new(MAX_TEXTURE_COUNT as u32).unwrap()),
182 // ```
183 //
184 // One may need to pay attention to the limit of sampler binding
185 // amount on some platforms.
186 (1, sampler(SamplerBindingType::Filtering)),
187 ),
188 )
189 .to_vec()
190 }
399fn receive_image_from_buffer(
400 image_copiers: Res<ImageCopiers>,
401 render_device: Res<RenderDevice>,
402 sender: Res<RenderWorldSender>,
403) {
404 for image_copier in image_copiers.0.iter() {
405 if !image_copier.enabled() {
406 continue;
407 }
408
409 // Finally time to get our data back from the gpu.
410 // First we get a buffer slice which represents a chunk of the buffer (which we
411 // can't access yet).
412 // We want the whole thing so use unbounded range.
413 let buffer_slice = image_copier.buffer.slice(..);
414
415 // Now things get complicated. WebGPU, for safety reasons, only allows either the GPU
416 // or CPU to access a buffer's contents at a time. We need to "map" the buffer which means
417 // flipping ownership of the buffer over to the CPU and making access legal. We do this
418 // with `BufferSlice::map_async`.
419 //
420 // The problem is that map_async is not an async function so we can't await it. What
421 // we need to do instead is pass in a closure that will be executed when the slice is
422 // either mapped or the mapping has failed.
423 //
424 // The problem with this is that we don't have a reliable way to wait in the main
425 // code for the buffer to be mapped and even worse, calling get_mapped_range or
426 // get_mapped_range_mut prematurely will cause a panic, not return an error.
427 //
428 // Using channels solves this as awaiting the receiving of a message from
429 // the passed closure will force the outside code to wait. It also doesn't hurt
430 // if the closure finishes before the outside code catches up as the message is
431 // buffered and receiving will just pick that up.
432 //
433 // It may also be worth noting that although on native, the usage of asynchronous
434 // channels is wholly unnecessary, for the sake of portability to Wasm
435 // we'll use async channels that work on both native and Wasm.
436
437 let (s, r) = crossbeam_channel::bounded(1);
438
439 // Maps the buffer so it can be read on the cpu
440 buffer_slice.map_async(MapMode::Read, move |r| match r {
441 // This will execute once the gpu is ready, so after the call to poll()
442 Ok(r) => s.send(r).expect("Failed to send map update"),
443 Err(err) => panic!("Failed to map buffer {err}"),
444 });
445
446 // In order for the mapping to be completed, one of three things must happen.
447 // One of those can be calling `Device::poll`. This isn't necessary on the web as devices
448 // are polled automatically but natively, we need to make sure this happens manually.
449 // `Maintain::Wait` will cause the thread to wait on native but not on WebGpu.
450
451 // This blocks until the gpu is done executing everything
452 render_device.poll(Maintain::wait()).panic_on_timeout();
453
454 // This blocks until the buffer is mapped
455 r.recv().expect("Failed to receive the map_async message");
456
457 // This could fail on app exit, if Main world clears resources (including receiver) while Render world still renders
458 let _ = sender.send(buffer_slice.get_mapped_range().to_vec());
459
460 // We need to make sure all `BufferView`'s are dropped before we do what we're about
461 // to do.
462 // Unmap so that we can copy to the staging buffer in the next iteration.
463 image_copier.buffer.unmap();
464 }
465}
51fn main() {
52 let mut world = World::new();
53 let mut lines = std::io::stdin().lines();
54 let mut component_names = HashMap::<String, ComponentId>::new();
55 let mut component_info = HashMap::<ComponentId, ComponentInfo>::new();
56
57 println!("{PROMPT}");
58 loop {
59 print!("\n> ");
60 let _ = std::io::stdout().flush();
61 let Some(Ok(line)) = lines.next() else {
62 return;
63 };
64
65 if line.is_empty() {
66 return;
67 };
68
69 let Some((first, rest)) = line.trim().split_once(|c: char| c.is_whitespace()) else {
70 match &line.chars().next() {
71 Some('c') => println!("{COMPONENT_PROMPT}"),
72 Some('s') => println!("{ENTITY_PROMPT}"),
73 Some('q') => println!("{QUERY_PROMPT}"),
74 _ => println!("{PROMPT}"),
75 }
76 continue;
77 };
78
79 match &first[0..1] {
80 "c" => {
81 rest.split(',').for_each(|component| {
82 let mut component = component.split_whitespace();
83 let Some(name) = component.next() else {
84 return;
85 };
86 let size = match component.next().map(str::parse) {
87 Some(Ok(size)) => size,
88 _ => 0,
89 };
90 // Register our new component to the world with a layout specified by it's size
91 // SAFETY: [u64] is Send + Sync
92 let id = world.register_component_with_descriptor(unsafe {
93 ComponentDescriptor::new_with_layout(
94 name.to_string(),
95 StorageType::Table,
96 Layout::array::<u64>(size).unwrap(),
97 None,
98 true,
99 ComponentCloneBehavior::Default,
100 )
101 });
102 let Some(info) = world.components().get_info(id) else {
103 return;
104 };
105 component_names.insert(name.to_string(), id);
106 component_info.insert(id, info.clone());
107 println!("Component {} created with id: {}", name, id.index());
108 });
109 }
110 "s" => {
111 let mut to_insert_ids = Vec::new();
112 let mut to_insert_data = Vec::new();
113 rest.split(',').for_each(|component| {
114 let mut component = component.split_whitespace();
115 let Some(name) = component.next() else {
116 return;
117 };
118
119 // Get the id for the component with the given name
120 let Some(&id) = component_names.get(name) else {
121 println!("Component {name} does not exist");
122 return;
123 };
124
125 // Calculate the length for the array based on the layout created for this component id
126 let info = world.components().get_info(id).unwrap();
127 let len = info.layout().size() / size_of::<u64>();
128 let mut values: Vec<u64> = component
129 .take(len)
130 .filter_map(|value| value.parse::<u64>().ok())
131 .collect();
132 values.resize(len, 0);
133
134 // Collect the id and array to be inserted onto our entity
135 to_insert_ids.push(id);
136 to_insert_data.push(values);
137 });
138
139 let mut entity = world.spawn_empty();
140
141 // Construct an `OwningPtr` for each component in `to_insert_data`
142 let to_insert_ptr = to_owning_ptrs(&mut to_insert_data);
143
144 // SAFETY:
145 // - Component ids have been taken from the same world
146 // - Each array is created to the layout specified in the world
147 unsafe {
148 entity.insert_by_ids(&to_insert_ids, to_insert_ptr.into_iter());
149 }
150
151 println!("Entity spawned with id: {}", entity.id());
152 }
153 "q" => {
154 let mut builder = QueryBuilder::<FilteredEntityMut>::new(&mut world);
155 parse_query(rest, &mut builder, &component_names);
156 let mut query = builder.build();
157 query.iter_mut(&mut world).for_each(|filtered_entity| {
158 let terms = filtered_entity
159 .access()
160 .try_iter_component_access()
161 .unwrap()
162 .map(|component_access| {
163 let id = *component_access.index();
164 let ptr = filtered_entity.get_by_id(id).unwrap();
165 let info = component_info.get(&id).unwrap();
166 let len = info.layout().size() / size_of::<u64>();
167
168 // SAFETY:
169 // - All components are created with layout [u64]
170 // - len is calculated from the component descriptor
171 let data = unsafe {
172 std::slice::from_raw_parts_mut(
173 ptr.assert_unique().as_ptr().cast::<u64>(),
174 len,
175 )
176 };
177
178 // If we have write access, increment each value once
179 if matches!(component_access, ComponentAccessKind::Exclusive(_)) {
180 data.iter_mut().for_each(|data| {
181 *data += 1;
182 });
183 }
184
185 format!("{}: {:?}", info.name(), data[0..len].to_vec())
186 })
187 .collect::<Vec<_>>()
188 .join(", ");
189
190 println!("{}: {}", filtered_entity.id(), terms);
191 });
192 }
193 _ => continue,
194 }
195 }
196}
Sourcepub fn to_vec_in<A>(&self, alloc: A) -> Vec<T, A>
🔬This is a nightly-only experimental API. (allocator_api
)
pub fn to_vec_in<A>(&self, alloc: A) -> Vec<T, A>
allocator_api
)Copies self
into a new Vec
with an allocator.
§Examples
#![feature(allocator_api)]
use std::alloc::System;
let s = [10, 40, 30];
let x = s.to_vec_in(System);
// Here, `s` and `x` can be modified independently.
1.0.0 · Sourcepub fn concat<Item>(&self) -> <[T] as Concat<Item>>::Output ⓘ
pub fn concat<Item>(&self) -> <[T] as Concat<Item>>::Output ⓘ
Flattens a slice of T
into a single value Self::Output
.
§Examples
assert_eq!(["hello", "world"].concat(), "helloworld");
assert_eq!([[1, 2], [3, 4]].concat(), [1, 2, 3, 4]);
1.3.0 · Sourcepub fn join<Separator>(
&self,
sep: Separator,
) -> <[T] as Join<Separator>>::Output ⓘ
pub fn join<Separator>( &self, sep: Separator, ) -> <[T] as Join<Separator>>::Output ⓘ
Flattens a slice of T
into a single value Self::Output
, placing a
given separator between each.
§Examples
assert_eq!(["hello", "world"].join(" "), "hello world");
assert_eq!([[1, 2], [3, 4]].join(&0), [1, 2, 0, 3, 4]);
assert_eq!([[1, 2], [3, 4]].join(&[0, 0][..]), [1, 2, 0, 0, 3, 4]);
Examples found in repository?
52fn check_for_gltf_extras(
53 gltf_extras_per_entity: Query<(
54 Entity,
55 Option<&Name>,
56 Option<&GltfSceneExtras>,
57 Option<&GltfExtras>,
58 Option<&GltfMeshExtras>,
59 Option<&GltfMaterialExtras>,
60 )>,
61 mut display: Single<&mut Text, With<ExampleDisplay>>,
62) {
63 let mut gltf_extra_infos_lines: Vec<String> = vec![];
64
65 for (id, name, scene_extras, extras, mesh_extras, material_extras) in
66 gltf_extras_per_entity.iter()
67 {
68 if scene_extras.is_some()
69 || extras.is_some()
70 || mesh_extras.is_some()
71 || material_extras.is_some()
72 {
73 let formatted_extras = format!(
74 "Extras per entity {} ('Name: {}'):
75 - scene extras: {:?}
76 - primitive extras: {:?}
77 - mesh extras: {:?}
78 - material extras: {:?}
79 ",
80 id,
81 name.unwrap_or(&Name::default()),
82 scene_extras,
83 extras,
84 mesh_extras,
85 material_extras
86 );
87 gltf_extra_infos_lines.push(formatted_extras);
88 }
89 display.0 = gltf_extra_infos_lines.join("\n");
90 }
91}
More examples
78 fn debug_relationships(
79 // Not all of our entities are targeted by something, so we use `Option` in our query to handle this case.
80 relations_query: Query<(&Name, &Targeting, Option<&TargetedBy>)>,
81 name_query: Query<&Name>,
82 ) {
83 let mut relationships = String::new();
84
85 for (name, targeting, maybe_targeted_by) in relations_query.iter() {
86 let targeting_name = name_query.get(targeting.0).unwrap();
87 let targeted_by_string = if let Some(targeted_by) = maybe_targeted_by {
88 let mut vec_of_names = Vec::<&Name>::new();
89
90 for entity in &targeted_by.0 {
91 let name = name_query.get(*entity).unwrap();
92 vec_of_names.push(name);
93 }
94
95 // Convert this to a nice string for printing.
96 let vec_of_str: Vec<&str> = vec_of_names.iter().map(|name| name.as_str()).collect();
97 vec_of_str.join(", ")
98 } else {
99 "nobody".to_string()
100 };
101
102 relationships.push_str(&format!(
103 "{name} is targeting {targeting_name}, and is targeted by {targeted_by_string}\n",
104 ));
105 }
106
107 println!("{}", relationships);
108 }
51fn main() {
52 let mut world = World::new();
53 let mut lines = std::io::stdin().lines();
54 let mut component_names = HashMap::<String, ComponentId>::new();
55 let mut component_info = HashMap::<ComponentId, ComponentInfo>::new();
56
57 println!("{PROMPT}");
58 loop {
59 print!("\n> ");
60 let _ = std::io::stdout().flush();
61 let Some(Ok(line)) = lines.next() else {
62 return;
63 };
64
65 if line.is_empty() {
66 return;
67 };
68
69 let Some((first, rest)) = line.trim().split_once(|c: char| c.is_whitespace()) else {
70 match &line.chars().next() {
71 Some('c') => println!("{COMPONENT_PROMPT}"),
72 Some('s') => println!("{ENTITY_PROMPT}"),
73 Some('q') => println!("{QUERY_PROMPT}"),
74 _ => println!("{PROMPT}"),
75 }
76 continue;
77 };
78
79 match &first[0..1] {
80 "c" => {
81 rest.split(',').for_each(|component| {
82 let mut component = component.split_whitespace();
83 let Some(name) = component.next() else {
84 return;
85 };
86 let size = match component.next().map(str::parse) {
87 Some(Ok(size)) => size,
88 _ => 0,
89 };
90 // Register our new component to the world with a layout specified by it's size
91 // SAFETY: [u64] is Send + Sync
92 let id = world.register_component_with_descriptor(unsafe {
93 ComponentDescriptor::new_with_layout(
94 name.to_string(),
95 StorageType::Table,
96 Layout::array::<u64>(size).unwrap(),
97 None,
98 true,
99 ComponentCloneBehavior::Default,
100 )
101 });
102 let Some(info) = world.components().get_info(id) else {
103 return;
104 };
105 component_names.insert(name.to_string(), id);
106 component_info.insert(id, info.clone());
107 println!("Component {} created with id: {}", name, id.index());
108 });
109 }
110 "s" => {
111 let mut to_insert_ids = Vec::new();
112 let mut to_insert_data = Vec::new();
113 rest.split(',').for_each(|component| {
114 let mut component = component.split_whitespace();
115 let Some(name) = component.next() else {
116 return;
117 };
118
119 // Get the id for the component with the given name
120 let Some(&id) = component_names.get(name) else {
121 println!("Component {name} does not exist");
122 return;
123 };
124
125 // Calculate the length for the array based on the layout created for this component id
126 let info = world.components().get_info(id).unwrap();
127 let len = info.layout().size() / size_of::<u64>();
128 let mut values: Vec<u64> = component
129 .take(len)
130 .filter_map(|value| value.parse::<u64>().ok())
131 .collect();
132 values.resize(len, 0);
133
134 // Collect the id and array to be inserted onto our entity
135 to_insert_ids.push(id);
136 to_insert_data.push(values);
137 });
138
139 let mut entity = world.spawn_empty();
140
141 // Construct an `OwningPtr` for each component in `to_insert_data`
142 let to_insert_ptr = to_owning_ptrs(&mut to_insert_data);
143
144 // SAFETY:
145 // - Component ids have been taken from the same world
146 // - Each array is created to the layout specified in the world
147 unsafe {
148 entity.insert_by_ids(&to_insert_ids, to_insert_ptr.into_iter());
149 }
150
151 println!("Entity spawned with id: {}", entity.id());
152 }
153 "q" => {
154 let mut builder = QueryBuilder::<FilteredEntityMut>::new(&mut world);
155 parse_query(rest, &mut builder, &component_names);
156 let mut query = builder.build();
157 query.iter_mut(&mut world).for_each(|filtered_entity| {
158 let terms = filtered_entity
159 .access()
160 .try_iter_component_access()
161 .unwrap()
162 .map(|component_access| {
163 let id = *component_access.index();
164 let ptr = filtered_entity.get_by_id(id).unwrap();
165 let info = component_info.get(&id).unwrap();
166 let len = info.layout().size() / size_of::<u64>();
167
168 // SAFETY:
169 // - All components are created with layout [u64]
170 // - len is calculated from the component descriptor
171 let data = unsafe {
172 std::slice::from_raw_parts_mut(
173 ptr.assert_unique().as_ptr().cast::<u64>(),
174 len,
175 )
176 };
177
178 // If we have write access, increment each value once
179 if matches!(component_access, ComponentAccessKind::Exclusive(_)) {
180 data.iter_mut().for_each(|data| {
181 *data += 1;
182 });
183 }
184
185 format!("{}: {:?}", info.name(), data[0..len].to_vec())
186 })
187 .collect::<Vec<_>>()
188 .join(", ");
189
190 println!("{}: {}", filtered_entity.id(), terms);
191 });
192 }
193 _ => continue,
194 }
195 }
196}
1.0.0 · Sourcepub fn connect<Separator>(
&self,
sep: Separator,
) -> <[T] as Join<Separator>>::Output ⓘ
👎Deprecated since 1.3.0: renamed to join
pub fn connect<Separator>( &self, sep: Separator, ) -> <[T] as Join<Separator>>::Output ⓘ
Flattens a slice of T
into a single value Self::Output
, placing a
given separator between each.
§Examples
assert_eq!(["hello", "world"].connect(" "), "hello world");
assert_eq!([[1, 2], [3, 4]].connect(&0), [1, 2, 0, 3, 4]);
Trait Implementations§
Source§impl Component for BoxShadow
impl Component for BoxShadow
Source§const STORAGE_TYPE: StorageType = bevy_ecs::component::StorageType::Table
const STORAGE_TYPE: StorageType = bevy_ecs::component::StorageType::Table
Source§type Mutability = Mutable
type Mutability = Mutable
Component<Mutability = Mutable>
],
while immutable components will instead have [Component<Mutability = Immutable>
]. Read moreSource§fn register_required_components(
requiree: ComponentId,
components: &mut ComponentsRegistrator<'_>,
required_components: &mut RequiredComponents,
inheritance_depth: u16,
recursion_check_stack: &mut Vec<ComponentId>,
)
fn register_required_components( requiree: ComponentId, components: &mut ComponentsRegistrator<'_>, required_components: &mut RequiredComponents, inheritance_depth: u16, recursion_check_stack: &mut Vec<ComponentId>, )
Source§fn clone_behavior() -> ComponentCloneBehavior
fn clone_behavior() -> ComponentCloneBehavior
Source§fn register_component_hooks(hooks: &mut ComponentHooks)
fn register_component_hooks(hooks: &mut ComponentHooks)
Component::on_add
, etc.)ComponentHooks
.Source§fn on_add() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_add() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn on_insert() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_insert() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn on_replace() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_replace() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn on_remove() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_remove() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn on_despawn() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_despawn() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn map_entities<E>(_this: &mut Self, _mapper: &mut E)where
E: EntityMapper,
fn map_entities<E>(_this: &mut Self, _mapper: &mut E)where
E: EntityMapper,
EntityMapper
. This is used to remap entities in contexts like scenes and entity cloning.
When deriving Component
, this is populated by annotating fields containing entities with #[entities]
Read moreSource§impl<'de> Deserialize<'de> for BoxShadow
impl<'de> Deserialize<'de> for BoxShadow
Source§fn deserialize<__D>(
__deserializer: __D,
) -> Result<BoxShadow, <__D as Deserializer<'de>>::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(
__deserializer: __D,
) -> Result<BoxShadow, <__D as Deserializer<'de>>::Error>where
__D: Deserializer<'de>,
Source§impl From<ShadowStyle> for BoxShadow
impl From<ShadowStyle> for BoxShadow
Source§fn from(value: ShadowStyle) -> BoxShadow
fn from(value: ShadowStyle) -> BoxShadow
Source§impl FromArg for &'static BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl FromArg for &'static BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§impl FromArg for &'static mut BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl FromArg for &'static mut BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§impl FromArg for BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl FromArg for BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§impl FromReflect for BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl FromReflect for BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§fn from_reflect(reflect: &(dyn PartialReflect + 'static)) -> Option<BoxShadow>
fn from_reflect(reflect: &(dyn PartialReflect + 'static)) -> Option<BoxShadow>
Self
from a reflected value.Source§fn take_from_reflect(
reflect: Box<dyn PartialReflect>,
) -> Result<Self, Box<dyn PartialReflect>>
fn take_from_reflect( reflect: Box<dyn PartialReflect>, ) -> Result<Self, Box<dyn PartialReflect>>
Self
using,
constructing the value using from_reflect
if that fails. Read moreSource§impl GetOwnership for &BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl GetOwnership for &BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§impl GetOwnership for &mut BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl GetOwnership for &mut BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§impl GetOwnership for BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl GetOwnership for BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§impl GetTypeRegistration for BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl GetTypeRegistration for BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§fn get_type_registration() -> TypeRegistration
fn get_type_registration() -> TypeRegistration
TypeRegistration
for this type.Source§fn register_type_dependencies(registry: &mut TypeRegistry)
fn register_type_dependencies(registry: &mut TypeRegistry)
Source§impl IntoReturn for &BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl IntoReturn for &BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§impl IntoReturn for &mut BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl IntoReturn for &mut BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§impl IntoReturn for BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl IntoReturn for BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§impl PartialReflect for BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl PartialReflect for BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§fn get_represented_type_info(&self) -> Option<&'static TypeInfo>
fn get_represented_type_info(&self) -> Option<&'static TypeInfo>
Source§fn try_apply(
&mut self,
value: &(dyn PartialReflect + 'static),
) -> Result<(), ApplyError>
fn try_apply( &mut self, value: &(dyn PartialReflect + 'static), ) -> Result<(), ApplyError>
Source§fn reflect_kind(&self) -> ReflectKind
fn reflect_kind(&self) -> ReflectKind
Source§fn reflect_ref(&self) -> ReflectRef<'_>
fn reflect_ref(&self) -> ReflectRef<'_>
Source§fn reflect_mut(&mut self) -> ReflectMut<'_>
fn reflect_mut(&mut self) -> ReflectMut<'_>
Source§fn reflect_owned(self: Box<BoxShadow>) -> ReflectOwned
fn reflect_owned(self: Box<BoxShadow>) -> ReflectOwned
Source§fn try_into_reflect(
self: Box<BoxShadow>,
) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>>
fn try_into_reflect( self: Box<BoxShadow>, ) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>>
Source§fn try_as_reflect(&self) -> Option<&(dyn Reflect + 'static)>
fn try_as_reflect(&self) -> Option<&(dyn Reflect + 'static)>
Source§fn try_as_reflect_mut(&mut self) -> Option<&mut (dyn Reflect + 'static)>
fn try_as_reflect_mut(&mut self) -> Option<&mut (dyn Reflect + 'static)>
Source§fn into_partial_reflect(self: Box<BoxShadow>) -> Box<dyn PartialReflect>
fn into_partial_reflect(self: Box<BoxShadow>) -> Box<dyn PartialReflect>
Source§fn as_partial_reflect(&self) -> &(dyn PartialReflect + 'static)
fn as_partial_reflect(&self) -> &(dyn PartialReflect + 'static)
Source§fn as_partial_reflect_mut(&mut self) -> &mut (dyn PartialReflect + 'static)
fn as_partial_reflect_mut(&mut self) -> &mut (dyn PartialReflect + 'static)
Source§fn reflect_partial_eq(
&self,
value: &(dyn PartialReflect + 'static),
) -> Option<bool>
fn reflect_partial_eq( &self, value: &(dyn PartialReflect + 'static), ) -> Option<bool>
Source§fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError>
fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError>
Self
using reflection. Read moreSource§fn apply(&mut self, value: &(dyn PartialReflect + 'static))
fn apply(&mut self, value: &(dyn PartialReflect + 'static))
Source§fn clone_value(&self) -> Box<dyn PartialReflect>
fn clone_value(&self) -> Box<dyn PartialReflect>
reflect_clone
. To convert reflected values to dynamic ones, use to_dynamic
.Self
into its dynamic representation. Read moreSource§fn to_dynamic(&self) -> Box<dyn PartialReflect>
fn to_dynamic(&self) -> Box<dyn PartialReflect>
Source§fn reflect_hash(&self) -> Option<u64>
fn reflect_hash(&self) -> Option<u64>
Source§fn debug(&self, f: &mut Formatter<'_>) -> Result<(), Error>
fn debug(&self, f: &mut Formatter<'_>) -> Result<(), Error>
Source§fn is_dynamic(&self) -> bool
fn is_dynamic(&self) -> bool
Source§impl Reflect for BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl Reflect for BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§fn into_any(self: Box<BoxShadow>) -> Box<dyn Any>
fn into_any(self: Box<BoxShadow>) -> Box<dyn Any>
Box<dyn Any>
. Read moreSource§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut dyn Any
. Read moreSource§fn into_reflect(self: Box<BoxShadow>) -> Box<dyn Reflect>
fn into_reflect(self: Box<BoxShadow>) -> Box<dyn Reflect>
Source§fn as_reflect(&self) -> &(dyn Reflect + 'static)
fn as_reflect(&self) -> &(dyn Reflect + 'static)
Source§fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)
fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)
Source§impl Serialize for BoxShadow
impl Serialize for BoxShadow
Source§fn serialize<__S>(
&self,
__serializer: __S,
) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>where
__S: Serializer,
fn serialize<__S>(
&self,
__serializer: __S,
) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>where
__S: Serializer,
Source§impl TupleStruct for BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl TupleStruct for BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
Source§fn field(&self, index: usize) -> Option<&(dyn PartialReflect + 'static)>
fn field(&self, index: usize) -> Option<&(dyn PartialReflect + 'static)>
index
as a
&dyn Reflect
.Source§fn field_mut(
&mut self,
index: usize,
) -> Option<&mut (dyn PartialReflect + 'static)>
fn field_mut( &mut self, index: usize, ) -> Option<&mut (dyn PartialReflect + 'static)>
index
as a &mut dyn Reflect
.Source§fn iter_fields(&self) -> TupleStructFieldIter<'_> ⓘ
fn iter_fields(&self) -> TupleStructFieldIter<'_> ⓘ
Source§fn to_dynamic_tuple_struct(&self) -> DynamicTupleStruct
fn to_dynamic_tuple_struct(&self) -> DynamicTupleStruct
DynamicTupleStruct
from this tuple struct.Source§fn clone_dynamic(&self) -> DynamicTupleStruct
fn clone_dynamic(&self) -> DynamicTupleStruct
to_dynamic_tuple_struct
insteadDynamicTupleStruct
.Source§fn get_represented_tuple_struct_info(&self) -> Option<&'static TupleStructInfo>
fn get_represented_tuple_struct_info(&self) -> Option<&'static TupleStructInfo>
None
if TypeInfo
is not available.Source§impl TypePath for BoxShadow
impl TypePath for BoxShadow
Source§fn type_path() -> &'static str
fn type_path() -> &'static str
Source§fn short_type_path() -> &'static str
fn short_type_path() -> &'static str
Source§fn type_ident() -> Option<&'static str>
fn type_ident() -> Option<&'static str>
Source§fn crate_name() -> Option<&'static str>
fn crate_name() -> Option<&'static str>
Source§impl Typed for BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl Typed for BoxShadowwhere
BoxShadow: Any + Send + Sync,
Vec<ShadowStyle>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
impl StructuralPartialEq for BoxShadow
Auto Trait Implementations§
impl Freeze for BoxShadow
impl RefUnwindSafe for BoxShadow
impl Send for BoxShadow
impl Sync for BoxShadow
impl Unpin for BoxShadow
impl UnwindSafe for BoxShadow
Blanket Implementations§
Source§impl<T, U> AsBindGroupShaderType<U> for T
impl<T, U> AsBindGroupShaderType<U> for T
Source§fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
T
ShaderType
for self
. When used in AsBindGroup
derives, it is safe to assume that all images in self
exist.Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<C> Bundle for Cwhere
C: Component,
impl<C> Bundle for Cwhere
C: Component,
fn component_ids( components: &mut ComponentsRegistrator<'_>, ids: &mut impl FnMut(ComponentId), )
Source§fn register_required_components(
components: &mut ComponentsRegistrator<'_>,
required_components: &mut RequiredComponents,
)
fn register_required_components( components: &mut ComponentsRegistrator<'_>, required_components: &mut RequiredComponents, )
Bundle
.Source§fn get_component_ids(
components: &Components,
ids: &mut impl FnMut(Option<ComponentId>),
)
fn get_component_ids( components: &Components, ids: &mut impl FnMut(Option<ComponentId>), )
Source§impl<C> BundleFromComponents for Cwhere
C: Component,
impl<C> BundleFromComponents for Cwhere
C: Component,
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait>
(where Trait: Downcast
) to Box<dyn Any>
, which can then be
downcast
into Box<dyn ConcreteType>
where ConcreteType
implements Trait
.Source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait>
(where Trait: Downcast
) to Rc<Any>
, which can then be further
downcast
into Rc<ConcreteType>
where ConcreteType
implements Trait
.Source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &Any
’s vtable from &Trait
’s.Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &mut Any
’s vtable from &mut Trait
’s.Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait>
(where Trait: Downcast
) to Box<dyn Any>
. Box<dyn Any>
can
then be further downcast
into Box<ConcreteType>
where ConcreteType
implements Trait
.Source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait>
(where Trait: Downcast
) to Rc<Any>
. Rc<Any>
can then be
further downcast
into Rc<ConcreteType>
where ConcreteType
implements Trait
.Source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &Any
’s vtable from &Trait
’s.Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &mut Any
’s vtable from &mut Trait
’s.Source§impl<T> DowncastSend for T
impl<T> DowncastSend for T
Source§impl<T> DowncastSync for T
impl<T> DowncastSync for T
Source§impl<C> DynamicBundle for Cwhere
C: Component,
impl<C> DynamicBundle for Cwhere
C: Component,
fn get_components( self, func: &mut impl FnMut(StorageType, OwningPtr<'_>), ) -> <C as DynamicBundle>::Effect
Source§impl<T> DynamicTypePath for Twhere
T: TypePath,
impl<T> DynamicTypePath for Twhere
T: TypePath,
Source§fn reflect_type_path(&self) -> &str
fn reflect_type_path(&self) -> &str
TypePath::type_path
.Source§fn reflect_short_type_path(&self) -> &str
fn reflect_short_type_path(&self) -> &str
Source§fn reflect_type_ident(&self) -> Option<&str>
fn reflect_type_ident(&self) -> Option<&str>
TypePath::type_ident
.Source§fn reflect_crate_name(&self) -> Option<&str>
fn reflect_crate_name(&self) -> Option<&str>
TypePath::crate_name
.Source§fn reflect_module_path(&self) -> Option<&str>
fn reflect_module_path(&self) -> Option<&str>
Source§impl<T> DynamicTyped for Twhere
T: Typed,
impl<T> DynamicTyped for Twhere
T: Typed,
Source§fn reflect_type_info(&self) -> &'static TypeInfo
fn reflect_type_info(&self) -> &'static TypeInfo
Typed::type_info
.Source§impl<T> FmtForward for T
impl<T> FmtForward for T
Source§fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
self
to use its Binary
implementation when Debug
-formatted.Source§fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
self
to use its Display
implementation when
Debug
-formatted.Source§fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
self
to use its LowerExp
implementation when
Debug
-formatted.Source§fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
self
to use its LowerHex
implementation when
Debug
-formatted.Source§fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
self
to use its Octal
implementation when Debug
-formatted.Source§fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
self
to use its Pointer
implementation when
Debug
-formatted.Source§fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
self
to use its UpperExp
implementation when
Debug
-formatted.Source§fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
self
to use its UpperHex
implementation when
Debug
-formatted.Source§impl<S> FromSample<S> for S
impl<S> FromSample<S> for S
fn from_sample_(s: S) -> S
Source§impl<T> FromWorld for Twhere
T: Default,
impl<T> FromWorld for Twhere
T: Default,
Source§fn from_world(_world: &mut World) -> T
fn from_world(_world: &mut World) -> T
Creates Self
using default()
.
Source§impl<T> GetPath for T
impl<T> GetPath for T
Source§fn reflect_path<'p>(
&self,
path: impl ReflectPath<'p>,
) -> Result<&(dyn PartialReflect + 'static), ReflectPathError<'p>>
fn reflect_path<'p>( &self, path: impl ReflectPath<'p>, ) -> Result<&(dyn PartialReflect + 'static), ReflectPathError<'p>>
path
. Read moreSource§fn reflect_path_mut<'p>(
&mut self,
path: impl ReflectPath<'p>,
) -> Result<&mut (dyn PartialReflect + 'static), ReflectPathError<'p>>
fn reflect_path_mut<'p>( &mut self, path: impl ReflectPath<'p>, ) -> Result<&mut (dyn PartialReflect + 'static), ReflectPathError<'p>>
path
. Read moreSource§fn path<'p, T>(
&self,
path: impl ReflectPath<'p>,
) -> Result<&T, ReflectPathError<'p>>where
T: Reflect,
fn path<'p, T>(
&self,
path: impl ReflectPath<'p>,
) -> Result<&T, ReflectPathError<'p>>where
T: Reflect,
path
. Read moreSource§fn path_mut<'p, T>(
&mut self,
path: impl ReflectPath<'p>,
) -> Result<&mut T, ReflectPathError<'p>>where
T: Reflect,
fn path_mut<'p, T>(
&mut self,
path: impl ReflectPath<'p>,
) -> Result<&mut T, ReflectPathError<'p>>where
T: Reflect,
path
. Read moreSource§impl<S> GetTupleStructField for Swhere
S: TupleStruct,
impl<S> GetTupleStructField for Swhere
S: TupleStruct,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
fn into_sample(self) -> T
Source§impl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
Source§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
Source§fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
self
and passes that borrow into the pipe function. Read moreSource§fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
self
and passes that borrow into the pipe function. Read moreSource§fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
Source§fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R,
) -> R
fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
Source§fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
self
, then passes self.as_ref()
into the pipe function.Source§fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
self
, then passes self.as_mut()
into the pipe
function.Source§fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
self
, then passes self.deref()
into the pipe function.Source§impl<T> Pointable for T
impl<T> Pointable for T
Source§impl<R, P> ReadPrimitive<R> for P
impl<R, P> ReadPrimitive<R> for P
Source§fn read_from_little_endian(read: &mut R) -> Result<Self, Error>
fn read_from_little_endian(read: &mut R) -> Result<Self, Error>
ReadEndian::read_from_little_endian()
.Source§impl<T> Serialize for T
impl<T> Serialize for T
fn erased_serialize(&self, serializer: &mut dyn Serializer) -> Result<(), Error>
fn do_erased_serialize( &self, serializer: &mut dyn Serializer, ) -> Result<(), ErrorImpl>
Source§impl<T> Tap for T
impl<T> Tap for T
Source§fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
Borrow<B>
of a value. Read moreSource§fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
BorrowMut<B>
of a value. Read moreSource§fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
AsRef<R>
view of a value. Read moreSource§fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
AsMut<R>
view of a value. Read moreSource§fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
Deref::Target
of a value. Read moreSource§fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
Deref::Target
of a value. Read moreSource§fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
.tap()
only in debug builds, and is erased in release builds.Source§fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
.tap_mut()
only in debug builds, and is erased in release
builds.Source§fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
.tap_borrow()
only in debug builds, and is erased in release
builds.Source§fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
.tap_borrow_mut()
only in debug builds, and is erased in release
builds.Source§fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
.tap_ref()
only in debug builds, and is erased in release
builds.Source§fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
.tap_ref_mut()
only in debug builds, and is erased in release
builds.Source§fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
.tap_deref()
only in debug builds, and is erased in release
builds.