Skip to main content

BindingResources

Struct BindingResources 

Source
pub struct BindingResources(pub Vec<(u32, OwnedBindingResource)>);
Available on crate feature bevy_render only.
Expand description

A pair of binding index and binding resource, used as part of PreparedBindGroup.

Tuple Fields§

§0: Vec<(u32, OwnedBindingResource)>

Methods from Deref<Target = Vec<(u32, OwnedBindingResource)>>§

1.0.0 · Source

pub fn push(&mut self, value: T)

Available on non-no_global_oom_handling only.

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?
examples/showcase/stepping.rs (line 23)
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<(
108        bevy_ecs::intern::Interned<dyn ScheduleLabel + 'static>,
109        NodeId,
110    )> = Vec::new();
111
112    let Ok(schedule_order) = stepping.schedules() else {
113        return;
114    };
115
116    // go through the stepping schedules and construct a list of systems for
117    // each label
118    for label in schedule_order {
119        let schedule = schedules.get(*label).unwrap();
120        text_spans.push((
121            TextSpan(format!("{label:?}\n")),
122            TextFont {
123                font: asset_server.load(FONT_BOLD).into(),
124                ..default()
125            },
126            TextColor(FONT_COLOR),
127        ));
128
129        // grab the list of systems in the schedule, in the order the
130        // single-threaded executor would run them.
131        let Ok(systems) = schedule.systems() else {
132            return;
133        };
134
135        for (key, system) in systems {
136            // skip bevy default systems; we don't want to step those
137            #[cfg(feature = "debug")]
138            if system.name().as_string().starts_with("bevy") {
139                always_run.push((*label, NodeId::System(key)));
140                continue;
141            }
142
143            // Add an entry to our systems list so we can find where to draw
144            // the cursor when the stepping cursor is at this system
145            // we add plus 1 to account for the empty root span
146            state
147                .systems
148                .push((*label, NodeId::System(key), text_spans.len() + 1));
149
150            // Add a text section for displaying the cursor for this system
151            text_spans.push((
152                TextSpan::new("   "),
153                TextFont::default(),
154                TextColor(FONT_COLOR),
155            ));
156
157            // add the name of the system to the ui
158            text_spans.push((
159                TextSpan(format!("{}\n", system.name())),
160                TextFont::default(),
161                TextColor(FONT_COLOR),
162            ));
163        }
164    }
165
166    for (label, node) in always_run.drain(..) {
167        stepping.always_run_node(label, node);
168    }
169
170    commands.spawn((
171        Text::default(),
172        SteppingUi,
173        Node {
174            position_type: PositionType::Absolute,
175            top: state.ui_top,
176            left: state.ui_left,
177            padding: UiRect::all(px(10)),
178            ..default()
179        },
180        BackgroundColor(Color::srgba(1.0, 1.0, 1.0, 0.33)),
181        Visibility::Hidden,
182        Children::spawn(text_spans),
183    ));
184}
More examples
Hide additional examples
examples/shader/shader_defs.rs (line 70)
62    fn specialize(
63        _pipeline: &MaterialPipeline,
64        descriptor: &mut RenderPipelineDescriptor,
65        _layout: &MeshVertexBufferLayoutRef,
66        key: MaterialPipelineKey<Self>,
67    ) -> Result<(), SpecializedMeshPipelineError> {
68        if key.bind_group_data.is_red {
69            let fragment = descriptor.fragment.as_mut().unwrap();
70            fragment.shader_defs.push("IS_RED".into());
71        }
72        Ok(())
73    }
examples/shader/pipeline_constants.rs (line 96)
85    fn specialize(
86        _pipeline: &Material2dPipeline,
87        descriptor: &mut RenderPipelineDescriptor,
88        _layout: &MeshVertexBufferLayoutRef,
89        key: Material2dKey<Self>,
90    ) -> Result<(), SpecializedMeshPipelineError> {
91        descriptor
92            .fragment
93            .as_mut()
94            .unwrap()
95            .constants
96            .push(("LEVELS".into(), key.bind_group_data.levels as f64));
97        Ok(())
98    }
examples/ecs/message.rs (lines 60-62)
56fn apply_extra_damage(mut dmg_messages: MessageMutator<DealDamage>) {
57    let mut extra = Vec::new();
58    for message in dmg_messages.read() {
59        if message.amount >= 10 {
60            extra.push(DealDamage {
61                amount: message.amount / 10,
62            });
63        }
64    }
65    // Note that this system will read messages it wrote itself!
66    // These are written after the `read()`, so they will be read the next time it runs.
67    for message in extra {
68        dmg_messages.write(message);
69    }
70}
examples/gltf/gltf_extension_animation_graph.rs (line 145)
130    fn build(&self, app: &mut App) {
131        #[cfg(target_family = "wasm")]
132        bevy::tasks::block_on(async {
133            app.world_mut()
134                .resource_mut::<GltfExtensionHandlers>()
135                .0
136                .write()
137                .await
138                .push(Box::new(GltfExtensionHandlerAnimation::default()))
139        });
140        #[cfg(not(target_family = "wasm"))]
141        app.world_mut()
142            .resource_mut::<GltfExtensionHandlers>()
143            .0
144            .write_blocking()
145            .push(Box::new(GltfExtensionHandlerAnimation::default()));
146    }
examples/gltf/gltf_extension_mesh_2d.rs (line 85)
70    fn build(&self, app: &mut App) {
71        #[cfg(target_family = "wasm")]
72        bevy::tasks::block_on(async {
73            app.world_mut()
74                .resource_mut::<GltfExtensionHandlers>()
75                .0
76                .write()
77                .await
78                .push(Box::new(GltfExtensionHandlerToMesh2d))
79        });
80        #[cfg(not(target_family = "wasm"))]
81        app.world_mut()
82            .resource_mut::<GltfExtensionHandlers>()
83            .0
84            .write_blocking()
85            .push(Box::new(GltfExtensionHandlerToMesh2d));
86
87        app.add_plugins(Material2dPlugin::<CustomMaterial>::default());
88    }
1.95.0 · Source

pub fn push_mut(&mut self, value: T) -> &mut T

Available on non-no_global_oom_handling only.

Appends an element to the back of a collection, returning a reference to it.

§Panics

Panics if the new capacity exceeds isize::MAX bytes.

§Examples
let mut vec = vec![1, 2];
let last = vec.push_mut(3);
assert_eq!(*last, 3);
assert_eq!(vec, [1, 2, 3]);

let last = vec.push_mut(3);
*last += 1;
assert_eq!(vec, [1, 2, 3, 4]);
§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.

1.0.0 · Source

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 · Source

pub fn reserve(&mut self, additional: usize)

Available on non-no_global_oom_handling only.

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 · Source

pub fn reserve_exact(&mut self, additional: usize)

Available on non-no_global_oom_handling only.

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 · Source

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 · Source

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 · Source

pub fn shrink_to_fit(&mut self)

Available on non-no_global_oom_handling only.

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 · Source

pub fn shrink_to(&mut self, min_capacity: usize)

Available on non-no_global_oom_handling only.

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);
Source

pub fn try_shrink_to_fit(&mut self) -> Result<(), TryReserveError>

🔬This is a nightly-only experimental API. (vec_fallible_shrink)

Tries to shrink 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.

§Errors

This function returns an error if the allocator fails to shrink the allocation, the vector thereafter is still safe to use, the capacity remains unchanged however. See Allocator::shrink.

§Examples
#![feature(vec_fallible_shrink)]

let mut vec = Vec::with_capacity(10);
vec.extend([1, 2, 3]);
assert!(vec.capacity() >= 10);
vec.try_shrink_to_fit().expect("for this test, shrink shouldn't fail");
assert!(vec.capacity() >= 3);
Source

pub fn try_shrink_to( &mut self, min_capacity: usize, ) -> Result<(), TryReserveError>

🔬This is a nightly-only experimental API. (vec_fallible_shrink)

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.

§Errors

This function returns an error if the allocator fails to shrink the allocation, the vector thereafter is still safe to use, the capacity remains unchanged however. See Allocator::shrink.

§Examples
#![feature(vec_fallible_shrink)]

let mut vec = Vec::with_capacity(10);
vec.extend([1, 2, 3]);
assert!(vec.capacity() >= 10);
vec.try_shrink_to(4).expect("for this test, shrink shouldn't fail");
assert!(vec.capacity() >= 4);
vec.try_shrink_to(0).expect("this is a no-op and thus the allocator isn't involved.");
assert!(vec.capacity() >= 3);
1.0.0 · Source

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 · Source

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?
examples/shader_advanced/custom_shader_instancing.rs (line 222)
214fn prepare_instance_buffers(
215    mut commands: Commands,
216    query: Query<(Entity, &InstanceMaterialData)>,
217    render_device: Res<RenderDevice>,
218) {
219    for (entity, instance_data) in &query {
220        let buffer = render_device.create_buffer_with_data(&BufferInitDescriptor {
221            label: Some("instance data buffer"),
222            contents: bytemuck::cast_slice(instance_data.as_slice()),
223            usage: BufferUsages::VERTEX | BufferUsages::COPY_DST,
224        });
225        commands.entity(entity).insert(InstanceBuffer {
226            buffer,
227            length: instance_data.len(),
228        });
229    }
230}
More examples
Hide additional examples
examples/asset/asset_decompression.rs (line 66)
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            .path()
52            .file_name()
53            .ok_or(GzAssetLoaderError::IndeterminateFilePath)?
54            .to_string_lossy();
55        let uncompressed_file_name = file_name
56            .strip_suffix(".gz")
57            .ok_or(GzAssetLoaderError::IndeterminateFilePath)?;
58        let contained_path = compressed_path
59            .resolve_embed_str(uncompressed_file_name)
60            .map_err(|_| GzAssetLoaderError::IndeterminateFilePath)?;
61
62        let mut bytes_compressed = Vec::new();
63
64        reader.read_to_end(&mut bytes_compressed).await?;
65
66        let mut decoder = GzDecoder::new(bytes_compressed.as_slice());
67
68        let mut bytes_uncompressed = Vec::new();
69
70        decoder.read_to_end(&mut bytes_uncompressed)?;
71
72        // Now that we have decompressed the asset, let's pass it back to the
73        // context to continue loading
74
75        let mut reader = VecReader::new(bytes_uncompressed);
76
77        let uncompressed = load_context
78            .load_builder()
79            .load_untyped_value_from_reader(contained_path, &mut reader)
80            .await?;
81
82        Ok(GzAsset { uncompressed })
83    }
1.7.0 · Source

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 · Source

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 · Source

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.

The method also guarantees that, as long as T is not zero-sized and the capacity is nonzero, the pointer may be passed into dealloc with a layout of Layout::array::<T>(capacity) in order to deallocate the backing memory. If this is done, be careful not to run the destructor of the Vec, as dropping it will result in double-frees. Wrapping the Vec in a ManuallyDrop is the typical way to achieve this.

§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);
}

Deallocating a vector using Box (which uses dealloc internally):

use std::mem::{ManuallyDrop, MaybeUninit};

let mut v = ManuallyDrop::new(vec![0, 1, 2]);
let ptr = v.as_mut_ptr();
let capacity = v.capacity();
let slice_ptr: *mut [MaybeUninit<i32>] =
    std::ptr::slice_from_raw_parts_mut(ptr.cast(), capacity);
drop(unsafe { Box::from_raw(slice_ptr) });
Examples found in repository?
examples/ecs/dynamic.rs (line 303)
299fn to_owning_ptrs(components: &mut [Vec<u64>]) -> Vec<OwningPtr<'_, Aligned>> {
300    components
301        .iter_mut()
302        .map(|data| {
303            let ptr = data.as_mut_ptr();
304            // SAFETY:
305            // - Pointers are guaranteed to be non-null
306            // - Memory pointed to won't be dropped until `components` is dropped
307            unsafe {
308                let non_null = NonNull::new_unchecked(ptr.cast());
309                OwningPtr::new(non_null)
310            }
311        })
312        .collect()
313}
Source

pub fn as_non_null(&mut self) -> NonNull<T>

🔬This is a nightly-only experimental API. (vec_as_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(vec_as_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(vec_as_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);
}
1.100.0 · Source

pub fn allocator(&self) -> &A

Returns a reference to the underlying allocator.

1.0.0 · Source

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 to capacity().
  • 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 · Source

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"]);
Examples found in repository?
examples/stress_tests/many_morph_targets.rs (line 300)
298fn take_random<T>(rng: &mut ChaCha8Rng, from: &mut Vec<T>, count: usize) -> Vec<T> {
299    (0..count)
300        .map(|_| from.swap_remove(rng.random_range(..from.len())))
301        .collect()
302}
1.0.0 · Source

pub fn insert(&mut self, index: usize, element: T)

Available on non-no_global_oom_handling only.

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.95.0 · Source

pub fn insert_mut(&mut self, index: usize, element: T) -> &mut T

Available on non-no_global_oom_handling only.

Inserts an element at position index within the vector, shifting all elements after it to the right, and returning a reference to the new element.

§Panics

Panics if index > len.

§Examples
let mut vec = vec![1, 3, 5, 9];
let x = vec.insert_mut(3, 6);
*x += 1;
assert_eq!(vec, [1, 3, 5, 7, 9]);
§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 · Source

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.101.0 · Source

pub fn try_remove(&mut self, index: usize) -> Option<T>

Remove and return the element at position index within the vector, shifting all elements after it to the left, or None if it does not exist.

Note: Because this shifts over the remaining elements, it has a worst-case performance of O(n). If you’d like to remove elements from the beginning of the Vec, consider using VecDeque::pop_front instead.

§Examples
let mut v = vec![1, 2, 3];
assert_eq!(v.try_remove(0), Some(1));
assert_eq!(v.try_remove(2), None);
1.0.0 · Source

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

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?
examples/showcase/loading_screen.rs (lines 208-212)
197fn update_loading_data(
198    mut loading_data: ResMut<LoadingData>,
199    mut loading_state: ResMut<LoadingState>,
200    asset_server: Res<AssetServer>,
201    pipelines_ready: Res<PipelinesReady>,
202) {
203    if !loading_data.loading_assets.is_empty() || !pipelines_ready.0 {
204        // If we are still loading assets / pipelines are not fully compiled,
205        // we reset the confirmation frame count.
206        loading_data.confirmation_frames_count = 0;
207
208        loading_data.loading_assets.retain(|asset| {
209            asset_server
210                .get_recursive_dependency_load_state(asset)
211                .is_none_or(|state| !state.is_loaded())
212        });
213
214        // If there are no more assets being monitored, and pipelines
215        // are compiled, then start counting confirmation frames.
216        // Once enough confirmations have passed, everything will be
217        // considered to be fully loaded.
218    } else {
219        loading_data.confirmation_frames_count += 1;
220        if loading_data.confirmation_frames_count == loading_data.confirmation_frames_target {
221            *loading_state = LoadingState::LevelReady;
222        }
223    }
224}
1.61.0 · Source

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

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 · Source

pub fn dedup_by_key<F, K>(&mut self, key: F)
where F: FnMut(&mut T) -> K, K: PartialEq,

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 · Source

pub fn dedup_by<F>(&mut self, same_bucket: F)
where F: FnMut(&mut T, &mut T) -> bool,

Removes all but the first of consecutive elements in the vector that are “equal” according to the given predicate function.

The predicate same_bucket(x, p) is passed references to two elements. If it returns true, the element x is removed from the vector.

The element p occurs before x in the vector ([.., p, .., x, ..]), so same_bucket(x, p) is receiving them in reversed order (unlike windows).

If the vector is sorted, this removes all duplicates. For more complicated predicates however, the order (ascending vs. descending) can matter.

§Examples
let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
vec.dedup_by(|x, p| x.eq_ignore_ascii_case(p));
assert_eq!(vec, ["foo", "bar", "baz", "bar"]);

Both references passed to same_bucket are mutable. This allows merging elements by mutating p and returning true:

let mut ranges = vec![1..2, 2..4, 2..5, 8..9];

// Sort ranges by start, and if equal, by end (lexicographically)
// Sorting in reverse instead (`x.start.cmp(&p.start)...`) would later fail
ranges.sort_unstable_by(|p, x| p.start.cmp(&x.start).then(p.end.cmp(&x.end)));

// Merge touching (`1..2` and `2..4`) and then overlapping (`1..4` and `2..5`) ranges
ranges.dedup_by(|x, p| {
    if p.end >= x.start {
        p.end = p.end.max(x.end);
        true
    } else {
        false
    }
});

assert_eq!(ranges, [1..5, 8..9]);
Source

pub fn push_within_capacity(&mut self, value: T) -> Result<&mut T, T>

🔬This is a nightly-only experimental API. (vec_push_within_capacity)

Appends an element and returns a reference to it 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 · Source

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?
examples/showcase/mines.rs (line 91)
89    fn reveal(&mut self, target: IVec2) {
90        let mut open = vec![target];
91        while let Some(current) = open.pop() {
92            if !self[current].revealed {
93                self[current].revealed = true;
94                if self.count_adjacent_mines(current) == 0 {
95                    open.extend(self.get_adjacent(current));
96                }
97            }
98        }
99    }
More examples
Hide additional examples
examples/math/cubic_splines.rs (line 418)
393fn handle_keypress(
394    keyboard: Res<ButtonInput<KeyCode>>,
395    mut spline_mode: ResMut<SplineMode>,
396    mut cycling_mode: ResMut<CyclingMode>,
397    mut control_points: ResMut<ControlPoints>,
398) {
399    // S => change spline mode
400    if keyboard.just_pressed(KeyCode::KeyS) {
401        *spline_mode = match *spline_mode {
402            SplineMode::Hermite => SplineMode::Cardinal,
403            SplineMode::Cardinal => SplineMode::B,
404            SplineMode::B => SplineMode::Hermite,
405        }
406    }
407
408    // C => change cycling mode
409    if keyboard.just_pressed(KeyCode::KeyC) {
410        *cycling_mode = match *cycling_mode {
411            CyclingMode::NotCyclic => CyclingMode::Cyclic,
412            CyclingMode::Cyclic => CyclingMode::NotCyclic,
413        }
414    }
415
416    // R => remove last control point
417    if keyboard.just_pressed(KeyCode::KeyR) {
418        control_points.points_and_tangents.pop();
419    }
420}
examples/stress_tests/many_morph_targets.rs (line 324)
304fn update(
305    args: Res<Args>,
306    mut commands: Commands,
307    mut state: ResMut<State>,
308    mut rng: ResMut<Rng>,
309    assets: Res<MorphAssets>,
310) {
311    state.ticks += 1;
312
313    if state.spawned.is_empty() {
314        state.cycle = CycleState::Spawn;
315    } else if state.despawned.is_empty() {
316        state.cycle = CycleState::Despawn;
317    }
318
319    let mut to_spawn = Vec::<usize>::default();
320    let mut to_despawn = Vec::<(usize, Entity)>::default();
321
322    match args.spawning {
323        ArgSpawning::Instant => to_spawn = std::mem::take(&mut state.despawned),
324        ArgSpawning::Gradual => to_spawn = state.despawned.pop().into_iter().collect(),
325        ArgSpawning::RegularCycle => match state.cycle {
326            CycleState::Spawn => to_spawn.push(state.despawned.pop().unwrap()),
327            CycleState::Despawn => to_despawn.push(state.spawned.pop().unwrap()),
328        },
329        ArgSpawning::RandomCycle => match state.cycle {
330            CycleState::Spawn => to_spawn = take_random(&mut rng.0, &mut state.despawned, 1),
331            CycleState::Despawn => to_despawn = take_random(&mut rng.0, &mut state.spawned, 1),
332        },
333        ArgSpawning::RandomSteady => {
334            if state.spawned.is_empty() {
335                let spawn_count = state.slot_count / 2;
336                to_spawn = take_random(&mut rng.0, &mut state.despawned, spawn_count);
337            } else {
338                to_spawn = take_random(&mut rng.0, &mut state.despawned, 1);
339                to_despawn = take_random(&mut rng.0, &mut state.spawned, 1);
340            }
341        }
342    }
343
344    for (mesh_index, entity) in to_despawn {
345        commands.entity(entity).despawn();
346        state.despawned.push(mesh_index);
347    }
348
349    for mesh_index in to_spawn {
350        // Arrange the meshes in a grid.
351
352        let (x_dim, y_dim) = dims(state.slot_count);
353
354        let x = 2.5 + (5.0 * ((mesh_index.rem_euclid(x_dim) as f32) - ((x_dim as f32) * 0.5)));
355        let y = -2.2 - (3.0 * ((mesh_index.div_euclid(x_dim) as f32) - ((y_dim as f32) * 0.5)));
356
357        // Vary the animation speed so that the number of morph targets
358        // active on each frame is more likely to be stable.
359
360        let speed = ((mesh_index as f32) * 0.1).rem_euclid(1.0) + 0.5;
361
362        let animation_asset =
363            assets.animations[mesh_index.rem_euclid(assets.animations.len())].clone();
364        let animation = AnimationToPlay {
365            graph_handle: animation_asset.0.clone(),
366            index: animation_asset.1,
367            speed,
368        };
369
370        let entity = commands
371            .spawn((
372                animation,
373                Transform::from_xyz(x, y, 0.0),
374                WorldAssetRoot(assets.scene.clone()),
375            ))
376            .observe(play_animation)
377            .observe(set_weights)
378            .id();
379
380        state.spawned.push((mesh_index, entity));
381    }
382}
1.86.0 · Source

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);
Source

pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T, A>>

🔬This is a nightly-only experimental API. (vec_peek_mut)

Returns a mutable reference to the last item in the vector, or None if it is empty.

§Examples

Basic usage:

#![feature(vec_peek_mut)]
let mut vec = Vec::new();
assert!(vec.peek_mut().is_none());

vec.push(1);
vec.push(5);
vec.push(2);
assert_eq!(vec.last(), Some(&2));
if let Some(mut val) = vec.peek_mut() {
    *val = 0;
}
assert_eq!(vec.last(), Some(&0));
1.4.0 · Source

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

Available on non-no_global_oom_handling only.

Moves all the elements of other into self, leaving other empty.

§Panics

Panics if the new capacity exceeds isize::MAX bytes.

§Examples
let mut vec = vec![1, 2, 3];
let mut vec2 = vec![4, 5, 6];
vec.append(&mut vec2);
assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
assert_eq!(vec2, []);
1.6.0 · Source

pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A> ⓘ

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 range has start_bound > end_bound, or, if the range is bounded on either end and past 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?
examples/showcase/stepping.rs (line 166)
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<(
108        bevy_ecs::intern::Interned<dyn ScheduleLabel + 'static>,
109        NodeId,
110    )> = Vec::new();
111
112    let Ok(schedule_order) = stepping.schedules() else {
113        return;
114    };
115
116    // go through the stepping schedules and construct a list of systems for
117    // each label
118    for label in schedule_order {
119        let schedule = schedules.get(*label).unwrap();
120        text_spans.push((
121            TextSpan(format!("{label:?}\n")),
122            TextFont {
123                font: asset_server.load(FONT_BOLD).into(),
124                ..default()
125            },
126            TextColor(FONT_COLOR),
127        ));
128
129        // grab the list of systems in the schedule, in the order the
130        // single-threaded executor would run them.
131        let Ok(systems) = schedule.systems() else {
132            return;
133        };
134
135        for (key, system) in systems {
136            // skip bevy default systems; we don't want to step those
137            #[cfg(feature = "debug")]
138            if system.name().as_string().starts_with("bevy") {
139                always_run.push((*label, NodeId::System(key)));
140                continue;
141            }
142
143            // Add an entry to our systems list so we can find where to draw
144            // the cursor when the stepping cursor is at this system
145            // we add plus 1 to account for the empty root span
146            state
147                .systems
148                .push((*label, NodeId::System(key), text_spans.len() + 1));
149
150            // Add a text section for displaying the cursor for this system
151            text_spans.push((
152                TextSpan::new("   "),
153                TextFont::default(),
154                TextColor(FONT_COLOR),
155            ));
156
157            // add the name of the system to the ui
158            text_spans.push((
159                TextSpan(format!("{}\n", system.name())),
160                TextFont::default(),
161                TextColor(FONT_COLOR),
162            ));
163        }
164    }
165
166    for (label, node) in always_run.drain(..) {
167        stepping.always_run_node(label, node);
168    }
169
170    commands.spawn((
171        Text::default(),
172        SteppingUi,
173        Node {
174            position_type: PositionType::Absolute,
175            top: state.ui_top,
176            left: state.ui_left,
177            padding: UiRect::all(px(10)),
178            ..default()
179        },
180        BackgroundColor(Color::srgba(1.0, 1.0, 1.0, 0.33)),
181        Visibility::Hidden,
182        Children::spawn(text_spans),
183    ));
184}
1.0.0 · Source

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());
Examples found in repository?
examples/picking/custom_hit_data.rs (line 161)
157fn cache_hovered_triangles(
158    mut pointer_hits: MessageReader<PointerHits>,
159    mut hovered_triangles: ResMut<HoveredTriangles>,
160) {
161    hovered_triangles.0.clear();
162
163    for hits in pointer_hits.read() {
164        for (_, hit) in &hits.picks {
165            let (Some(position), Some(normal)) = (hit.position, hit.normal) else {
166                continue;
167            };
168
169            let Some(info) = hit.extra_as::<TriangleHitInfo>() else {
170                continue;
171            };
172            let Some(vertices) = info.triangle_vertices else {
173                continue;
174            };
175
176            hovered_triangles.0.push(TriangleOverlay {
177                position,
178                normal,
179                vertices,
180            });
181        }
182    }
183}
More examples
Hide additional examples
examples/shader_advanced/manual_material.rs (line 292)
274fn check_entities_needing_specialization(
275    needs_specialization: Query<
276        Entity,
277        (
278            Or<(
279                Changed<Mesh3d>,
280                AssetChanged<Mesh3d>,
281                Changed<ImageMaterial3d>,
282                AssetChanged<ImageMaterial3d>,
283            )>,
284            With<ImageMaterial3d>,
285        ),
286    >,
287    mut par_local: Local<Parallel<Vec<Entity>>>,
288    mut entities_needing_specialization: ResMut<EntitiesNeedingSpecialization<ImageMaterial>>,
289    mut removed_mesh_3d_components: RemovedComponents<Mesh3d>,
290    mut removed_mesh_material_3d_components: RemovedComponents<ImageMaterial3d>,
291) {
292    entities_needing_specialization.changed.clear();
293    entities_needing_specialization.removed.clear();
294
295    // Gather all entities that need their specializations regenerated.
296    needs_specialization
297        .par_iter()
298        .for_each(|entity| par_local.borrow_local_mut().push(entity));
299    par_local.drain_into(&mut entities_needing_specialization.changed);
300
301    // All entities that removed their `Mesh3d` or `ImageMaterial3d` components
302    // need to have their specializations removed as well.
303    for entity in removed_mesh_3d_components
304        .read()
305        .chain(removed_mesh_material_3d_components.read())
306    {
307        entities_needing_specialization.removed.push(entity);
308    }
309}
examples/usage/character_creation.rs (line 703)
638fn refresh_character(
639    mut commands: Commands,
640    character_view_q: Single<(Entity, &Children), With<CharacterView>>,
641    view_type_q: Query<(
642        Entity,
643        Has<CharacterSprite>,
644        Has<CharacterHat>,
645        Has<CharacterNameAndAge>,
646    )>,
647    mut character: ResMut<Character>,
648) {
649    let (character_view, children) = character_view_q.into_inner();
650    let (mut already_updated_name_age, mut already_updated_sprite, mut already_updated_hat) =
651        (false, false, false);
652    for changed_field in character.changed_fields.iter().copied() {
653        // First, find the correct child to despawn
654        // Then, add an updated child.
655        match changed_field {
656            ChangedField::Name | ChangedField::Age if !already_updated_name_age => {
657                for (child, _, _, is_name_and_age) in children
658                    .iter()
659                    .filter_map(|child| view_type_q.get(child).ok())
660                {
661                    if is_name_and_age {
662                        commands.entity(child).try_despawn();
663                    }
664                }
665                let new_child = commands
666                    .spawn_scene(character_name_and_age(&character))
667                    .id();
668                commands.entity(character_view).add_child(new_child);
669
670                already_updated_name_age = true;
671            }
672            ChangedField::TintYellow if !already_updated_sprite => {
673                for (child, is_sprite, _, _) in children
674                    .iter()
675                    .filter_map(|child| view_type_q.get(child).ok())
676                {
677                    if is_sprite {
678                        commands.entity(child).try_despawn();
679                    }
680                }
681                let new_child = commands.spawn_scene(character_sprite(&character)).id();
682                commands.entity(character_view).add_child(new_child);
683
684                already_updated_sprite = true;
685            }
686            ChangedField::HatType if !already_updated_hat => {
687                for (child, _, is_hat, _) in children
688                    .iter()
689                    .filter_map(|child| view_type_q.get(child).ok())
690                {
691                    if is_hat {
692                        commands.entity(child).try_despawn();
693                    }
694                }
695                let new_child = commands.spawn_scene(character_hat(&character)).id();
696                commands.entity(character_view).add_child(new_child);
697
698                already_updated_hat = true;
699            }
700            _ => {}
701        }
702    }
703    character.changed_fields.clear();
704}
examples/ui/navigation/directional_navigation_overrides.rs (line 298)
168fn setup_paged_ui(
169    mut commands: Commands,
170    mut manual_directional_nav_map: ResMut<DirectionalNavigationMap>,
171) {
172    commands.spawn(Camera2d);
173
174    // Create a full-screen background node
175    commands.spawn_scene(bsn! {
176        Node {
177            width: percent(100),
178            height: percent(100),
179        }
180        Children [
181            @instructions_scene()
182            --
183            @focus_display_scene()
184            --
185            @key_display_scene()
186        ]
187    });
188
189    // Setup the pages with buttons and helper text
190    let pages_entities = [0, 1, 2]
191        .into_iter()
192        .map(|page_num| {
193            let button_entities = if page_num == 1 {
194                // the second page
195                setup_buttons_for_triangle_page(&mut commands, page_num)
196            } else {
197                // the first and third pages are regular grids
198                setup_buttons_for_grid_page(&mut commands, page_num)
199            };
200
201            // Only the first page is visible at setup.
202            let visibility = if page_num == 0 {
203                Visibility::Inherited
204            } else {
205                Visibility::Hidden
206            };
207
208            // Each page is its own separate root UI node with its own visibility.
209            let page_id = if page_num == 1 {
210                commands
211                    .spawn_scene(bsn! {
212                        Node {
213                            width: percent(100),
214                            height: percent(100),
215                        }
216                        visibility
217                        Children [
218                            { triangle_page_text_entities_scene_list(page_num) }
219                        ]
220                    })
221                    .id()
222            } else {
223                commands
224                    .spawn_scene(bsn! {
225                        Node {
226                            width: percent(100),
227                            height: percent(100),
228                        }
229                        visibility
230                        Children [
231                            { grid_page_text_entities_scene_list(page_num) }
232                        ]
233                    })
234                    .id()
235            };
236
237            commands.entity(page_id).add_children(&button_entities);
238
239            button_entities
240        })
241        .collect::<Vec<_>>();
242
243    // For Pages 1 and 3, add manual edges within the grid page for navigation between rows.
244    let entity_pairs = [
245        // the end of the first row should connect to the beginning of the second
246        ((0, 2), (1, 0)),
247        // the end of the second row should connect to the beginning of the third
248        ((1, 2), (2, 0)),
249        // the end of the third row should connect to the beginning of the fourth
250        ((2, 2), (3, 0)),
251    ];
252    for (page_num, page_entities) in pages_entities.iter().enumerate() {
253        // Skip Page 2; we are only adding these manual edges for the grid pages.
254        if page_num == 1 {
255            continue;
256        }
257        for ((entity_a_row, entity_a_col), (entity_b_row, entity_b_col)) in entity_pairs.iter() {
258            manual_directional_nav_map.add_symmetrical_edge(
259                page_entities[entity_a_row * 3 + entity_a_col],
260                page_entities[entity_b_row * 3 + entity_b_col],
261                CompassOctant::East,
262            );
263        }
264    }
265
266    // Add manual edges within the triangle page (Page 2) between buttons 3 and 4.
267    // The `AutoNavigationConfig` is set to our desired values, but automatic
268    // navigation does not connect Button 3 to Button 4, so we have to add
269    // this navigation manually.
270    manual_directional_nav_map.add_symmetrical_edge(
271        pages_entities[1][2],
272        pages_entities[1][3],
273        CompassOctant::East,
274    );
275    manual_directional_nav_map.add_symmetrical_edge(
276        pages_entities[1][2],
277        pages_entities[1][3],
278        CompassOctant::South,
279    );
280    manual_directional_nav_map.add_symmetrical_edge(
281        pages_entities[1][2],
282        pages_entities[1][3],
283        CompassOctant::SouthEast,
284    );
285    // Add one-way blocking within the first grid page (Page 1) for down nav.
286    for btn in &pages_entities[0] {
287        manual_directional_nav_map.block_edge(*btn, CompassOctant::South);
288        manual_directional_nav_map.block_edge(*btn, CompassOctant::North);
289    }
290
291    // For Page 3, we override the navigation North and South to be inverted.
292    let mut col_entities = Vec::with_capacity(4);
293    for col in 0..=2 {
294        for row in 0..=3 {
295            col_entities.push(pages_entities[2][row * 3 + col]);
296        }
297        manual_directional_nav_map.add_looping_edges(&col_entities, CompassOctant::North);
298        col_entities.clear();
299    }
300
301    // Add manual edges between pages.
302    // When navigating east (right) from the last button of page 1,
303    // go to the first button of page 2. This edge is symmetrical.
304    manual_directional_nav_map.add_symmetrical_edge(
305        pages_entities[0][11],
306        pages_entities[1][0],
307        CompassOctant::East,
308    );
309    // When navigating south (down) from the last button of page 2,
310    // go to the first button of page 3. This edge is NOT symmetrical.
311    // This means going north (up) from the first button of page 3 does
312    // NOT go to the last button of page 2.
313    manual_directional_nav_map.add_edge(
314        pages_entities[1][3],
315        pages_entities[2][0],
316        CompassOctant::South,
317    );
318    // When navigating west (left) from the first button of page 3,
319    // go back to the last button of page 2. This edge is NOT symmetrical.
320    manual_directional_nav_map.add_edge(
321        pages_entities[2][0],
322        pages_entities[1][3],
323        CompassOctant::West,
324    );
325    // When navigating east (right) from the last button of page 1,
326    // go to the first button of page 2. This edge is symmetrical.
327    manual_directional_nav_map.add_symmetrical_edge(
328        pages_entities[2][11],
329        pages_entities[0][0],
330        CompassOctant::East,
331    );
332
333    // Set initial focus
334    commands.entity(pages_entities[0][0]).insert(AutoFocus);
335}
1.0.0 · Source

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?
examples/stress_tests/many_morph_targets.rs (line 300)
298fn take_random<T>(rng: &mut ChaCha8Rng, from: &mut Vec<T>, count: usize) -> Vec<T> {
299    (0..count)
300        .map(|_| from.swap_remove(rng.random_range(..from.len())))
301        .collect()
302}
303
304fn update(
305    args: Res<Args>,
306    mut commands: Commands,
307    mut state: ResMut<State>,
308    mut rng: ResMut<Rng>,
309    assets: Res<MorphAssets>,
310) {
311    state.ticks += 1;
312
313    if state.spawned.is_empty() {
314        state.cycle = CycleState::Spawn;
315    } else if state.despawned.is_empty() {
316        state.cycle = CycleState::Despawn;
317    }
318
319    let mut to_spawn = Vec::<usize>::default();
320    let mut to_despawn = Vec::<(usize, Entity)>::default();
321
322    match args.spawning {
323        ArgSpawning::Instant => to_spawn = std::mem::take(&mut state.despawned),
324        ArgSpawning::Gradual => to_spawn = state.despawned.pop().into_iter().collect(),
325        ArgSpawning::RegularCycle => match state.cycle {
326            CycleState::Spawn => to_spawn.push(state.despawned.pop().unwrap()),
327            CycleState::Despawn => to_despawn.push(state.spawned.pop().unwrap()),
328        },
329        ArgSpawning::RandomCycle => match state.cycle {
330            CycleState::Spawn => to_spawn = take_random(&mut rng.0, &mut state.despawned, 1),
331            CycleState::Despawn => to_despawn = take_random(&mut rng.0, &mut state.spawned, 1),
332        },
333        ArgSpawning::RandomSteady => {
334            if state.spawned.is_empty() {
335                let spawn_count = state.slot_count / 2;
336                to_spawn = take_random(&mut rng.0, &mut state.despawned, spawn_count);
337            } else {
338                to_spawn = take_random(&mut rng.0, &mut state.despawned, 1);
339                to_despawn = take_random(&mut rng.0, &mut state.spawned, 1);
340            }
341        }
342    }
343
344    for (mesh_index, entity) in to_despawn {
345        commands.entity(entity).despawn();
346        state.despawned.push(mesh_index);
347    }
348
349    for mesh_index in to_spawn {
350        // Arrange the meshes in a grid.
351
352        let (x_dim, y_dim) = dims(state.slot_count);
353
354        let x = 2.5 + (5.0 * ((mesh_index.rem_euclid(x_dim) as f32) - ((x_dim as f32) * 0.5)));
355        let y = -2.2 - (3.0 * ((mesh_index.div_euclid(x_dim) as f32) - ((y_dim as f32) * 0.5)));
356
357        // Vary the animation speed so that the number of morph targets
358        // active on each frame is more likely to be stable.
359
360        let speed = ((mesh_index as f32) * 0.1).rem_euclid(1.0) + 0.5;
361
362        let animation_asset =
363            assets.animations[mesh_index.rem_euclid(assets.animations.len())].clone();
364        let animation = AnimationToPlay {
365            graph_handle: animation_asset.0.clone(),
366            index: animation_asset.1,
367            speed,
368        };
369
370        let entity = commands
371            .spawn((
372                animation,
373                Transform::from_xyz(x, y, 0.0),
374                WorldAssetRoot(assets.scene.clone()),
375            ))
376            .observe(play_animation)
377            .observe(set_weights)
378            .id();
379
380        state.spawned.push((mesh_index, entity));
381    }
382}
More examples
Hide additional examples
examples/2d/tilemap_chunk.rs (line 126)
116fn update_tilemap(
117    time: Res<Time>,
118    mut query: Query<(&mut TilemapChunkTileData, &mut UpdateTimer)>,
119    mut rng: ResMut<SeededRng>,
120) {
121    for (mut tile_data, mut timer) in query.iter_mut() {
122        timer.tick(time.delta());
123
124        if timer.just_finished() {
125            for _ in 0..50 {
126                let index = rng.random_range(0..tile_data.len());
127                tile_data[index] = Some(TileData::from_tileset_index(rng.random_range(0..5)));
128            }
129        }
130    }
131}
examples/ecs/dynamic.rs (line 367)
359fn parse_query<Q: QueryData>(
360    str: &str,
361    builder: &mut QueryBuilder<Q>,
362    components: &HashMap<String, ComponentId>,
363) {
364    let str = str.split(',');
365    str.for_each(|term| {
366        let sub_terms: Vec<_> = term.split("||").collect();
367        if sub_terms.len() == 1 {
368            parse_term(sub_terms[0], builder, components);
369        } else {
370            builder.or(|b| {
371                sub_terms
372                    .iter()
373                    .for_each(|term| parse_term(term, b, components));
374            });
375        }
376    });
377}
examples/stress_tests/many_animated_sprites.rs (line 120)
108fn animate_sprite(
109    time: Res<Time>,
110    texture_atlases: Res<Assets<TextureAtlasLayout>>,
111    mut query: Query<(&mut AnimationTimer, &mut Sprite)>,
112) {
113    for (mut timer, mut sprite) in query.iter_mut() {
114        timer.tick(time.delta());
115        if timer.just_finished() {
116            let Some(atlas) = &mut sprite.texture_atlas else {
117                continue;
118            };
119            let texture_atlas = texture_atlases.get(&atlas.layout).unwrap();
120            atlas.index = (atlas.index + 1) % texture_atlas.textures.len();
121        }
122    }
123}
examples/window/window_settings.rs (line 190)
183fn cycle_cursor_icon(
184    mut cursor: Single<&mut CursorIcon>,
185    input: Res<ButtonInput<MouseButton>>,
186    mut index: Local<usize>,
187    cursor_icons: Res<CursorIcons>,
188) {
189    if input.just_pressed(MouseButton::Left) {
190        *index = (*index + 1) % cursor_icons.0.len();
191        **cursor = cursor_icons.0[*index].clone();
192    } else if input.just_pressed(MouseButton::Right) {
193        *index = if *index == 0 {
194            cursor_icons.0.len() - 1
195        } else {
196            *index - 1
197        };
198        **cursor = cursor_icons.0[*index].clone();
199    }
200}
examples/shader_advanced/custom_shader_instancing.rs (line 227)
214fn prepare_instance_buffers(
215    mut commands: Commands,
216    query: Query<(Entity, &InstanceMaterialData)>,
217    render_device: Res<RenderDevice>,
218) {
219    for (entity, instance_data) in &query {
220        let buffer = render_device.create_buffer_with_data(&BufferInitDescriptor {
221            label: Some("instance data buffer"),
222            contents: bytemuck::cast_slice(instance_data.as_slice()),
223            usage: BufferUsages::VERTEX | BufferUsages::COPY_DST,
224        });
225        commands.entity(entity).insert(InstanceBuffer {
226            buffer,
227            length: instance_data.len(),
228        });
229    }
230}
1.0.0 · Source

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?
examples/showcase/stepping.rs (line 85)
84fn initialized(state: Res<State>) -> bool {
85    !state.systems.is_empty()
86}
More examples
Hide additional examples
examples/usage/character_creation.rs (line 46)
32fn main() {
33    App::new()
34        .add_plugins(DefaultPlugins)
35        .init_resource::<Character>()
36        .add_systems(Startup, setup)
37        .add_systems(
38            Update,
39            (
40                // Updates the Model if the user changed the name via text input.
41                // This is a Controller system, and is not an Observer because of
42                // the way the text input widget is designed.
43                on_changed_editable_text,
44                // Updates the View after any Model changes
45                refresh_character.run_if(resource_exists_and::<Character>(|character| {
46                    !character.changed_fields.is_empty()
47                })),
48            )
49                .chain(),
50        )
51        .run();
52}
examples/showcase/loading_screen.rs (line 203)
197fn update_loading_data(
198    mut loading_data: ResMut<LoadingData>,
199    mut loading_state: ResMut<LoadingState>,
200    asset_server: Res<AssetServer>,
201    pipelines_ready: Res<PipelinesReady>,
202) {
203    if !loading_data.loading_assets.is_empty() || !pipelines_ready.0 {
204        // If we are still loading assets / pipelines are not fully compiled,
205        // we reset the confirmation frame count.
206        loading_data.confirmation_frames_count = 0;
207
208        loading_data.loading_assets.retain(|asset| {
209            asset_server
210                .get_recursive_dependency_load_state(asset)
211                .is_none_or(|state| !state.is_loaded())
212        });
213
214        // If there are no more assets being monitored, and pipelines
215        // are compiled, then start counting confirmation frames.
216        // Once enough confirmations have passed, everything will be
217        // considered to be fully loaded.
218    } else {
219        loading_data.confirmation_frames_count += 1;
220        if loading_data.confirmation_frames_count == loading_data.confirmation_frames_target {
221            *loading_state = LoadingState::LevelReady;
222        }
223    }
224}
examples/picking/custom_hit_data.rs (line 151)
109fn custom_backend_system(
110    ray_map: Res<RayMap>,
111    cameras: Query<&Camera>,
112    pickables: Query<&Pickable>,
113    mut ray_cast: MeshRayCast,
114    mut pointer_hits: MessageWriter<PointerHits>,
115) {
116    for (&ray_id, &ray) in ray_map.iter() {
117        let Ok(camera) = cameras.get(ray_id.camera) else {
118            continue;
119        };
120
121        let settings = MeshRayCastSettings {
122            visibility: RayCastVisibility::VisibleInView,
123            filter: &|e| pickables.get(e).is_ok_and(|p| p.is_hoverable),
124            early_exit_test: &|entity_hit| {
125                pickables
126                    .get(entity_hit)
127                    .is_ok_and(|p| p.should_block_lower)
128            },
129        };
130
131        let picks: Vec<(Entity, HitData)> = ray_cast
132            .cast_ray(ray, &settings)
133            .iter()
134            .map(|(entity, hit)| {
135                let extra = TriangleHitInfo {
136                    triangle_vertices: hit.triangle,
137                };
138
139                let hit_data = HitData::new_with_extra(
140                    ray_id.camera,
141                    hit.distance,
142                    Some(hit.point),
143                    Some(hit.normal),
144                    extra,
145                );
146
147                (*entity, hit_data)
148            })
149            .collect();
150
151        if !picks.is_empty() {
152            pointer_hits.write(PointerHits::new(ray_id.pointer, picks, camera.order as f32));
153        }
154    }
155}
examples/stress_tests/many_morph_targets.rs (line 313)
304fn update(
305    args: Res<Args>,
306    mut commands: Commands,
307    mut state: ResMut<State>,
308    mut rng: ResMut<Rng>,
309    assets: Res<MorphAssets>,
310) {
311    state.ticks += 1;
312
313    if state.spawned.is_empty() {
314        state.cycle = CycleState::Spawn;
315    } else if state.despawned.is_empty() {
316        state.cycle = CycleState::Despawn;
317    }
318
319    let mut to_spawn = Vec::<usize>::default();
320    let mut to_despawn = Vec::<(usize, Entity)>::default();
321
322    match args.spawning {
323        ArgSpawning::Instant => to_spawn = std::mem::take(&mut state.despawned),
324        ArgSpawning::Gradual => to_spawn = state.despawned.pop().into_iter().collect(),
325        ArgSpawning::RegularCycle => match state.cycle {
326            CycleState::Spawn => to_spawn.push(state.despawned.pop().unwrap()),
327            CycleState::Despawn => to_despawn.push(state.spawned.pop().unwrap()),
328        },
329        ArgSpawning::RandomCycle => match state.cycle {
330            CycleState::Spawn => to_spawn = take_random(&mut rng.0, &mut state.despawned, 1),
331            CycleState::Despawn => to_despawn = take_random(&mut rng.0, &mut state.spawned, 1),
332        },
333        ArgSpawning::RandomSteady => {
334            if state.spawned.is_empty() {
335                let spawn_count = state.slot_count / 2;
336                to_spawn = take_random(&mut rng.0, &mut state.despawned, spawn_count);
337            } else {
338                to_spawn = take_random(&mut rng.0, &mut state.despawned, 1);
339                to_despawn = take_random(&mut rng.0, &mut state.spawned, 1);
340            }
341        }
342    }
343
344    for (mesh_index, entity) in to_despawn {
345        commands.entity(entity).despawn();
346        state.despawned.push(mesh_index);
347    }
348
349    for mesh_index in to_spawn {
350        // Arrange the meshes in a grid.
351
352        let (x_dim, y_dim) = dims(state.slot_count);
353
354        let x = 2.5 + (5.0 * ((mesh_index.rem_euclid(x_dim) as f32) - ((x_dim as f32) * 0.5)));
355        let y = -2.2 - (3.0 * ((mesh_index.div_euclid(x_dim) as f32) - ((y_dim as f32) * 0.5)));
356
357        // Vary the animation speed so that the number of morph targets
358        // active on each frame is more likely to be stable.
359
360        let speed = ((mesh_index as f32) * 0.1).rem_euclid(1.0) + 0.5;
361
362        let animation_asset =
363            assets.animations[mesh_index.rem_euclid(assets.animations.len())].clone();
364        let animation = AnimationToPlay {
365            graph_handle: animation_asset.0.clone(),
366            index: animation_asset.1,
367            speed,
368        };
369
370        let entity = commands
371            .spawn((
372                animation,
373                Transform::from_xyz(x, y, 0.0),
374                WorldAssetRoot(assets.scene.clone()),
375            ))
376            .observe(play_animation)
377            .observe(set_weights)
378            .id();
379
380        state.spawned.push((mesh_index, entity));
381    }
382}
examples/app/headless_renderer.rs (line 471)
453fn update(
454    images_to_save: Query<&ImageToSave>,
455    receiver: Res<MainWorldReceiver>,
456    mut images: ResMut<Assets<Image>>,
457    mut scene_controller: ResMut<SceneController>,
458    mut app_exit_writer: MessageWriter<AppExit>,
459    mut file_number: Local<u32>,
460) {
461    if let SceneState::Render(n) = scene_controller.state {
462        if n < 1 {
463            // We don't want to block the main world on this,
464            // so we use try_recv which attempts to receive without blocking
465            let mut image_data = Vec::new();
466            while let Ok(data) = receiver.try_recv() {
467                // image generation could be faster than saving to fs,
468                // that's why use only last of them
469                image_data = data;
470            }
471            if !image_data.is_empty() {
472                for image in images_to_save.iter() {
473                    // Fill correct data from channel to image
474                    let mut img_bytes = images.get_mut(image.id()).unwrap();
475
476                    // We need to ensure that this works regardless of the image dimensions
477                    // If the image became wider when copying from the texture to the buffer,
478                    // then the data is reduced to its original size when copying from the buffer to the image.
479                    let row_bytes = img_bytes.width() as usize
480                        * img_bytes.texture_descriptor.format.pixel_size().unwrap();
481                    let aligned_row_bytes = RenderDevice::align_copy_bytes_per_row(row_bytes);
482                    if row_bytes == aligned_row_bytes {
483                        img_bytes.data.as_mut().unwrap().clone_from(&image_data);
484                    } else {
485                        // shrink data to original image size
486                        img_bytes.data = Some(
487                            image_data
488                                .chunks(aligned_row_bytes)
489                                .take(img_bytes.height() as usize)
490                                .flat_map(|row| &row[..row_bytes.min(row.len())])
491                                .cloned()
492                                .collect(),
493                        );
494                    }
495
496                    // Create RGBA Image Buffer
497                    let img = match img_bytes.clone().try_into_dynamic() {
498                        Ok(img) => img.to_rgba8(),
499                        Err(e) => panic!("Failed to create image buffer {e:?}"),
500                    };
501
502                    // Prepare directory for images, test_images in bevy folder is used here for example
503                    // You should choose the path depending on your needs
504                    let images_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("test_images");
505                    info!("Saving image to: {images_dir:?}");
506                    std::fs::create_dir_all(&images_dir).unwrap();
507
508                    // Choose filename starting from 000.png
509                    let image_path = images_dir.join(format!("{:03}.png", file_number.deref()));
510                    *file_number.deref_mut() += 1;
511
512                    // Finally saving image to file, this heavy blocking operation is kept here
513                    // for example simplicity, but in real app you should move it to a separate task
514                    if let Err(e) = img.save(image_path) {
515                        panic!("Failed to save image: {e}");
516                    };
517                }
518                if scene_controller.single_image {
519                    app_exit_writer.write(AppExit::Success);
520                }
521            }
522        } else {
523            // clears channel for skipped frames
524            while receiver.try_recv().is_ok() {}
525            scene_controller.state = SceneState::Render(n - 1);
526        }
527    }
528}
1.4.0 · Source

pub fn split_off(&mut self, at: usize) -> Vec<T, A>
where A: Clone,

Available on non-no_global_oom_handling only.

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 or mem::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 · Source

pub fn resize_with<F>(&mut self, new_len: usize, f: F)
where F: FnMut() -> T,

Available on non-no_global_oom_handling only.

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 · Source

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]);
Source

pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>])

🔬This is a nightly-only experimental API. (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 · Source

pub fn resize(&mut self, new_len: usize, value: T)

Available on non-no_global_oom_handling only.

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?
examples/ecs/dynamic.rs (line 155)
69fn main() {
70    let mut world = World::new();
71    let mut lines = std::io::stdin().lines();
72    let mut component_names = HashMap::<String, ComponentId>::new();
73    let mut component_info = HashMap::<ComponentId, ComponentInfo>::new();
74    let mut event_names = HashMap::<String, EventKey>::new();
75
76    println!("{PROMPT}");
77    loop {
78        print!("\n> ");
79        let _ = std::io::stdout().flush();
80        let Some(Ok(line)) = lines.next() else {
81            return;
82        };
83
84        if line.is_empty() {
85            return;
86        };
87
88        let Some((first, rest)) = line.trim().split_once(|c: char| c.is_whitespace()) else {
89            match &line.chars().next() {
90                Some('c') => println!("{COMPONENT_PROMPT}"),
91                Some('s') => println!("{ENTITY_PROMPT}"),
92                Some('q') => println!("{QUERY_PROMPT}"),
93                Some('e') => println!("{EVENT_PROMPT}"),
94                Some('t') => println!("{EMIT_PROMPT}"),
95                _ => println!("{PROMPT}"),
96            }
97            continue;
98        };
99
100        match &first[0..1] {
101            "c" => {
102                rest.split(',').for_each(|component| {
103                    let mut component = component.split_whitespace();
104                    let Some(name) = component.next() else {
105                        return;
106                    };
107                    let size = match component.next().map(str::parse) {
108                        Some(Ok(size)) => size,
109                        _ => 0,
110                    };
111                    // Register our new component to the world with a layout specified by its size
112                    // SAFETY: [u64] is Send + Sync
113                    let id = world.register_component_with_descriptor(unsafe {
114                        ComponentDescriptor::new_with_layout(
115                            name.to_string(),
116                            StorageType::Table,
117                            Layout::array::<u64>(size).unwrap(),
118                            None,
119                            true,
120                            false,
121                            ComponentCloneBehavior::Default,
122                            None,
123                        )
124                    });
125                    let Some(info) = world.components().get_info(id) else {
126                        return;
127                    };
128                    component_names.insert(name.to_string(), id);
129                    component_info.insert(id, info.clone());
130                    println!("Component {} created with id: {}", name, id.index());
131                });
132            }
133            "s" => {
134                let mut to_insert_ids = Vec::new();
135                let mut to_insert_data = Vec::new();
136                rest.split(',').for_each(|component| {
137                    let mut component = component.split_whitespace();
138                    let Some(name) = component.next() else {
139                        return;
140                    };
141
142                    // Get the id for the component with the given name
143                    let Some(&id) = component_names.get(name) else {
144                        println!("Component {name} does not exist");
145                        return;
146                    };
147
148                    // Calculate the length for the array based on the layout created for this component id
149                    let info = world.components().get_info(id).unwrap();
150                    let len = info.layout().size() / size_of::<u64>();
151                    let mut values: Vec<u64> = component
152                        .take(len)
153                        .filter_map(|value| value.parse::<u64>().ok())
154                        .collect();
155                    values.resize(len, 0);
156
157                    // Collect the id and array to be inserted onto our entity
158                    to_insert_ids.push(id);
159                    to_insert_data.push(values);
160                });
161
162                let mut entity = world.spawn_empty();
163
164                // Construct an `OwningPtr` for each component in `to_insert_data`
165                let to_insert_ptr = to_owning_ptrs(&mut to_insert_data);
166
167                // SAFETY:
168                // - Component ids have been taken from the same world
169                // - Each array is created to the layout specified in the world
170                unsafe {
171                    entity.insert_by_ids(&to_insert_ids, to_insert_ptr.into_iter());
172                }
173
174                println!("Entity spawned with id: {}", entity.id());
175            }
176            "q" => {
177                let mut builder = QueryBuilder::<FilteredEntityMut>::new(&mut world);
178                parse_query(rest, &mut builder, &component_names);
179                let mut query = builder.build();
180                query.iter_mut(&mut world).for_each(|filtered_entity| {
181                    let terms = filtered_entity
182                        .access()
183                        .try_iter_access()
184                        .unwrap()
185                        .map(|component_access| {
186                            let id = *component_access.index();
187                            let ptr = filtered_entity.get_by_id(id).unwrap();
188                            let info = component_info.get(&id).unwrap();
189                            let len = info.layout().size() / size_of::<u64>();
190
191                            // SAFETY:
192                            // - All components are created with layout [u64]
193                            // - len is calculated from the component descriptor
194                            let data = unsafe {
195                                std::slice::from_raw_parts_mut(
196                                    ptr.assert_unique().as_ptr().cast::<u64>(),
197                                    len,
198                                )
199                            };
200
201                            // If we have write access, increment each value once
202                            if matches!(component_access, ComponentAccessKind::Exclusive(_)) {
203                                data.iter_mut().for_each(|data| {
204                                    *data += 1;
205                                });
206                            }
207
208                            format!("{}: {:?}", info.name(), data[0..len].to_vec())
209                        })
210                        .collect::<Vec<_>>()
211                        .join(", ");
212
213                    println!("{}: {}", filtered_entity.id(), terms);
214                });
215            }
216            "e" => {
217                rest.split(',').for_each(|event| {
218                    let name = event.trim();
219                    if name.is_empty() {
220                        return;
221                    }
222
223                    // Register a ComponentId for this event, no Rust type needed.
224                    // SAFETY: ZST with no drop
225                    let event_component_id = world.register_component_with_descriptor(unsafe {
226                        ComponentDescriptor::new_with_layout(
227                            format!("event:{name}"),
228                            StorageType::Table,
229                            Layout::new::<()>(),
230                            None,
231                            false,
232                            false,
233                            ComponentCloneBehavior::Ignore,
234                            None,
235                        )
236                    });
237                    // SAFETY: event_component_id was just registered for this event
238                    let event_key = unsafe { EventKey::new(event_component_id) };
239                    event_names.insert(name.to_string(), event_key);
240
241                    // Build a dynamic observer that prints when the event fires.
242                    let runner: ObserverRunner = |mut world, _observer, ctx, _event, _trigger| {
243                        println!("  Observer fired!");
244                        if let Some(mut counts) = world.get_resource_mut::<EventFireCount>() {
245                            *counts.0.entry(ctx.event_key).or_insert(0) += 1;
246                        }
247                    };
248
249                    // SAFETY: event_key was just registered, runner ignores pointers
250                    let observer =
251                        unsafe { Observer::with_dynamic_runner(runner).with_event_key(event_key) };
252                    world.spawn(observer);
253
254                    println!(
255                        "Event '{name}' registered (key: {}) with a dynamic observer",
256                        event_component_id.index()
257                    );
258                });
259
260                // Ensure the counter resource exists.
261                world.init_resource::<EventFireCount>();
262            }
263            "t" => {
264                let name = rest.trim();
265                let Some(&event_key) = event_names.get(name) else {
266                    println!(
267                        "Event '{name}' does not exist. Register it first with 'event {name}'"
268                    );
269                    continue;
270                };
271
272                let mut event_data = ();
273                let mut trigger_data = ();
274                // SAFETY: event_key was registered in this world, both pointers are valid ZSTs
275                unsafe {
276                    world.trigger_dynamic(
277                        event_key,
278                        PtrMut::from(&mut event_data),
279                        PtrMut::from(&mut trigger_data),
280                    );
281                }
282
283                let count = world
284                    .get_resource::<EventFireCount>()
285                    .map_or(0, |c| c.0.get(&event_key).copied().unwrap_or(0));
286                println!("Event '{name}' triggered ({count} fires)");
287            }
288            _ => continue,
289        }
290    }
291}
1.6.0 · Source

pub fn extend_from_slice(&mut self, other: &[T])

Available on non-no_global_oom_handling only.

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.

§Panics

Panics if the new capacity exceeds isize::MAX bytes.

§Examples
let mut vec = vec![1];
vec.extend_from_slice(&[2, 3, 4]);
assert_eq!(vec, [1, 2, 3, 4]);
Examples found in repository?
examples/math/custom_primitives.rs (line 548)
509    fn build(&self) -> Mesh {
510        let radius = self.heart.radius;
511        // The curved parts of each wing (half) of the heart have an angle of `PI * 1.25` or 225°
512        let wing_angle = PI * 1.25;
513
514        // We create buffers for the vertices, their normals and UVs, as well as the indices used to connect the vertices.
515        let mut vertices = Vec::with_capacity(2 * self.resolution);
516        let mut uvs = Vec::with_capacity(2 * self.resolution);
517        let mut indices = Vec::with_capacity(6 * self.resolution - 9);
518        // Since the heart is flat, we know all the normals are identical already.
519        let normals = vec![[0f32, 0f32, 1f32]; 2 * self.resolution];
520
521        // The point in the middle of the two curved parts of the heart
522        vertices.push([0.0; 3]);
523        uvs.push([0.5, 0.5]);
524
525        // The left wing of the heart, starting from the point in the middle.
526        for i in 1..self.resolution {
527            let angle = (i as f32 / self.resolution as f32) * wing_angle;
528            let (sin, cos) = ops::sin_cos(angle);
529            vertices.push([radius * (cos - 1.0), radius * sin, 0.0]);
530            uvs.push([0.5 - (cos - 1.0) / 4., 0.5 - sin / 2.]);
531        }
532
533        // The bottom tip of the heart
534        vertices.push([0.0, radius * (-1. - SQRT_2), 0.0]);
535        uvs.push([0.5, 1.]);
536
537        // The right wing of the heart, starting from the bottom most point and going towards the middle point.
538        for i in 0..self.resolution - 1 {
539            let angle = (i as f32 / self.resolution as f32) * wing_angle - PI / 4.;
540            let (sin, cos) = ops::sin_cos(angle);
541            vertices.push([radius * (cos + 1.0), radius * sin, 0.0]);
542            uvs.push([0.5 - (cos + 1.0) / 4., 0.5 - sin / 2.]);
543        }
544
545        // This is where we build all the triangles from the points created above.
546        // Each triangle has one corner on the middle point with the other two being adjacent points on the perimeter of the heart.
547        for i in 2..2 * self.resolution as u32 {
548            indices.extend_from_slice(&[i - 1, i, 0]);
549        }
550
551        // Here, the actual `Mesh` is created. We set the indices, vertices, normals and UVs created above and specify the topology of the mesh.
552        Mesh::new(
553            bevy::mesh::PrimitiveTopology::TriangleList,
554            RenderAssetUsages::default(),
555        )
556        .with_inserted_indices(bevy::mesh::Indices::U32(indices))
557        .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, vertices)
558        .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
559        .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs)
560    }
More examples
Hide additional examples
examples/2d/mesh2d_manual.rs (line 109)
66fn star(
67    mut commands: Commands,
68    // We will add a new Mesh for the star being created
69    mut meshes: ResMut<Assets<Mesh>>,
70) {
71    // Let's define the mesh for the object we want to draw: a nice star.
72    // We will specify here what kind of topology is used to define the mesh,
73    // that is, how triangles are built from the vertices. We will use a
74    // triangle list, meaning that each vertex of the triangle has to be
75    // specified. We set `RenderAssetUsages::RENDER_WORLD`, meaning this mesh
76    // will not be accessible in future frames from the `meshes` resource, in
77    // order to save on memory once it has been uploaded to the GPU.
78    let mut star = Mesh::new(
79        PrimitiveTopology::TriangleList,
80        RenderAssetUsages::RENDER_WORLD,
81    );
82
83    // Vertices need to have a position attribute. We will use the following
84    // vertices (I hope you can spot the star in the schema).
85    //
86    //        1
87    //
88    //     10   2
89    // 9      0      3
90    //     8     4
91    //        6
92    //   7        5
93    //
94    // These vertices are specified in 3D space.
95    let mut v_pos = vec![[0.0, 0.0, 0.0]];
96    for i in 0..10 {
97        // The angle between each vertex is 1/10 of a full rotation.
98        let a = i as f32 * PI / 5.0;
99        // The radius of inner vertices (even indices) is 100. For outer vertices (odd indices) it's 200.
100        let r = (1 - i % 2) as f32 * 100.0 + 100.0;
101        // Add the vertex position.
102        v_pos.push([r * ops::sin(a), r * ops::cos(a), 0.0]);
103    }
104    // Set the position attribute
105    star.insert_attribute(Mesh::ATTRIBUTE_POSITION, v_pos);
106    // And a RGB color attribute as well. A built-in `Mesh::ATTRIBUTE_COLOR` exists, but we
107    // use a custom vertex attribute here for demonstration purposes.
108    let mut v_color: Vec<u32> = vec![LinearRgba::BLACK.as_u32()];
109    v_color.extend_from_slice(&[LinearRgba::from(YELLOW).as_u32(); 10]);
110    star.insert_attribute(
111        MeshVertexAttribute::new("Vertex_Color", 1, VertexFormat::Uint32),
112        v_color,
113    );
114
115    // Now, we specify the indices of the vertex that are going to compose the
116    // triangles in our star. Vertices in triangles have to be specified in CCW
117    // winding (that will be the front face, colored). Since we are using
118    // triangle list, we will specify each triangle as 3 vertices
119    //   First triangle: 0, 2, 1
120    //   Second triangle: 0, 3, 2
121    //   Third triangle: 0, 4, 3
122    //   etc
123    //   Last triangle: 0, 1, 10
124    let mut indices = vec![0, 1, 10];
125    for i in 2..=10 {
126        indices.extend_from_slice(&[0, i, i - 1]);
127    }
128    star.insert_indices(Indices::U32(indices));
129
130    // We can now spawn the entities for the star and the camera
131    commands.spawn((
132        // We use a marker component to identify the custom colored meshes
133        ColoredMesh2d,
134        // The `Handle<Mesh>` needs to be wrapped in a `Mesh2d` for 2D rendering
135        Mesh2d(meshes.add(star)),
136    ));
137
138    commands.spawn(Camera2d);
139}
1.53.0 · Source

pub fn extend_from_within<R>(&mut self, src: R)
where R: RangeBounds<usize>,

Available on non-no_global_oom_handling only.

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, if the index is greater than the length of the vector, or if the new capacity exceeds isize::MAX bytes.

§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.0.0 · Source

pub fn dedup(&mut self)

Removes consecutive repeated elements in the vector according to the PartialEq trait implementation.

If the vector is sorted, this removes all duplicates.

§Examples
let mut vec = vec![1, 2, 2, 3, 2];

vec.dedup();

assert_eq!(vec, [1, 2, 3, 2]);
Examples found in repository?
examples/ui/text/system_fonts.rs (line 24)
16fn setup(mut commands: Commands, mut font_system: ResMut<FontCx>) {
17    let mut families: Vec<String> = font_system
18        .context
19        .collection
20        .family_names()
21        .map(ToOwned::to_owned)
22        .collect();
23    families.sort_unstable();
24    families.dedup();
25    let family_count = families.len();
26
27    commands.spawn(Camera2d);
28
29    commands
30        .spawn((
31            Node {
32                flex_direction: FlexDirection::Column,
33                width: percent(100),
34                height: percent(100),
35                align_items: AlignItems::Center,
36                row_gap: px(10.),
37                ..default()
38            },
39            BackgroundColor(Color::srgb(0.1, 0.1, 0.1)),
40        ))
41        .with_children(move |builder| {
42            builder.spawn(Text::new(format!(
43                "Total available fonts: {}",
44                family_count,
45            )));
46
47            builder
48                .spawn(Node {
49                    flex_direction: FlexDirection::Column,
50                    row_gap: px(6),
51                    overflow: Overflow::scroll_y(),
52                    align_items: AlignItems::Stretch,
53                    ..default()
54                })
55                .with_children(|builder| {
56                    for family in families {
57                        let font = FontSource::Family(family.clone().into());
58                        builder.spawn((
59                            Node {
60                                display: Display::Grid,
61                                grid_template_columns: vec![
62                                    GridTrack::flex(1.),
63                                    GridTrack::flex(1.),
64                                ],
65                                padding: px(6).all(),
66                                column_gap: px(50.),
67                                ..default()
68                            },
69                            BackgroundColor(Color::srgb(0.2, 0.2, 0.25)),
70                            children![
71                                (
72                                    Text::new(&family),
73                                    TextFont { font, ..default() },
74                                    TextLayout::no_wrap()
75                                ),
76                                (Text::new(family), TextLayout::no_wrap()),
77                            ],
78                        ));
79                    }
80                })
81                .observe(
82                    |on_scroll: On<PointerScroll>,
83                     mut query: Query<(&mut ScrollPosition, &ComputedNode)>| {
84                        if let Ok((mut scroll_position, node)) = query.get_mut(on_scroll.entity) {
85                            let dy = match on_scroll.unit {
86                                MouseScrollUnit::Line => on_scroll.y * 20.,
87                                MouseScrollUnit::Pixel => on_scroll.y,
88                            };
89                            let range = (node.content_size.y - node.size.y).max(0.)
90                                * node.inverse_scale_factor;
91                            scroll_position.y = (scroll_position.y - dy).clamp(0., range);
92                        }
93                    },
94                );
95        });
96}
1.21.0 · Source

pub fn splice<R, I>( &mut self, range: R, replace_with: I, ) -> Splice<'_, <I as IntoIterator>::IntoIter, A> ⓘ
where A: AllocatorNightly, R: RangeBounds<usize>, I: IntoIterator<Item = T>,

Available on non-no_global_oom_handling only.

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 than range’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 range has start_bound > end_bound, or, if the range is bounded on either end and past 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 · Source

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 an element in the range should be removed.

If the closure returns true, the element is removed from the vector and yielded. If the closure returns false, or panics, the element remains in the vector and will not be yielded.

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 extract_if().for_each(drop) if you do not need the returned iterator, or retain_mut with a negated predicate if you also do not need to restrict the range.

Using this method is equivalent to the following code:

let mut i = range.start;
let end_items = vec.len() - range.end;

while i < vec.len() - end_items {
    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.

The iterator also lets you mutate the value of each element in the closure, regardless of whether you choose to keep or remove it.

§Panics

If range is out of bounds.

§Examples

Splitting a vector into even and odd values, reusing the original vector:

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 · Source

pub fn len(&self) -> usize

Returns the number of elements in the slice.

§Examples
let a = [1, 2, 3];
assert_eq!(a.len(), 3);
1.0.0 · Source

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 · Source

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 · Source

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 · Source

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 · Source

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 · Source

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 · Source

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 · Source

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 · Source

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 · Source

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 · Source

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 · Source

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 · Source

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 · Source

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 · Source

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 · Source

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 · Source

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 · Source

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 · Source

pub fn get_mut<I>( &mut self, index: I, ) -> Option<&mut <I as SliceIndex<[T]>>::Output>
where I: SliceIndex<[T]>,

Returns a mutable reference to an element or subslice depending on the type of index (see get) or None if the index is out of bounds.

§Examples
let x = &mut [0, 1, 2];

if let Some(elem) = x.get_mut(1) {
    *elem = 42;
}
assert_eq!(x, &[0, 42, 2]);
1.0.0 · Source

pub unsafe fn get_unchecked<I>( &self, index: I, ) -> &<I as SliceIndex<[T]>>::Output
where 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 · Source

pub unsafe fn get_unchecked_mut<I>( &mut self, index: I, ) -> &mut <I as SliceIndex<[T]>>::Output
where 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 · Source

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 · Source

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 · Source

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 · Source

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++.

1.93.0 · Source

pub fn as_array<const N: usize>(&self) -> Option<&[T; N]>

Gets a reference to the underlying array.

If N is not exactly equal to the length of self, then this method returns None.

1.93.0 · Source

pub fn as_mut_array<const N: usize>(&mut self) -> Option<&mut [T; N]>

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 · Source

pub fn swap(&mut self, a: usize, b: usize)

Swaps two elements in the slice.

If a equals 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"]);
Source

pub unsafe fn swap_unchecked(&mut self, a: usize, b: usize)

🔬This is a nightly-only experimental API. (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 · Source

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 · Source

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 · Source

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 · Source

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 · Source

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.

If your chunk_size is a constant, consider using as_chunks instead, which will give references to arrays of exactly that length, rather than slices.

§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 · Source

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.

If your chunk_size is a constant, consider using as_chunks_mut instead, which will give references to arrays of exactly that length, rather than slices.

§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 · Source

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.

If your chunk_size is a constant, consider using as_chunks instead, which will give references to arrays of exactly that length, rather than slices.

§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 · Source

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.

If your chunk_size is a constant, consider using as_chunks_mut instead, which will give references to arrays of exactly that length, rather than slices.

§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]);
1.88.0 · Source

pub unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]]

Splits the slice into a slice of N-element arrays, assuming that there’s no remainder.

This is the inverse operation to as_flattened.

As this is unsafe, consider whether you could use as_chunks or as_rchunks instead, perhaps via something like if let (chunks, []) = slice.as_chunks() or let (chunks, []) = slice.as_chunks() else { unreachable!() };.

§Safety

This may only be called when

  • The slice splits exactly into N-element chunks (aka self.len() % N == 0).
  • N != 0.
§Examples
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
1.88.0 · Source

pub fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T])

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.

The remainder is meaningful in the division sense. Given let (chunks, remainder) = slice.as_chunks(), then:

  • chunks.len() equals slice.len() / N,
  • remainder.len() equals slice.len() % N, and
  • slice.len() equals chunks.len() * N + remainder.len().

You can flatten the chunks back into a slice-of-T with as_flattened.

§Panics

Panics if N is zero.

Note that this check is against a const generic parameter, not a runtime value, and thus a particular monomorphization will either always panic or it will never panic.

§Examples
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:

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']]);
1.88.0 · Source

pub fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]])

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.

The remainder is meaningful in the division sense. Given let (remainder, chunks) = slice.as_rchunks(), then:

  • remainder.len() equals slice.len() % N,
  • chunks.len() equals slice.len() / N, and
  • slice.len() equals chunks.len() * N + remainder.len().

You can flatten the chunks back into a slice-of-T with as_flattened.

§Panics

Panics if N is zero.

Note that this check is against a const generic parameter, not a runtime value, and thus a particular monomorphization will either always panic or it will never panic.

§Examples
let slice = ['l', 'o', 'r', 'e', 'm'];
let (remainder, chunks) = slice.as_rchunks();
assert_eq!(remainder, &['l']);
assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]);
1.88.0 · Source

pub unsafe fn as_chunks_unchecked_mut<const N: usize>( &mut self, ) -> &mut [[T; N]]

Splits the slice into a slice of N-element arrays, assuming that there’s no remainder.

This is the inverse operation to as_flattened_mut.

As this is unsafe, consider whether you could use as_chunks_mut or as_rchunks_mut instead, perhaps via something like if let (chunks, []) = slice.as_chunks_mut() or let (chunks, []) = slice.as_chunks_mut() else { unreachable!() };.

§Safety

This may only be called when

  • The slice splits exactly into N-element chunks (aka self.len() % N == 0).
  • N != 0.
§Examples
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
1.88.0 · Source

pub fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T])

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.

The remainder is meaningful in the division sense. Given let (chunks, remainder) = slice.as_chunks_mut(), then:

  • chunks.len() equals slice.len() / N,
  • remainder.len() equals slice.len() % N, and
  • slice.len() equals chunks.len() * N + remainder.len().

You can flatten the chunks back into a slice-of-T with as_flattened_mut.

§Panics

Panics if N is zero.

Note that this check is against a const generic parameter, not a runtime value, and thus a particular monomorphization will either always panic or it will never panic.

§Examples
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]);
1.88.0 · Source

pub fn as_rchunks_mut<const N: usize>(&mut self) -> (&mut [T], &mut [[T; N]])

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.

The remainder is meaningful in the division sense. Given let (remainder, chunks) = slice.as_rchunks_mut(), then:

  • remainder.len() equals slice.len() % N,
  • chunks.len() equals slice.len() / N, and
  • slice.len() equals chunks.len() * N + remainder.len().

You can flatten the chunks back into a slice-of-T with as_flattened_mut.

§Panics

Panics if N is zero.

Note that this check is against a const generic parameter, not a runtime value, and thus a particular monomorphization will either always panic or it will never panic.

§Examples
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]);
1.94.0 · Source

pub fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N> ⓘ

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.

Note that this check is against a const generic parameter, not a runtime value, and thus a particular monomorphization will either always panic or it will never panic.

§Examples
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 · Source

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.

If your chunk_size is a constant, consider using as_rchunks instead, which will give references to arrays of exactly that length, rather than slices.

§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 · Source

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.

If your chunk_size is a constant, consider using as_rchunks_mut instead, which will give references to arrays of exactly that length, rather than slices.

§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 · Source

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.

If your chunk_size is a constant, consider using as_rchunks instead, which will give references to arrays of exactly that length, rather than slices.

§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 · Source

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.

If your chunk_size is a constant, consider using as_rchunks_mut instead, which will give references to arrays of exactly that length, rather than slices.

§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 · Source

pub fn chunk_by<F>(&self, pred: F) -> ChunkBy<'_, T, F> ⓘ
where F: FnMut(&T, &T) -> bool,

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 · Source

pub fn chunk_by_mut<F>(&mut self, pred: F) -> ChunkByMut<'_, T, F> ⓘ
where F: FnMut(&T, &T) -> bool,

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 · Source

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 · Source

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 · Source

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 · Source

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 · Source

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 · Source

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 · Source

pub fn split<F>(&self, pred: F) -> Split<'_, T, F> ⓘ
where F: FnMut(&T) -> bool,

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 · Source

pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F> ⓘ
where F: FnMut(&T) -> bool,

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 · Source

pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F> ⓘ
where F: FnMut(&T) -> bool,

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 · Source

pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F> ⓘ
where F: FnMut(&T) -> bool,

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 · Source

pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F> ⓘ
where F: FnMut(&T) -> bool,

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 · Source

pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F> ⓘ
where F: FnMut(&T) -> bool,

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 · Source

pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F> ⓘ
where F: FnMut(&T) -> bool,

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 · Source

pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F> ⓘ
where F: FnMut(&T) -> bool,

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 · Source

pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F> ⓘ
where F: FnMut(&T) -> bool,

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 · Source

pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F> ⓘ
where F: FnMut(&T) -> bool,

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]);
Source

pub fn split_once<F>(&self, pred: F) -> Option<(&[T], &[T])>
where F: FnMut(&T) -> bool,

🔬This is a nightly-only experimental API. (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);
Source

pub fn rsplit_once<F>(&self, pred: F) -> Option<(&[T], &[T])>
where F: FnMut(&T) -> bool,

🔬This is a nightly-only experimental API. (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 · Source

pub fn contains(&self, x: &T) -> bool
where 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 · Source

pub fn starts_with(&self, needle: &[T]) -> bool
where 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 · Source

pub fn ends_with(&self, needle: &[T]) -> bool
where 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 · Source

pub fn strip_prefix<P>(&self, prefix: &P) -> Option<&[T]>
where P: SlicePattern<Item = T> + ?Sized, T: PartialEq,

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 · Source

pub fn strip_suffix<P>(&self, suffix: &P) -> Option<&[T]>
where P: SlicePattern<Item = T> + ?Sized, T: PartialEq,

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.98.0 · Source

pub fn strip_circumfix<S, P>(&self, prefix: &P, suffix: &S) -> Option<&[T]>
where T: PartialEq, S: SlicePattern<Item = T> + ?Sized, P: SlicePattern<Item = T> + ?Sized,

Returns a subslice with the prefix and suffix removed.

If the slice starts with prefix, ends with suffix, and the prefix and suffix don’t overlap, returns the subslice after the prefix and before the suffix, wrapped in Some.

If the slice does not start with prefix, does not end with suffix, or the prefix and suffix overlap in the slice, returns None.

§Examples
let v = &[10, 50, 40, 30];
assert_eq!(v.strip_circumfix(&[10], &[30]), Some(&[50, 40][..]));
assert_eq!(v.strip_circumfix(&[10], &[40, 30]), Some(&[50][..]));
assert_eq!(v.strip_circumfix(&[10, 50], &[40, 30]), Some(&[][..]));
assert_eq!(v.strip_circumfix(&[50], &[30]), None);
assert_eq!(v.strip_circumfix(&[10], &[40]), None);
assert_eq!(v.strip_circumfix(&[], &[40, 30]), Some(&[10, 50][..]));
assert_eq!(v.strip_circumfix(&[10, 50], &[]), Some(&[40, 30][..]));
assert_eq!(v.strip_circumfix(&[10, 50, 40], &[50, 40, 30]), None);
1.100.0 · Source

pub fn trim_prefix<P>(&self, prefix: &P) -> &[T]
where P: SlicePattern<Item = T> + ?Sized, T: PartialEq,

Returns a subslice with the optional prefix removed.

If the slice starts with prefix, returns the subslice after the prefix. If prefix is empty or the slice does not start with prefix, simply returns the original slice. If prefix is equal to the original slice, returns an empty slice.

§Examples
let v = &[10, 40, 30];

// Prefix present - removes it
assert_eq!(v.trim_prefix(&[10]), &[40, 30][..]);
assert_eq!(v.trim_prefix(&[10, 40]), &[30][..]);
assert_eq!(v.trim_prefix(&[10, 40, 30]), &[][..]);

// Prefix absent - returns original slice
assert_eq!(v.trim_prefix(&[50]), &[10, 40, 30][..]);
assert_eq!(v.trim_prefix(&[10, 50]), &[10, 40, 30][..]);

let prefix : &str = "he";
assert_eq!(b"hello".trim_prefix(prefix.as_bytes()), b"llo".as_ref());
1.100.0 · Source

pub fn trim_suffix<P>(&self, suffix: &P) -> &[T]
where P: SlicePattern<Item = T> + ?Sized, T: PartialEq,

Returns a subslice with the optional suffix removed.

If the slice ends with suffix, returns the subslice before the suffix. If suffix is empty or the slice does not end with suffix, simply returns the original slice. If suffix is equal to the original slice, returns an empty slice.

§Examples
let v = &[10, 40, 30];

// Suffix present - removes it
assert_eq!(v.trim_suffix(&[30]), &[10, 40][..]);
assert_eq!(v.trim_suffix(&[40, 30]), &[10][..]);
assert_eq!(v.trim_suffix(&[10, 40, 30]), &[][..]);

// Suffix absent - returns original slice
assert_eq!(v.trim_suffix(&[50]), &[10, 40, 30][..]);
assert_eq!(v.trim_suffix(&[50, 30]), &[10, 40, 30][..]);

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 · Source

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

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 · Source

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

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 · Source

pub fn sort_unstable(&mut self)
where T: Ord,

Sorts the slice in ascending order 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 · Source

pub fn sort_unstable_by<F>(&mut self, compare: F)
where F: FnMut(&T, &T) -> Ordering,

Sorts the slice in ascending order 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 · Source

pub fn sort_unstable_by_key<K, F>(&mut self, f: F)
where F: FnMut(&T) -> K, K: Ord,

Sorts the slice in ascending order 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]);
Source

pub fn partial_sort_unstable<R>(&mut self, range: R)
where T: Ord, R: RangeBounds<usize>,

🔬This is a nightly-only experimental API. (slice_partial_sort_unstable)

Partially sorts the slice in ascending order without preserving the initial order of equal elements.

Upon completion, for the specified range start..end, it’s guaranteed that:

  1. Every element in self[..start] is smaller than or equal to
  2. Every element in self[start..end], which is sorted, and smaller than or equal to
  3. Every element in self[end..].

This partial sort is unstable, meaning it may reorder equal elements in the specified range. It may reorder elements outside the specified range as well, but the guarantees above still hold.

This partial sort is in-place (i.e., does not allocate), and O(n + k * log(k)) worst-case, where n is the length of the slice and k is the length of the specified range.

See the documentation of sort_unstable for implementation notes.

§Panics

May panic if the implementation of Ord for T does not implement a total order, or if the Ord implementation panics, or if the specified range is out of bounds.

§Examples
#![feature(slice_partial_sort_unstable)]

let mut v = [4, -5, 1, -3, 2];

// empty range at the beginning, nothing changed
v.partial_sort_unstable(0..0);
assert_eq!(v, [4, -5, 1, -3, 2]);

// empty range in the middle, partitioning the slice
v.partial_sort_unstable(2..2);
for i in 0..2 {
   assert!(v[i] <= v[2]);
}
for i in 3..v.len() {
  assert!(v[2] <= v[i]);
}

// single element range, same as select_nth_unstable
v.partial_sort_unstable(2..3);
for i in 0..2 {
   assert!(v[i] <= v[2]);
}
for i in 3..v.len() {
  assert!(v[2] <= v[i]);
}

// partial sort a subrange
v.partial_sort_unstable(1..4);
assert_eq!(&v[1..4], [-3, 1, 2]);

// partial sort the whole range, same as sort_unstable
v.partial_sort_unstable(..);
assert_eq!(v, [-5, -3, 1, 2, 4]);
Source

pub fn partial_sort_unstable_by<F, R>(&mut self, range: R, compare: F)
where F: FnMut(&T, &T) -> Ordering, R: RangeBounds<usize>,

🔬This is a nightly-only experimental API. (slice_partial_sort_unstable)

Partially sorts the slice in ascending order with a comparison function, without preserving the initial order of equal elements.

Upon completion, for the specified range start..end, it’s guaranteed that:

  1. Every element in self[..start] is smaller than or equal to
  2. Every element in self[start..end], which is sorted, and smaller than or equal to
  3. Every element in self[end..].

This partial sort is unstable, meaning it may reorder equal elements in the specified range. It may reorder elements outside the specified range as well, but the guarantees above still hold.

This partial sort is in-place (i.e., does not allocate), and O(n + k * log(k)) worst-case, where n is the length of the slice and k is the length of the specified range.

See the documentation of sort_unstable_by for implementation notes.

§Panics

May panic if the compare does not implement a total order, or if the compare itself panics, or if the specified range is out of bounds.

§Examples
#![feature(slice_partial_sort_unstable)]

let mut v = [4, -5, 1, -3, 2];

// empty range at the beginning, nothing changed
v.partial_sort_unstable_by(0..0, |a, b| b.cmp(a));
assert_eq!(v, [4, -5, 1, -3, 2]);

// empty range in the middle, partitioning the slice
v.partial_sort_unstable_by(2..2, |a, b| b.cmp(a));
for i in 0..2 {
   assert!(v[i] >= v[2]);
}
for i in 3..v.len() {
  assert!(v[2] >= v[i]);
}

// single element range, same as select_nth_unstable
v.partial_sort_unstable_by(2..3, |a, b| b.cmp(a));
for i in 0..2 {
   assert!(v[i] >= v[2]);
}
for i in 3..v.len() {
  assert!(v[2] >= v[i]);
}

// partial sort a subrange
v.partial_sort_unstable_by(1..4, |a, b| b.cmp(a));
assert_eq!(&v[1..4], [2, 1, -3]);

// partial sort the whole range, same as sort_unstable
v.partial_sort_unstable_by(.., |a, b| b.cmp(a));
assert_eq!(v, [4, 2, 1, -3, -5]);
Source

pub fn partial_sort_unstable_by_key<K, F, R>(&mut self, range: R, f: F)
where F: FnMut(&T) -> K, K: Ord, R: RangeBounds<usize>,

🔬This is a nightly-only experimental API. (slice_partial_sort_unstable)

Partially sorts the slice in ascending order with a key extraction function, without preserving the initial order of equal elements.

Upon completion, for the specified range start..end, it’s guaranteed that:

  1. Every element in self[..start] is smaller than or equal to
  2. Every element in self[start..end], which is sorted, and smaller than or equal to
  3. Every element in self[end..].

This partial sort is unstable, meaning it may reorder equal elements in the specified range. It may reorder elements outside the specified range as well, but the guarantees above still hold.

This partial sort is in-place (i.e., does not allocate), and O(n + k * log(k)) worst-case, where n is the length of the slice and k is the length of the specified range.

See the documentation of sort_unstable_by_key for implementation notes.

§Panics

May panic if the implementation of Ord for K does not implement a total order, or if the Ord implementation panics, or if the specified range is out of bounds.

§Examples
#![feature(slice_partial_sort_unstable)]

let mut v = [4i32, -5, 1, -3, 2];

// empty range at the beginning, nothing changed
v.partial_sort_unstable_by_key(0..0, |k| k.abs());
assert_eq!(v, [4, -5, 1, -3, 2]);

// empty range in the middle, partitioning the slice
v.partial_sort_unstable_by_key(2..2, |k| k.abs());
for i in 0..2 {
   assert!(v[i].abs() <= v[2].abs());
}
for i in 3..v.len() {
  assert!(v[2].abs() <= v[i].abs());
}

// single element range, same as select_nth_unstable
v.partial_sort_unstable_by_key(2..3, |k| k.abs());
for i in 0..2 {
   assert!(v[i].abs() <= v[2].abs());
}
for i in 3..v.len() {
  assert!(v[2].abs() <= v[i].abs());
}

// partial sort a subrange
v.partial_sort_unstable_by_key(1..4, |k| k.abs());
assert_eq!(&v[1..4], [2, -3, 4]);

// partial sort the whole range, same as sort_unstable
v.partial_sort_unstable_by_key(.., |k| k.abs());
assert_eq!(v, [1, 2, -3, 4, -5]);
1.49.0 · Source

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 satisfy x <= self[index].

  • The element at index.

  • The unsorted subslice after index, whose elements all satisfy x >= 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 · Source

pub fn select_nth_unstable_by<F>( &mut self, index: usize, compare: F, ) -> (&mut [T], &mut T, &mut [T])
where F: FnMut(&T, &T) -> Ordering,

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 satisfy compare(x, self[index]).is_le().

  • The element at index.

  • The unsorted subslice after index, whose elements all satisfy compare(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 · Source

pub fn select_nth_unstable_by_key<K, F>( &mut self, index: usize, f: F, ) -> (&mut [T], &mut T, &mut [T])
where F: FnMut(&T) -> K, K: Ord,

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 satisfy f(x) <= f(self[index]).

  • The element at index.

  • The unsorted subslice after index, whose elements all satisfy f(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]);
Source

pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])
where T: PartialEq,

🔬This is a nightly-only experimental API. (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]);
Source

pub fn partition_dedup_by<F>(&mut self, same_bucket: F) -> (&mut [T], &mut [T])
where F: FnMut(&mut T, &mut T) -> bool,

🔬This is a nightly-only experimental API. (slice_partition_dedup)

Moves all but the first of consecutive elements to the end of the slice that are “equal” according to the given predicate function.

Returns two slices. The first contains no consecutive repeated elements. The second contains all the duplicates in no specified order.

The predicate same_bucket(x, p) is passed references to two elements from the slice and must determine if the elements compare equal. The element p occurs before x in the slice ([.., p, .., x, ..]), so same_bucket(x, p) is receiving them in reversed order.

If the slice is sorted, the first returned slice contains no duplicates. For more complicated predicates however, the order (ascending vs. descending) can matter.

Both references passed to same_bucket are mutable. This allows merged elements in the first slice by mutating p and returning true.

§Examples
#![feature(slice_partition_dedup)]

let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];

let (dedup, duplicates) = slice.partition_dedup_by(|x, p| x.eq_ignore_ascii_case(p));

assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
Source

pub fn partition_dedup_by_key<K, F>(&mut self, key: F) -> (&mut [T], &mut [T])
where F: FnMut(&mut T) -> K, K: PartialEq,

🔬This is a nightly-only experimental API. (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 · Source

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 · Source

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']);
Source

pub fn shift_left<const N: usize>(&mut self, inserted: [T; N]) -> [T; N]

🔬This is a nightly-only experimental API. (slice_shift)

Moves the elements of this slice N places to the left, returning the ones that “fall off” the front, and putting inserted at the end.

Equivalently, you can think of concatenating self and inserted into one long sequence, then returning the left-most N items and the rest into self:

          self (before)    inserted
          vvvvvvvvvvvvvvv  vvv
          [1, 2, 3, 4, 5]  [9]
       ↙   ↙  ↙  ↙  ↙   ↙
     [1]  [2, 3, 4, 5, 9]
     ^^^  ^^^^^^^^^^^^^^^
returned  self (after)

See also Self::shift_right and compare Self::rotate_left.

§Examples
#![feature(slice_shift)]

// Same as the diagram above
let mut a = [1, 2, 3, 4, 5];
let inserted = [9];
let returned = a.shift_left(inserted);
assert_eq!(returned, [1]);
assert_eq!(a, [2, 3, 4, 5, 9]);

// You can shift multiple items at a time
let mut a = *b"Hello world";
assert_eq!(a.shift_left(*b" peace"), *b"Hello ");
assert_eq!(a, *b"world peace");

// The name comes from this operation's similarity to bitshifts
let mut a: u8 = 0b10010110;
a <<= 3;
assert_eq!(a, 0b10110000_u8);
let mut a: [_; 8] = [1, 0, 0, 1, 0, 1, 1, 0];
a.shift_left([0; 3]);
assert_eq!(a, [1, 0, 1, 1, 0, 0, 0, 0]);

// Remember you can sub-slice to affect less that the whole slice.
// For example, this is similar to `.remove(1)` + `.insert(4, 'Z')`
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
assert_eq!(a[1..=4].shift_left(['Z']), ['b']);
assert_eq!(a, ['a', 'c', 'd', 'e', 'Z', 'f']);

// If the size matches it's equivalent to `mem::replace`
let mut a = [1, 2, 3];
assert_eq!(a.shift_left([7, 8, 9]), [1, 2, 3]);
assert_eq!(a, [7, 8, 9]);

// Some of the "inserted" elements end up returned if the slice is too short
let mut a = [];
assert_eq!(a.shift_left([1, 2, 3]), [1, 2, 3]);
let mut a = [9];
assert_eq!(a.shift_left([1, 2, 3]), [9, 1, 2]);
assert_eq!(a, [3]);
Source

pub fn shift_right<const N: usize>(&mut self, inserted: [T; N]) -> [T; N]

🔬This is a nightly-only experimental API. (slice_shift)

Moves the elements of this slice N places to the right, returning the ones that “fall off” the back, and putting inserted at the beginning.

Equivalently, you can think of concatenating inserted and self into one long sequence, then returning the right-most N items and the rest into self:

inserted  self (before)
     vvv  vvvvvvvvvvvvvvv
     [0]  [5, 6, 7, 8, 9]
       ↘   ↘  ↘  ↘  ↘   ↘
          [0, 5, 6, 7, 8]  [9]
          ^^^^^^^^^^^^^^^  ^^^
          self (after)     returned

See also Self::shift_left and compare Self::rotate_right.

§Examples
#![feature(slice_shift)]

// Same as the diagram above
let mut a = [5, 6, 7, 8, 9];
let inserted = [0];
let returned = a.shift_right(inserted);
assert_eq!(returned, [9]);
assert_eq!(a, [0, 5, 6, 7, 8]);

// The name comes from this operation's similarity to bitshifts
let mut a: u8 = 0b10010110;
a >>= 3;
assert_eq!(a, 0b00010010_u8);
let mut a: [_; 8] = [1, 0, 0, 1, 0, 1, 1, 0];
a.shift_right([0; 3]);
assert_eq!(a, [0, 0, 0, 1, 0, 0, 1, 0]);

// Remember you can sub-slice to affect less that the whole slice.
// For example, this is similar to `.remove(4)` + `.insert(1, 'Z')`
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
assert_eq!(a[1..=4].shift_right(['Z']), ['e']);
assert_eq!(a, ['a', 'Z', 'b', 'c', 'd', 'f']);

// If the size matches it's equivalent to `mem::replace`
let mut a = [1, 2, 3];
assert_eq!(a.shift_right([7, 8, 9]), [1, 2, 3]);
assert_eq!(a, [7, 8, 9]);

// Some of the "inserted" elements end up returned if the slice is too short
let mut a = [];
assert_eq!(a.shift_right([1, 2, 3]), [1, 2, 3]);
let mut a = [9];
assert_eq!(a.shift_right([1, 2, 3]), [2, 3, 9]);
assert_eq!(a, [1]);
1.50.0 · Source

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 · Source

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 · Source

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 · Source

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 · Source

pub fn copy_within<R>(&mut self, src: R, dest: usize)
where R: RangeBounds<usize>, T: Copy,

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 · Source

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 · Source

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 · Source

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);
}
Source

pub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])
where Simd<T, LANES>: AsRef<[T; LANES]>, T: SimdElement,

🔬This is a nightly-only experimental API. (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);
Source

pub fn as_simd_mut<const LANES: usize>( &mut self, ) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T])
where Simd<T, LANES>: AsMut<[T; LANES]>, T: SimdElement,

🔬This is a nightly-only experimental API. (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 · Source

pub fn is_sorted(&self) -> bool
where 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 · Source

pub fn is_sorted_by<'a, F>(&'a self, compare: F) -> bool
where F: FnMut(&'a T, &'a T) -> 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 · Source

pub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> bool
where F: FnMut(&'a T) -> K, K: PartialOrd,

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 · Source

pub fn partition_point<P>(&self, pred: P) -> usize
where P: FnMut(&T) -> bool,

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 · Source

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 a slice starting with the third element:

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 · Source

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']);

Splitting off a slice starting with the third element:

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 · Source

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 · Source

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 · Source

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 · Source

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 · Source

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 usizes 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 · Source

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 usizes 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]);
1.94.0 · Source

pub fn element_offset(&self, element: &T) -> Option<usize>

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:

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:

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
1.98.0 · Source

pub fn subslice_range(&self, subslice: &[T]) -> Option<Range<usize>>

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:

use core::range::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(Range { start: 0, end: 0 }));
assert_eq!(iter.next(), Some(Range { start: 1, end: 3 }));
assert_eq!(iter.next(), Some(Range { start: 4, end: 4 }));
assert_eq!(iter.next(), Some(Range { start: 5, end: 6 }));
Source

pub fn as_slice(&self) -> &[T]

🔬This is a nightly-only experimental API. (str_as_str)

Returns the same slice &[T].

This method is redundant when used directly on &[T], but it helps dereferencing other “container” types to slices, for example Box<[T]> or Arc<[T]>.

Source

pub fn as_mut_slice(&mut self) -> &mut [T]

🔬This is a nightly-only experimental API. (str_as_str)

Returns the same slice &mut [T].

This method is redundant when used directly on &mut [T], but it helps dereferencing other “container” types to slices, for example Box<[T]> or MutexGuard<[T]>.

1.0.0 · Source

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

Available on non-no_global_oom_handling only.

Sorts the slice in ascending order, 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 · Source

pub fn sort_by<F>(&mut self, compare: F)
where F: FnMut(&T, &T) -> Ordering,

Available on non-no_global_oom_handling only.

Sorts the slice in ascending order 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 · Source

pub fn sort_by_key<K, F>(&mut self, f: F)
where F: FnMut(&T) -> K, K: Ord,

Available on non-no_global_oom_handling only.

Sorts the slice in ascending order 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 · Source

pub fn sort_by_cached_key<K, F>(&mut self, f: F)
where F: FnMut(&T) -> K, K: Ord,

Available on non-no_global_oom_handling only.

Sorts the slice in ascending order 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 · Source

pub fn to_vec(&self) -> Vec<T>
where T: Clone,

Available on non-no_global_oom_handling only.

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?
examples/3d/occlusion_culling.rs (line 591)
559fn readback_indirect_parameters(
560    mut indirect_parameters_staging_buffers: ResMut<IndirectParametersStagingBuffers>,
561    saved_indirect_parameters: Res<SavedIndirectParameters>,
562) {
563    // If culling isn't supported on this platform, bail.
564    if !saved_indirect_parameters
565        .lock()
566        .unwrap()
567        .as_ref()
568        .unwrap()
569        .occlusion_culling_supported
570    {
571        return;
572    }
573
574    // Grab the staging buffers.
575    let (Some(data_buffer), Some(batch_sets_buffer)) = (
576        indirect_parameters_staging_buffers.data.take(),
577        indirect_parameters_staging_buffers.batch_sets.take(),
578    ) else {
579        return;
580    };
581
582    // Read the GPU buffers back.
583    let saved_indirect_parameters_0 = (**saved_indirect_parameters).clone();
584    let saved_indirect_parameters_1 = (**saved_indirect_parameters).clone();
585    readback_buffer::<IndirectParametersIndexed>(data_buffer, move |indirect_parameters| {
586        saved_indirect_parameters_0
587            .lock()
588            .unwrap()
589            .as_mut()
590            .unwrap()
591            .data = indirect_parameters.to_vec();
592    });
593    readback_buffer::<u32>(batch_sets_buffer, move |indirect_parameters_count| {
594        saved_indirect_parameters_1
595            .lock()
596            .unwrap()
597            .as_mut()
598            .unwrap()
599            .count = indirect_parameters_count[0];
600    });
601}
More examples
Hide additional examples
examples/shader_advanced/texture_binding_array.rs (line 198)
165    fn bind_group_layout_entries(_: &RenderDevice, _: bool) -> Vec<BindGroupLayoutEntry>
166    where
167        Self: Sized,
168    {
169        BindGroupLayoutEntries::with_indices(
170            // The layout entries will only be visible in the fragment stage
171            ShaderStages::FRAGMENT,
172            (
173                // Screen texture
174                //
175                // @group(#{MATERIAL_BIND_GROUP}) @binding(0) var textures: binding_array<texture_2d<f32>>;
176                (
177                    0,
178                    texture_2d(TextureSampleType::Float { filterable: true })
179                        .count(NonZero::<u32>::new(MAX_TEXTURE_COUNT as u32).unwrap()),
180                ),
181                // Sampler
182                //
183                // @group(#{MATERIAL_BIND_GROUP}) @binding(1) var nearest_sampler: sampler;
184                //
185                // Note: as with textures, multiple samplers can also be bound
186                // onto one binding slot:
187                //
188                // ```
189                // sampler(SamplerBindingType::Filtering)
190                //     .count(NonZero::<u32>::new(MAX_TEXTURE_COUNT as u32).unwrap()),
191                // ```
192                //
193                // One may need to pay attention to the limit of sampler binding
194                // amount on some platforms.
195                (1, sampler(SamplerBindingType::Filtering)),
196            ),
197        )
198        .to_vec()
199    }
examples/math/render_primitives.rs (line 456)
430fn draw_gizmos_2d(mut gizmos: Gizmos, state: Res<State<PrimitiveSelected>>, time: Res<Time>) {
431    const POSITION: Vec2 = Vec2::new(-LEFT_RIGHT_OFFSET_2D, 0.0);
432    let angle = time.elapsed_secs();
433    let isometry = Isometry2d::new(POSITION, Rot2::radians(angle));
434    let color = Color::WHITE;
435
436    #[expect(
437        clippy::match_same_arms,
438        reason = "Certain primitives don't have any 2D rendering support yet."
439    )]
440    match state.get() {
441        PrimitiveSelected::RectangleAndCuboid => {
442            gizmos.primitive_2d(&RECTANGLE, isometry, color);
443        }
444        PrimitiveSelected::CircleAndSphere => {
445            gizmos.primitive_2d(&CIRCLE, isometry, color);
446        }
447        PrimitiveSelected::Ellipse => drop(gizmos.primitive_2d(&ELLIPSE, isometry, color)),
448        PrimitiveSelected::Triangle => gizmos.primitive_2d(&TRIANGLE_2D, isometry, color),
449        PrimitiveSelected::Plane => gizmos.primitive_2d(&PLANE_2D, isometry, color),
450        PrimitiveSelected::Line => drop(gizmos.primitive_2d(&LINE_2D, isometry, color)),
451        PrimitiveSelected::Segment => {
452            drop(gizmos.primitive_2d(&SEGMENT_2D, isometry, color));
453        }
454        PrimitiveSelected::Polyline => gizmos.primitive_2d(
455            &Polyline2d {
456                vertices: POLYLINE_2D_VERTICES.to_vec(),
457            },
458            isometry,
459            color,
460        ),
461        PrimitiveSelected::ConvexPolygon => gizmos.primitive_2d(
462            &Polygon::from(ConvexPolygon::new(CONVEX_POLYGON_VERTICES).unwrap()),
463            isometry,
464            color,
465        ),
466        PrimitiveSelected::Polygon => gizmos.primitive_2d(
467            &Polygon {
468                vertices: vec![
469                    Vec2::new(-BIG_2D, -SMALL_2D),
470                    Vec2::new(BIG_2D, -SMALL_2D),
471                    Vec2::new(BIG_2D, SMALL_2D),
472                    Vec2::new(0.0, 0.0),
473                    Vec2::new(-BIG_2D, SMALL_2D),
474                ],
475            },
476            isometry,
477            color,
478        ),
479        PrimitiveSelected::RegularPolygon => {
480            gizmos.primitive_2d(&REGULAR_POLYGON, isometry, color);
481        }
482        PrimitiveSelected::Capsule => gizmos.primitive_2d(&CAPSULE_2D, isometry, color),
483        PrimitiveSelected::Cylinder => {}
484        PrimitiveSelected::Cone => {}
485        PrimitiveSelected::ConicalFrustum => {}
486        PrimitiveSelected::Torus => drop(gizmos.primitive_2d(&ANNULUS, isometry, color)),
487        PrimitiveSelected::Tetrahedron => {}
488        PrimitiveSelected::Arc => gizmos.primitive_2d(&ARC, isometry, color),
489        PrimitiveSelected::CircularSector => {
490            gizmos.primitive_2d(&CIRCULAR_SECTOR, isometry, color);
491        }
492        PrimitiveSelected::CircularSegment => {
493            gizmos.primitive_2d(&CIRCULAR_SEGMENT, isometry, color);
494        }
495    }
496}
497
498/// Marker for primitive meshes to record in which state they should be visible in
499#[derive(Debug, Clone, Component, Default, Reflect)]
500pub struct PrimitiveData {
501    camera_mode: CameraActive,
502    primitive_state: PrimitiveSelected,
503}
504
505/// Marker for meshes of 2D primitives
506#[derive(Debug, Clone, Component, Default)]
507pub struct MeshDim2;
508
509/// Marker for meshes of 3D primitives
510#[derive(Debug, Clone, Component, Default)]
511pub struct MeshDim3;
512
513fn spawn_primitive_2d(
514    mut commands: Commands,
515    mut materials: ResMut<Assets<ColorMaterial>>,
516    mut meshes: ResMut<Assets<Mesh>>,
517) {
518    const POSITION: Vec3 = Vec3::new(LEFT_RIGHT_OFFSET_2D, 0.0, 0.0);
519    let material: Handle<ColorMaterial> = materials.add(Color::WHITE);
520    let camera_mode = CameraActive::Dim2;
521    let polyline_2d = Polyline2d {
522        vertices: POLYLINE_2D_VERTICES.to_vec(),
523    };
524    let convex_polygon = ConvexPolygon::new(CONVEX_POLYGON_VERTICES).unwrap();
525    [
526        Some(RECTANGLE.mesh().build()),
527        Some(CIRCLE.mesh().build()),
528        Some(ELLIPSE.mesh().build()),
529        Some(TRIANGLE_2D.mesh().build()),
530        None, // plane
531        None, // line
532        Some(SEGMENT_2D.mesh().build()),
533        Some(polyline_2d.mesh().build()),
534        None, // polygon
535        Some(convex_polygon.mesh().build()),
536        Some(REGULAR_POLYGON.mesh().build()),
537        Some(CAPSULE_2D.mesh().build()),
538        None, // cylinder
539        None, // cone
540        None, // conical frustum
541        Some(ANNULUS.mesh().build()),
542        None, // tetrahedron
543        None, // arc
544        Some(CIRCULAR_SECTOR.mesh().build()),
545        Some(CIRCULAR_SEGMENT.mesh().build()),
546    ]
547    .into_iter()
548    .zip(PrimitiveSelected::ALL)
549    .for_each(|(maybe_mesh, state)| {
550        if let Some(mesh) = maybe_mesh {
551            commands.spawn((
552                MeshDim2,
553                PrimitiveData {
554                    camera_mode,
555                    primitive_state: state,
556                },
557                Mesh2d(meshes.add(mesh)),
558                MeshMaterial2d(material.clone()),
559                Transform::from_translation(POSITION),
560            ));
561        }
562    });
563}
564
565fn spawn_primitive_3d(
566    mut commands: Commands,
567    mut materials: ResMut<Assets<StandardMaterial>>,
568    mut meshes: ResMut<Assets<Mesh>>,
569) {
570    const POSITION: Vec3 = Vec3::new(-LEFT_RIGHT_OFFSET_3D, 0.0, 0.0);
571    let material: Handle<StandardMaterial> = materials.add(Color::WHITE);
572    let camera_mode = CameraActive::Dim3;
573    let polyline_3d = Polyline3d {
574        vertices: POLYLINE_3D_VERTICES.to_vec(),
575    };
576    [
577        Some(CUBOID.mesh().build()),
578        Some(SPHERE.mesh().build()),
579        None, // ellipse
580        Some(TRIANGLE_3D.mesh().build()),
581        Some(PLANE_3D.mesh().build()),
582        None, // line
583        Some(SEGMENT_3D.mesh().build()),
584        Some(polyline_3d.mesh().build()),
585        None, // polygon
586        None, // convex polygon
587        None, // regular polygon
588        Some(CAPSULE_3D.mesh().build()),
589        Some(CYLINDER.mesh().build()),
590        Some(CONE.mesh().build()),
591        Some(CONICAL_FRUSTUM.mesh().build()),
592        Some(TORUS.mesh().build()),
593        Some(TETRAHEDRON.mesh().build()),
594        None, // arc
595        None, // circular sector
596        None, // circular segment
597    ]
598    .into_iter()
599    .zip(PrimitiveSelected::ALL)
600    .for_each(|(maybe_mesh, state)| {
601        if let Some(mesh) = maybe_mesh {
602            commands.spawn((
603                MeshDim3,
604                PrimitiveData {
605                    camera_mode,
606                    primitive_state: state,
607                },
608                Mesh3d(meshes.add(mesh)),
609                MeshMaterial3d(material.clone()),
610                Transform::from_translation(POSITION),
611            ));
612        }
613    });
614}
615
616fn update_primitive_meshes(
617    camera_state: Res<State<CameraActive>>,
618    primitive_state: Res<State<PrimitiveSelected>>,
619    mut primitives: Query<(&mut Visibility, &PrimitiveData)>,
620) {
621    primitives.iter_mut().for_each(|(mut vis, primitive)| {
622        let visible = primitive.camera_mode == *camera_state.get()
623            && primitive.primitive_state == *primitive_state.get();
624        *vis = if visible {
625            Visibility::Inherited
626        } else {
627            Visibility::Hidden
628        };
629    });
630}
631
632fn rotate_primitive_2d_meshes(
633    mut primitives_2d: Query<
634        (&mut Transform, &ViewVisibility),
635        (With<PrimitiveData>, With<MeshDim2>),
636    >,
637    time: Res<Time>,
638) {
639    let rotation_2d = Quat::from_mat3(&Mat3::from_angle(time.elapsed_secs()));
640    primitives_2d
641        .iter_mut()
642        .filter(|(_, vis)| vis.get())
643        .for_each(|(mut transform, _)| {
644            transform.rotation = rotation_2d;
645        });
646}
647
648fn rotate_primitive_3d_meshes(
649    mut primitives_3d: Query<
650        (&mut Transform, &ViewVisibility),
651        (With<PrimitiveData>, With<MeshDim3>),
652    >,
653    time: Res<Time>,
654) {
655    let rotation_3d = Quat::from_rotation_arc(
656        Vec3::Z,
657        Vec3::new(
658            ops::sin(time.elapsed_secs()),
659            ops::cos(time.elapsed_secs()),
660            ops::sin(time.elapsed_secs()) * 0.5,
661        )
662        .try_normalize()
663        .unwrap_or(Vec3::Z),
664    );
665    primitives_3d
666        .iter_mut()
667        .filter(|(_, vis)| vis.get())
668        .for_each(|(mut transform, _)| {
669            transform.rotation = rotation_3d;
670        });
671}
672
673fn draw_gizmos_3d(mut gizmos: Gizmos, state: Res<State<PrimitiveSelected>>, time: Res<Time>) {
674    const POSITION: Vec3 = Vec3::new(LEFT_RIGHT_OFFSET_3D, 0.0, 0.0);
675    let rotation = Quat::from_rotation_arc(
676        Vec3::Z,
677        Vec3::new(
678            ops::sin(time.elapsed_secs()),
679            ops::cos(time.elapsed_secs()),
680            ops::sin(time.elapsed_secs()) * 0.5,
681        )
682        .try_normalize()
683        .unwrap_or(Vec3::Z),
684    );
685    let isometry = Isometry3d::new(POSITION, rotation);
686    let color = Color::WHITE;
687    let resolution = 10;
688
689    #[expect(
690        clippy::match_same_arms,
691        reason = "Certain primitives don't have any 3D rendering support yet."
692    )]
693    match state.get() {
694        PrimitiveSelected::RectangleAndCuboid => {
695            gizmos.primitive_3d(&CUBOID, isometry, color);
696        }
697        PrimitiveSelected::CircleAndSphere => drop(
698            gizmos
699                .primitive_3d(&SPHERE, isometry, color)
700                .resolution(resolution),
701        ),
702        PrimitiveSelected::Ellipse => {}
703        PrimitiveSelected::Triangle => gizmos.primitive_3d(&TRIANGLE_3D, isometry, color),
704        PrimitiveSelected::Plane => drop(gizmos.primitive_3d(&PLANE_3D, isometry, color)),
705        PrimitiveSelected::Line => gizmos.primitive_3d(&LINE_3D, isometry, color),
706        PrimitiveSelected::Segment => gizmos.primitive_3d(&SEGMENT_3D, isometry, color),
707        PrimitiveSelected::Polyline => gizmos.primitive_3d(
708            &Polyline3d {
709                vertices: POLYLINE_3D_VERTICES.to_vec(),
710            },
711            isometry,
712            color,
713        ),
714        PrimitiveSelected::Polygon => {}
715        PrimitiveSelected::ConvexPolygon => {}
716        PrimitiveSelected::RegularPolygon => {}
717        PrimitiveSelected::Capsule => drop(
718            gizmos
719                .primitive_3d(&CAPSULE_3D, isometry, color)
720                .resolution(resolution),
721        ),
722        PrimitiveSelected::Cylinder => drop(
723            gizmos
724                .primitive_3d(&CYLINDER, isometry, color)
725                .resolution(resolution),
726        ),
727        PrimitiveSelected::Cone => drop(
728            gizmos
729                .primitive_3d(&CONE, isometry, color)
730                .resolution(resolution),
731        ),
732        PrimitiveSelected::ConicalFrustum => {
733            gizmos.primitive_3d(&CONICAL_FRUSTUM, isometry, color);
734        }
735
736        PrimitiveSelected::Torus => drop(
737            gizmos
738                .primitive_3d(&TORUS, isometry, color)
739                .minor_resolution(resolution)
740                .major_resolution(resolution),
741        ),
742        PrimitiveSelected::Tetrahedron => {
743            gizmos.primitive_3d(&TETRAHEDRON, isometry, color);
744        }
745
746        PrimitiveSelected::Arc => {}
747        PrimitiveSelected::CircularSector => {}
748        PrimitiveSelected::CircularSegment => {}
749    }
750}
examples/app/headless_renderer.rs (line 439)
378fn receive_image_from_buffer(
379    image_copiers: Res<ImageCopiers>,
380    render_device: Res<RenderDevice>,
381    sender: Res<RenderWorldSender>,
382) {
383    for image_copier in image_copiers.0.iter() {
384        if !image_copier.enabled() {
385            continue;
386        }
387
388        // Finally time to get our data back from the gpu.
389        // First we get a buffer slice which represents a chunk of the buffer (which we
390        // can't access yet).
391        // We want the whole thing so use unbounded range.
392        let buffer_slice = image_copier.buffer.slice(..);
393
394        // Now things get complicated. WebGPU, for safety reasons, only allows either the GPU
395        // or CPU to access a buffer's contents at a time. We need to "map" the buffer which means
396        // flipping ownership of the buffer over to the CPU and making access legal. We do this
397        // with `BufferSlice::map_async`.
398        //
399        // The problem is that map_async is not an async function so we can't await it. What
400        // we need to do instead is pass in a closure that will be executed when the slice is
401        // either mapped or the mapping has failed.
402        //
403        // The problem with this is that we don't have a reliable way to wait in the main
404        // code for the buffer to be mapped and even worse, calling get_mapped_range or
405        // get_mapped_range_mut prematurely will cause a panic, not return an error.
406        //
407        // Using channels solves this as awaiting the receiving of a message from
408        // the passed closure will force the outside code to wait. It also doesn't hurt
409        // if the closure finishes before the outside code catches up as the message is
410        // buffered and receiving will just pick that up.
411        //
412        // It may also be worth noting that although on native, the usage of asynchronous
413        // channels is wholly unnecessary, for the sake of portability to Wasm
414        // we'll use async channels that work on both native and Wasm.
415
416        let (s, r) = crossbeam_channel::bounded(1);
417
418        // Maps the buffer so it can be read on the cpu
419        buffer_slice.map_async(MapMode::Read, move |r| match r {
420            // This will execute once the gpu is ready, so after the call to poll()
421            Ok(r) => s.send(r).expect("Failed to send map update"),
422            Err(err) => panic!("Failed to map buffer {err}"),
423        });
424
425        // In order for the mapping to be completed, one of three things must happen.
426        // One of those can be calling `Device::poll`. This isn't necessary on the web as devices
427        // are polled automatically but natively, we need to make sure this happens manually.
428        // `Maintain::Wait` will cause the thread to wait on native but not on WebGpu.
429
430        // This blocks until the gpu is done executing everything
431        render_device
432            .poll(PollType::wait_indefinitely())
433            .expect("Failed to poll device for map async");
434
435        // This blocks until the buffer is mapped
436        r.recv().expect("Failed to receive the map_async message");
437
438        // This could fail on app exit, if Main world clears resources (including receiver) while Render world still renders
439        let _ = sender.send(buffer_slice.get_mapped_range().unwrap().to_vec());
440
441        // We need to make sure all `BufferView`'s are dropped before we do what we're about
442        // to do.
443        // Unmap so that we can copy to the staging buffer in the next iteration.
444        image_copier.buffer.unmap();
445    }
446}
examples/ecs/dynamic.rs (line 208)
69fn main() {
70    let mut world = World::new();
71    let mut lines = std::io::stdin().lines();
72    let mut component_names = HashMap::<String, ComponentId>::new();
73    let mut component_info = HashMap::<ComponentId, ComponentInfo>::new();
74    let mut event_names = HashMap::<String, EventKey>::new();
75
76    println!("{PROMPT}");
77    loop {
78        print!("\n> ");
79        let _ = std::io::stdout().flush();
80        let Some(Ok(line)) = lines.next() else {
81            return;
82        };
83
84        if line.is_empty() {
85            return;
86        };
87
88        let Some((first, rest)) = line.trim().split_once(|c: char| c.is_whitespace()) else {
89            match &line.chars().next() {
90                Some('c') => println!("{COMPONENT_PROMPT}"),
91                Some('s') => println!("{ENTITY_PROMPT}"),
92                Some('q') => println!("{QUERY_PROMPT}"),
93                Some('e') => println!("{EVENT_PROMPT}"),
94                Some('t') => println!("{EMIT_PROMPT}"),
95                _ => println!("{PROMPT}"),
96            }
97            continue;
98        };
99
100        match &first[0..1] {
101            "c" => {
102                rest.split(',').for_each(|component| {
103                    let mut component = component.split_whitespace();
104                    let Some(name) = component.next() else {
105                        return;
106                    };
107                    let size = match component.next().map(str::parse) {
108                        Some(Ok(size)) => size,
109                        _ => 0,
110                    };
111                    // Register our new component to the world with a layout specified by its size
112                    // SAFETY: [u64] is Send + Sync
113                    let id = world.register_component_with_descriptor(unsafe {
114                        ComponentDescriptor::new_with_layout(
115                            name.to_string(),
116                            StorageType::Table,
117                            Layout::array::<u64>(size).unwrap(),
118                            None,
119                            true,
120                            false,
121                            ComponentCloneBehavior::Default,
122                            None,
123                        )
124                    });
125                    let Some(info) = world.components().get_info(id) else {
126                        return;
127                    };
128                    component_names.insert(name.to_string(), id);
129                    component_info.insert(id, info.clone());
130                    println!("Component {} created with id: {}", name, id.index());
131                });
132            }
133            "s" => {
134                let mut to_insert_ids = Vec::new();
135                let mut to_insert_data = Vec::new();
136                rest.split(',').for_each(|component| {
137                    let mut component = component.split_whitespace();
138                    let Some(name) = component.next() else {
139                        return;
140                    };
141
142                    // Get the id for the component with the given name
143                    let Some(&id) = component_names.get(name) else {
144                        println!("Component {name} does not exist");
145                        return;
146                    };
147
148                    // Calculate the length for the array based on the layout created for this component id
149                    let info = world.components().get_info(id).unwrap();
150                    let len = info.layout().size() / size_of::<u64>();
151                    let mut values: Vec<u64> = component
152                        .take(len)
153                        .filter_map(|value| value.parse::<u64>().ok())
154                        .collect();
155                    values.resize(len, 0);
156
157                    // Collect the id and array to be inserted onto our entity
158                    to_insert_ids.push(id);
159                    to_insert_data.push(values);
160                });
161
162                let mut entity = world.spawn_empty();
163
164                // Construct an `OwningPtr` for each component in `to_insert_data`
165                let to_insert_ptr = to_owning_ptrs(&mut to_insert_data);
166
167                // SAFETY:
168                // - Component ids have been taken from the same world
169                // - Each array is created to the layout specified in the world
170                unsafe {
171                    entity.insert_by_ids(&to_insert_ids, to_insert_ptr.into_iter());
172                }
173
174                println!("Entity spawned with id: {}", entity.id());
175            }
176            "q" => {
177                let mut builder = QueryBuilder::<FilteredEntityMut>::new(&mut world);
178                parse_query(rest, &mut builder, &component_names);
179                let mut query = builder.build();
180                query.iter_mut(&mut world).for_each(|filtered_entity| {
181                    let terms = filtered_entity
182                        .access()
183                        .try_iter_access()
184                        .unwrap()
185                        .map(|component_access| {
186                            let id = *component_access.index();
187                            let ptr = filtered_entity.get_by_id(id).unwrap();
188                            let info = component_info.get(&id).unwrap();
189                            let len = info.layout().size() / size_of::<u64>();
190
191                            // SAFETY:
192                            // - All components are created with layout [u64]
193                            // - len is calculated from the component descriptor
194                            let data = unsafe {
195                                std::slice::from_raw_parts_mut(
196                                    ptr.assert_unique().as_ptr().cast::<u64>(),
197                                    len,
198                                )
199                            };
200
201                            // If we have write access, increment each value once
202                            if matches!(component_access, ComponentAccessKind::Exclusive(_)) {
203                                data.iter_mut().for_each(|data| {
204                                    *data += 1;
205                                });
206                            }
207
208                            format!("{}: {:?}", info.name(), data[0..len].to_vec())
209                        })
210                        .collect::<Vec<_>>()
211                        .join(", ");
212
213                    println!("{}: {}", filtered_entity.id(), terms);
214                });
215            }
216            "e" => {
217                rest.split(',').for_each(|event| {
218                    let name = event.trim();
219                    if name.is_empty() {
220                        return;
221                    }
222
223                    // Register a ComponentId for this event, no Rust type needed.
224                    // SAFETY: ZST with no drop
225                    let event_component_id = world.register_component_with_descriptor(unsafe {
226                        ComponentDescriptor::new_with_layout(
227                            format!("event:{name}"),
228                            StorageType::Table,
229                            Layout::new::<()>(),
230                            None,
231                            false,
232                            false,
233                            ComponentCloneBehavior::Ignore,
234                            None,
235                        )
236                    });
237                    // SAFETY: event_component_id was just registered for this event
238                    let event_key = unsafe { EventKey::new(event_component_id) };
239                    event_names.insert(name.to_string(), event_key);
240
241                    // Build a dynamic observer that prints when the event fires.
242                    let runner: ObserverRunner = |mut world, _observer, ctx, _event, _trigger| {
243                        println!("  Observer fired!");
244                        if let Some(mut counts) = world.get_resource_mut::<EventFireCount>() {
245                            *counts.0.entry(ctx.event_key).or_insert(0) += 1;
246                        }
247                    };
248
249                    // SAFETY: event_key was just registered, runner ignores pointers
250                    let observer =
251                        unsafe { Observer::with_dynamic_runner(runner).with_event_key(event_key) };
252                    world.spawn(observer);
253
254                    println!(
255                        "Event '{name}' registered (key: {}) with a dynamic observer",
256                        event_component_id.index()
257                    );
258                });
259
260                // Ensure the counter resource exists.
261                world.init_resource::<EventFireCount>();
262            }
263            "t" => {
264                let name = rest.trim();
265                let Some(&event_key) = event_names.get(name) else {
266                    println!(
267                        "Event '{name}' does not exist. Register it first with 'event {name}'"
268                    );
269                    continue;
270                };
271
272                let mut event_data = ();
273                let mut trigger_data = ();
274                // SAFETY: event_key was registered in this world, both pointers are valid ZSTs
275                unsafe {
276                    world.trigger_dynamic(
277                        event_key,
278                        PtrMut::from(&mut event_data),
279                        PtrMut::from(&mut trigger_data),
280                    );
281                }
282
283                let count = world
284                    .get_resource::<EventFireCount>()
285                    .map_or(0, |c| c.0.get(&event_key).copied().unwrap_or(0));
286                println!("Event '{name}' triggered ({count} fires)");
287            }
288            _ => continue,
289        }
290    }
291}
Source

pub fn to_vec_in<A>(&self, alloc: A) -> Vec<T, A>
where A: Allocator, T: Clone,

🔬This is a nightly-only experimental API. (allocator_ext)
Available on non-no_global_oom_handling only.

Copies self into a new Vec with an allocator.

§Examples
#![feature(allocator_ext)]

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.40.0 · Source

pub fn repeat(&self, n: usize) -> Vec<T>
where T: Copy,

Available on non-no_global_oom_handling only.

Creates a vector by copying a slice n times.

§Panics

This function will panic if the capacity would overflow.

§Examples
assert_eq!([1, 2].repeat(3), vec![1, 2, 1, 2, 1, 2]);

A panic upon overflow:

ⓘ
// this will panic at runtime
b"0123456789abcdef".repeat(usize::MAX);
1.0.0 · Source

pub fn concat<Item>(&self) -> <[T] as Concat<Item>>::Output ⓘ
where [T]: Concat<Item>, Item: ?Sized,

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 · Source

pub fn join<Separator>( &self, sep: Separator, ) -> <[T] as Join<Separator>>::Output ⓘ
where [T]: Join<Separator>,

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?
examples/gltf/load_gltf_extras.rs (line 89)
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
Hide additional examples
examples/ecs/relationships.rs (line 97)
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.iter() {
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    }
examples/testbed/ui.rs (line 937)
887    pub fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
888        commands.spawn((Camera2d, DespawnOnExit(super::Scene::FontLists)));
889        commands.insert_resource(LoadedFontAssets {
890            _handles: FONT_ASSETS
891                .iter()
892                .map(|font_asset| asset_server.load(*font_asset))
893                .collect(),
894        });
895        commands.spawn((
896            Node {
897                flex_direction: FlexDirection::Column,
898                align_self: AlignSelf::Center,
899                justify_self: JustifySelf::Center,
900                row_gap: px(25),
901                ..default()
902            },
903            DespawnOnExit(super::Scene::FontLists),
904            children![
905                (
906                    Text::new("Font Lists"),
907                    TextFont::from_font_size(FontSize::Px(32.)),
908                    Underline,
909                ),
910                (
911                    Node {
912                        flex_direction: FlexDirection::Column,
913                        row_gap: px(6),
914                        ..default()
915                    },
916                    children![
917                        Text::new("FontSource::Families"),
918                        (
919                            Node {
920                                flex_direction: FlexDirection::Row,
921                                flex_wrap: FlexWrap::Wrap,
922                                padding: px(16).left(),
923                                column_gap: px(30),
924                                row_gap: px(30),
925                                ..default()
926                            },
927                            Children::spawn(SpawnIter(
928                                (0..FONT_NAMES.len())
929                                    .map(|start| {
930                                        FONT_NAMES
931                                            .iter()
932                                            .copied()
933                                            .cycle()
934                                            .skip(start)
935                                            .take(FONT_NAMES.len())
936                                            .collect::<Vec<_>>()
937                                            .join(", ")
938                                    })
939                                    .map(|list| {
940                                        (
941                                            Text::new(list.replace(", ", "\n")),
942                                            TextFont {
943                                                font: FontSource::families(list),
944                                                font_size: FontSize::Px(16.),
945                                                ..default()
946                                            },
947                                            Node {
948                                                padding: px(4.).all(),
949                                                ..default()
950                                            },
951                                            TextLayout::no_wrap(),
952                                            Outline::default(),
953                                        )
954                                    }),
955                            )),
956                        )
957                    ]
958                ),
959                (
960                    Node {
961                        flex_direction: FlexDirection::Column,
962                        row_gap: px(6),
963                        ..default()
964                    },
965                    children![
966                        Text::new("FontSource::List"),
967                        (
968                            Node {
969                                flex_direction: FlexDirection::Row,
970                                flex_wrap: FlexWrap::Wrap,
971                                padding: px(16).left(),
972                                column_gap: px(30),
973                                row_gap: px(30),
974                                ..default()
975                            },
976                            Children::spawn(SpawnIter(
977                                (0..FONT_NAMES.len())
978                                    .map(|start| {
979                                        FONT_NAMES
980                                            .iter()
981                                            .copied()
982                                            .cycle()
983                                            .skip(start)
984                                            .take(FONT_NAMES.len())
985                                            .collect::<Vec<_>>()
986                                    })
987                                    .map(|list| {
988                                        (
989                                            Text::new(list.join("\n")),
990                                            TextFont {
991                                                font: FontSource::list(list.iter().copied()),
992                                                font_size: FontSize::Px(16.),
993                                                ..default()
994                                            },
995                                            Node {
996                                                padding: px(4.).all(),
997                                                ..default()
998                                            },
999                                            TextLayout::no_wrap(),
1000                                            Outline::default(),
1001                                        )
1002                                    }),
1003                            )),
1004                        )
1005                    ]
1006                ),
1007            ],
1008        ));
1009    }
examples/ecs/dynamic.rs (line 211)
69fn main() {
70    let mut world = World::new();
71    let mut lines = std::io::stdin().lines();
72    let mut component_names = HashMap::<String, ComponentId>::new();
73    let mut component_info = HashMap::<ComponentId, ComponentInfo>::new();
74    let mut event_names = HashMap::<String, EventKey>::new();
75
76    println!("{PROMPT}");
77    loop {
78        print!("\n> ");
79        let _ = std::io::stdout().flush();
80        let Some(Ok(line)) = lines.next() else {
81            return;
82        };
83
84        if line.is_empty() {
85            return;
86        };
87
88        let Some((first, rest)) = line.trim().split_once(|c: char| c.is_whitespace()) else {
89            match &line.chars().next() {
90                Some('c') => println!("{COMPONENT_PROMPT}"),
91                Some('s') => println!("{ENTITY_PROMPT}"),
92                Some('q') => println!("{QUERY_PROMPT}"),
93                Some('e') => println!("{EVENT_PROMPT}"),
94                Some('t') => println!("{EMIT_PROMPT}"),
95                _ => println!("{PROMPT}"),
96            }
97            continue;
98        };
99
100        match &first[0..1] {
101            "c" => {
102                rest.split(',').for_each(|component| {
103                    let mut component = component.split_whitespace();
104                    let Some(name) = component.next() else {
105                        return;
106                    };
107                    let size = match component.next().map(str::parse) {
108                        Some(Ok(size)) => size,
109                        _ => 0,
110                    };
111                    // Register our new component to the world with a layout specified by its size
112                    // SAFETY: [u64] is Send + Sync
113                    let id = world.register_component_with_descriptor(unsafe {
114                        ComponentDescriptor::new_with_layout(
115                            name.to_string(),
116                            StorageType::Table,
117                            Layout::array::<u64>(size).unwrap(),
118                            None,
119                            true,
120                            false,
121                            ComponentCloneBehavior::Default,
122                            None,
123                        )
124                    });
125                    let Some(info) = world.components().get_info(id) else {
126                        return;
127                    };
128                    component_names.insert(name.to_string(), id);
129                    component_info.insert(id, info.clone());
130                    println!("Component {} created with id: {}", name, id.index());
131                });
132            }
133            "s" => {
134                let mut to_insert_ids = Vec::new();
135                let mut to_insert_data = Vec::new();
136                rest.split(',').for_each(|component| {
137                    let mut component = component.split_whitespace();
138                    let Some(name) = component.next() else {
139                        return;
140                    };
141
142                    // Get the id for the component with the given name
143                    let Some(&id) = component_names.get(name) else {
144                        println!("Component {name} does not exist");
145                        return;
146                    };
147
148                    // Calculate the length for the array based on the layout created for this component id
149                    let info = world.components().get_info(id).unwrap();
150                    let len = info.layout().size() / size_of::<u64>();
151                    let mut values: Vec<u64> = component
152                        .take(len)
153                        .filter_map(|value| value.parse::<u64>().ok())
154                        .collect();
155                    values.resize(len, 0);
156
157                    // Collect the id and array to be inserted onto our entity
158                    to_insert_ids.push(id);
159                    to_insert_data.push(values);
160                });
161
162                let mut entity = world.spawn_empty();
163
164                // Construct an `OwningPtr` for each component in `to_insert_data`
165                let to_insert_ptr = to_owning_ptrs(&mut to_insert_data);
166
167                // SAFETY:
168                // - Component ids have been taken from the same world
169                // - Each array is created to the layout specified in the world
170                unsafe {
171                    entity.insert_by_ids(&to_insert_ids, to_insert_ptr.into_iter());
172                }
173
174                println!("Entity spawned with id: {}", entity.id());
175            }
176            "q" => {
177                let mut builder = QueryBuilder::<FilteredEntityMut>::new(&mut world);
178                parse_query(rest, &mut builder, &component_names);
179                let mut query = builder.build();
180                query.iter_mut(&mut world).for_each(|filtered_entity| {
181                    let terms = filtered_entity
182                        .access()
183                        .try_iter_access()
184                        .unwrap()
185                        .map(|component_access| {
186                            let id = *component_access.index();
187                            let ptr = filtered_entity.get_by_id(id).unwrap();
188                            let info = component_info.get(&id).unwrap();
189                            let len = info.layout().size() / size_of::<u64>();
190
191                            // SAFETY:
192                            // - All components are created with layout [u64]
193                            // - len is calculated from the component descriptor
194                            let data = unsafe {
195                                std::slice::from_raw_parts_mut(
196                                    ptr.assert_unique().as_ptr().cast::<u64>(),
197                                    len,
198                                )
199                            };
200
201                            // If we have write access, increment each value once
202                            if matches!(component_access, ComponentAccessKind::Exclusive(_)) {
203                                data.iter_mut().for_each(|data| {
204                                    *data += 1;
205                                });
206                            }
207
208                            format!("{}: {:?}", info.name(), data[0..len].to_vec())
209                        })
210                        .collect::<Vec<_>>()
211                        .join(", ");
212
213                    println!("{}: {}", filtered_entity.id(), terms);
214                });
215            }
216            "e" => {
217                rest.split(',').for_each(|event| {
218                    let name = event.trim();
219                    if name.is_empty() {
220                        return;
221                    }
222
223                    // Register a ComponentId for this event, no Rust type needed.
224                    // SAFETY: ZST with no drop
225                    let event_component_id = world.register_component_with_descriptor(unsafe {
226                        ComponentDescriptor::new_with_layout(
227                            format!("event:{name}"),
228                            StorageType::Table,
229                            Layout::new::<()>(),
230                            None,
231                            false,
232                            false,
233                            ComponentCloneBehavior::Ignore,
234                            None,
235                        )
236                    });
237                    // SAFETY: event_component_id was just registered for this event
238                    let event_key = unsafe { EventKey::new(event_component_id) };
239                    event_names.insert(name.to_string(), event_key);
240
241                    // Build a dynamic observer that prints when the event fires.
242                    let runner: ObserverRunner = |mut world, _observer, ctx, _event, _trigger| {
243                        println!("  Observer fired!");
244                        if let Some(mut counts) = world.get_resource_mut::<EventFireCount>() {
245                            *counts.0.entry(ctx.event_key).or_insert(0) += 1;
246                        }
247                    };
248
249                    // SAFETY: event_key was just registered, runner ignores pointers
250                    let observer =
251                        unsafe { Observer::with_dynamic_runner(runner).with_event_key(event_key) };
252                    world.spawn(observer);
253
254                    println!(
255                        "Event '{name}' registered (key: {}) with a dynamic observer",
256                        event_component_id.index()
257                    );
258                });
259
260                // Ensure the counter resource exists.
261                world.init_resource::<EventFireCount>();
262            }
263            "t" => {
264                let name = rest.trim();
265                let Some(&event_key) = event_names.get(name) else {
266                    println!(
267                        "Event '{name}' does not exist. Register it first with 'event {name}'"
268                    );
269                    continue;
270                };
271
272                let mut event_data = ();
273                let mut trigger_data = ();
274                // SAFETY: event_key was registered in this world, both pointers are valid ZSTs
275                unsafe {
276                    world.trigger_dynamic(
277                        event_key,
278                        PtrMut::from(&mut event_data),
279                        PtrMut::from(&mut trigger_data),
280                    );
281                }
282
283                let count = world
284                    .get_resource::<EventFireCount>()
285                    .map_or(0, |c| c.0.get(&event_key).copied().unwrap_or(0));
286                println!("Event '{name}' triggered ({count} fires)");
287            }
288            _ => continue,
289        }
290    }
291}
1.0.0 · Source

pub fn connect<Separator>( &self, sep: Separator, ) -> <[T] as Join<Separator>>::Output ⓘ
where [T]: Join<Separator>,

👎Deprecated since 1.3.0:

renamed to join

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 Default for BindingResources

Source§

fn default() -> BindingResources

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

impl Deref for BindingResources

Source§

type Target = Vec<(u32, OwnedBindingResource)>

The resulting type after dereferencing.
Source§

fn deref(&self) -> &<BindingResources as Deref>::Target

Dereferences the value.
Source§

impl DerefMut for BindingResources

Source§

fn deref_mut(&mut self) -> &mut <BindingResources as Deref>::Target

Mutably dereferences the value.

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T, U> AsBindGroupShaderType<U> for T
where U: ShaderType, &'a T: for<'a> Into<U>,

Source§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U

Return the T ShaderType for self. When used in AsBindGroup derives, it is safe to assume that all images in self exist.
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> ConditionalSend for T
where T: Send,

Source§

impl<T> Conv for T

Source§

fn conv<T>(self) -> T
where Self: Into<T>,

Converts self into T using Into<T>. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts 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>

Converts 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)

Converts &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)

Converts &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 T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert 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>

Convert 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)

Convert &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)

Convert &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
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send> ⓘ

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> FmtForward for T

Source§

fn fmt_binary(self) -> FmtBinary<Self>
where Self: Binary,

Causes self to use its Binary implementation when Debug-formatted.
Source§

fn fmt_display(self) -> FmtDisplay<Self>
where Self: Display,

Causes self to use its Display implementation when Debug-formatted.
Source§

fn fmt_lower_exp(self) -> FmtLowerExp<Self>
where Self: LowerExp,

Causes self to use its LowerExp implementation when Debug-formatted.
Source§

fn fmt_lower_hex(self) -> FmtLowerHex<Self>
where Self: LowerHex,

Causes self to use its LowerHex implementation when Debug-formatted.
Source§

fn fmt_octal(self) -> FmtOctal<Self>
where Self: Octal,

Causes self to use its Octal implementation when Debug-formatted.
Source§

fn fmt_pointer(self) -> FmtPointer<Self>
where Self: Pointer,

Causes self to use its Pointer implementation when Debug-formatted.
Source§

fn fmt_upper_exp(self) -> FmtUpperExp<Self>
where Self: UpperExp,

Causes self to use its UpperExp implementation when Debug-formatted.
Source§

fn fmt_upper_hex(self) -> FmtUpperHex<Self>
where Self: UpperHex,

Causes self to use its UpperHex implementation when Debug-formatted.
Source§

fn fmt_list(self) -> FmtList<Self>
where &'a Self: for<'a> IntoIterator,

Formats each item in a sequence. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S> FromSample<S> for S

Source§

fn from_sample_(s: S) -> S

Source§

impl<T> FromWorld for T
where T: Default,

Source§

fn from_world(_world: &mut World) -> T

Creates Self using default().

Source§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

Source§

const WITNESS: W = W::MAKE

A constant of the type witness
Source§

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

Source§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
Source§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
Source§

impl<T> InitializeFromFunction<T> for T

Source§

fn initialize_from_function(f: fn() -> T) -> T

Create an instance of this type from an initialization function
Source§

impl<T> Instrument for T

Source§

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

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

fn in_current_span(self) -> Instrumented<Self> ⓘ

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

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

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts 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 more
Source§

impl<T> IntoResult<T> for T

Source§

fn into_result(self) -> Result<T, RunSystemError>

Converts this type into the system output type.
Source§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

Source§

fn into_sample(self) -> T

Source§

impl<A> Is for A
where A: Any,

Source§

fn is<T>() -> bool
where T: Any,

Checks if the current type “is” another type, using a TypeId equality comparison. This is most useful in the context of generic logic. Read more
Source§

impl<T> NoneValue for T
where T: Default,

Source§

type NoneType = T

Source§

fn null_value() -> T

The none-equivalent value.
Source§

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

Source§

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R
where Self: Sized,

Pipes by value. This is generally the method you want to use. Read more
Source§

fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> R
where R: 'a,

Borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> R
where R: 'a,

Mutably borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
where Self: Borrow<B>, B: 'a + ?Sized, R: 'a,

Borrows self, then passes self.borrow() into the pipe function. Read more
Source§

fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
where Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Source§

fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
where Self: AsRef<U>, U: 'a + ?Sized, R: 'a,

Borrows 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
where Self: AsMut<U>, U: 'a + ?Sized, R: 'a,

Mutably borrows 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
where Self: Deref<Target = T>, T: 'a + ?Sized, R: 'a,

Borrows self, then passes self.deref() into the pipe function.
Source§

fn pipe_deref_mut<'a, T, R>( &'a mut self, func: impl FnOnce(&'a mut T) -> R, ) -> R
where Self: DerefMut<Target = T> + Deref, T: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.deref_mut() into the pipe function.
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

Source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
Source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
Source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> Settings for T
where T: 'static + Send + Sync,

Source§

impl<Ret> SpawnIfAsync<(), Ret> for Ret

Source§

fn spawn(self) -> Ret

Spawn the value into the dioxus runtime if it is an async block
Source§

impl<T, O> SuperFrom<T> for O
where O: From<T>,

Source§

fn super_from(input: T) -> O

Convert from a type to another type.
Source§

impl<T, O, M> SuperInto<O, M> for T
where O: SuperFrom<T, M>,

Source§

fn super_into(self) -> O

Convert from a type to another type.
Source§

impl<T> Tap for T

Source§

fn tap(self, func: impl FnOnce(&Self)) -> Self

Immutable access to a value. Read more
Source§

fn tap_mut(self, func: impl FnOnce(&mut Self)) -> Self

Mutable access to a value. Read more
Source§

fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Immutable access to the Borrow<B> of a value. Read more
Source§

fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Mutable access to the BorrowMut<B> of a value. Read more
Source§

fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Immutable access to the AsRef<R> view of a value. Read more
Source§

fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Mutable access to the AsMut<R> view of a value. Read more
Source§

fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Immutable access to the Deref::Target of a value. Read more
Source§

fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Mutable access to the Deref::Target of a value. Read more
Source§

fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self

Calls .tap() only in debug builds, and is erased in release builds.
Source§

fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self

Calls .tap_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Calls .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
where Self: BorrowMut<B>, B: ?Sized,

Calls .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
where Self: AsRef<R>, R: ?Sized,

Calls .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
where Self: AsMut<R>, R: ?Sized,

Calls .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
where Self: Deref<Target = T>, T: ?Sized,

Calls .tap_deref() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
Source§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

Source§

fn to_sample_(self) -> U

Source§

impl<T> TryConv for T

Source§

fn try_conv<T>(self) -> Result<T, Self::Error>
where Self: TryInto<T>,

Attempts to convert self into T using TryInto<T>. Read more
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

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

Source§

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

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

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

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,

Source§

impl<T> WithSubscriber for T

Source§

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

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

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

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