Skip to main content

TextSpan

Struct TextSpan 

Source
pub struct TextSpan(pub String);
Expand description

A span of text in a tree of spans.

A TextSpan is only valid when it exists as a child of a parent that has either Text or Text2d. The parent’s Text / Text2d component contains the base text content. Any children with TextSpan extend this text by appending their content to the parent’s text in sequence to form a ComputedTextBlock. The parent’s TextLayout determines the layout of the block but each node has its own TextFont and TextColor.

Tuple Fields§

§0: String

Implementations§

Source§

impl TextSpan

Source

pub fn new(text: impl Into<String>) -> TextSpan

Makes a new text span component.

Examples found in repository?
examples/3d/motion_blur.rs (line 249)
237fn setup_ui(mut commands: Commands) {
238    commands.spawn((
239        Text::default(),
240        Node {
241            position_type: PositionType::Absolute,
242            top: px(12),
243            left: px(12),
244            ..default()
245        },
246        children![
247            TextSpan::default(),
248            TextSpan::default(),
249            TextSpan::new("1/2: -/+ shutter angle (blur amount)\n"),
250            TextSpan::new("3/4: -/+ sample count (blur quality)\n"),
251            TextSpan::new("Spacebar: cycle camera\n"),
252        ],
253    ));
254}
More examples
Hide additional examples
examples/ecs/one_shot_systems.rs (line 103)
92fn setup_ui(mut commands: Commands) {
93    commands.spawn(Camera2d);
94    commands.spawn((
95        Text::default(),
96        TextLayout::justify(Justify::Center),
97        Node {
98            align_self: AlignSelf::Center,
99            justify_self: JustifySelf::Center,
100            ..default()
101        },
102        children![
103            (TextSpan::new("Press A or B to trigger a one-shot system\n")),
104            (TextSpan::new("Last Triggered: ")),
105            (
106                TextSpan::new("-"),
107                TextColor(bevy::color::palettes::css::ORANGE.into()),
108            )
109        ],
110    ));
111}
examples/app/log_layers_ecs.rs (line 157)
144fn print_logs(
145    mut log_message_reader: MessageReader<LogMessage>,
146    mut commands: Commands,
147    log_viewer_root: Single<Entity, With<LogViewerRoot>>,
148) {
149    let root_entity = *log_viewer_root;
150
151    commands.entity(root_entity).with_children(|child| {
152        for log_message in log_message_reader.read() {
153            child.spawn((
154                Text::default(),
155                children![
156                    (
157                        TextSpan::new(format!("{:5} ", log_message.level)),
158                        TextColor(level_color(&log_message.level)),
159                    ),
160                    TextSpan::new(&log_message.message),
161                ],
162            ));
163        }
164    });
165}
examples/window/window_drag_move.rs (lines 74-76)
58fn setup(mut commands: Commands) {
59    // Camera
60    commands.spawn(Camera3d::default());
61
62    // UI
63    commands.spawn((
64        Node {
65            position_type: PositionType::Absolute,
66            padding: UiRect::all(px(5)),
67            ..default()
68        },
69        BackgroundColor(Color::BLACK.with_alpha(0.75)),
70        GlobalZIndex(i32::MAX),
71        children![(
72            Text::default(),
73            children![
74                TextSpan::new(
75                    "Demonstrate drag move and drag resize without window decorations.\n\n",
76                ),
77                TextSpan::new("Controls:\n"),
78                TextSpan::new("A - change left click action ["),
79                TextSpan::new("Move"),
80                TextSpan::new("]\n"),
81                TextSpan::new("S / D - change resize direction ["),
82                TextSpan::new("NorthWest"),
83                TextSpan::new("]\n"),
84            ]
85        )],
86    ));
87}
examples/math/render_primitives.rs (line 383)
365fn setup_text(mut commands: Commands, cameras: Query<(Entity, &Camera)>) {
366    let active_camera = cameras
367        .iter()
368        .find_map(|(entity, camera)| camera.is_active.then_some(entity))
369        .expect("run condition ensures existence");
370    commands.spawn((
371        HeaderNode,
372        Node {
373            justify_self: JustifySelf::Center,
374            top: px(5),
375            ..Default::default()
376        },
377        UiTargetCamera(active_camera),
378        children![(
379            Text::default(),
380            HeaderText,
381            TextLayout::justify(Justify::Center),
382            children![
383                TextSpan::new("Primitive: "),
384                TextSpan(format!("{text}", text = PrimitiveSelected::default())),
385                TextSpan::new("\n\n"),
386                TextSpan::new(
387                    "Press 'C' to switch between 2D and 3D mode\n\
388                    Press 'Up' or 'Down' to switch to the next/previous primitive",
389                ),
390                TextSpan::new("\n\n"),
391                TextSpan::new("(If nothing is displayed, there's no rendering support yet)",),
392            ]
393        )],
394    ));
395}
examples/window/low_power.rs (line 199)
167    pub fn setup(
168        mut commands: Commands,
169        mut meshes: ResMut<Assets<Mesh>>,
170        mut materials: ResMut<Assets<StandardMaterial>>,
171        mut request_redraw_writer: MessageWriter<RequestRedraw>,
172    ) {
173        commands.spawn((
174            Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))),
175            MeshMaterial3d(materials.add(Color::srgb(0.8, 0.7, 0.6))),
176            Rotator,
177        ));
178
179        commands.spawn((
180            DirectionalLight::default(),
181            Transform::from_xyz(1.0, 1.0, 1.0).looking_at(Vec3::ZERO, Vec3::Y),
182        ));
183        commands.spawn((
184            Camera3d::default(),
185            Transform::from_xyz(-2.0, 2.0, 2.0).looking_at(Vec3::ZERO, Vec3::Y),
186        ));
187        request_redraw_writer.write(RequestRedraw);
188        commands.spawn((
189            Text::default(),
190            Node {
191                align_self: AlignSelf::FlexStart,
192                position_type: PositionType::Absolute,
193                top: px(12),
194                left: px(12),
195                ..default()
196            },
197            ModeText,
198            children![
199                TextSpan::new("Press space bar to cycle modes\n"),
200                (TextSpan::default(), TextColor(LIME.into())),
201                (TextSpan::new("\nFrame: "), TextColor(YELLOW.into())),
202                (TextSpan::new(""), TextColor(YELLOW.into())),
203            ],
204        ));
205    }

Methods from Deref<Target = String>§

1.7.0 · Source

pub fn as_str(&self) -> &str

Extracts a string slice containing the entire String.

§Examples
let s = String::from("foo");

assert_eq!("foo", s.as_str());
Examples found in repository?
examples/time/time.rs (line 44)
35fn runner(mut app: App) -> AppExit {
36    banner();
37    help();
38    let stdin = io::stdin();
39    for line in stdin.lock().lines() {
40        if let Err(err) = line {
41            println!("read err: {err:#}");
42            break;
43        }
44        match line.unwrap().as_str() {
45            "" => {
46                app.update();
47            }
48            "f" => {
49                println!("FAST: setting relative speed to 2x");
50                app.world_mut()
51                    .resource_mut::<Time<Virtual>>()
52                    .set_relative_speed(2.0);
53            }
54            "n" => {
55                println!("NORMAL: setting relative speed to 1x");
56                app.world_mut()
57                    .resource_mut::<Time<Virtual>>()
58                    .set_relative_speed(1.0);
59            }
60            "s" => {
61                println!("SLOW: setting relative speed to 0.5x");
62                app.world_mut()
63                    .resource_mut::<Time<Virtual>>()
64                    .set_relative_speed(0.5);
65            }
66            "p" => {
67                println!("PAUSE: pausing virtual clock");
68                app.world_mut().resource_mut::<Time<Virtual>>().pause();
69            }
70            "u" => {
71                println!("UNPAUSE: resuming virtual clock");
72                app.world_mut().resource_mut::<Time<Virtual>>().unpause();
73            }
74            "q" => {
75                println!("QUITTING!");
76                break;
77            }
78            _ => {
79                help();
80            }
81        }
82    }
83
84    AppExit::Success
85}
More examples
Hide additional examples
examples/gltf/edit_material_on_gltf.rs (line 83)
55fn change_material(
56    scene_ready: On<WorldInstanceReady>,
57    mut commands: Commands,
58    children: Query<&Children>,
59    color_override: Query<&ColorOverride>,
60    mesh_materials: Query<(&MeshMaterial3d<StandardMaterial>, &GltfMaterialName)>,
61    mut asset_materials: ResMut<Assets<StandardMaterial>>,
62) {
63    info!("processing Scene Entity: {}", scene_ready.entity);
64
65    // Get the `ColorOverride` of the entity, if it does not have a color override, return
66    let Ok(color_override) = color_override.get(scene_ready.entity) else {
67        info!("{} does not have a color override", scene_ready.entity);
68        return;
69    };
70
71    // Iterate over all children recursively
72    for descendant in children.iter_descendants(scene_ready.entity) {
73        // Get the material id and name which were created from the glTF file information
74        let Ok((id, material_name)) = mesh_materials.get(descendant) else {
75            continue;
76        };
77        // Get the material of the descendant
78        let Some(material) = asset_materials.get(id.id()) else {
79            continue;
80        };
81
82        // match on the material name, modifying the materials as necessary
83        match material_name.0.as_str() {
84            "LeatherPartsMat" => {
85                info!("editing LeatherPartsMat to use ColorOverride tint");
86                // Create a copy of the material and override base color
87                // If you intend on creating multiple models with the same tint, it
88                // is best to cache the handle somewhere, as having multiple materials
89                // that are identical is expensive
90                let mut new_material = material.clone();
91                new_material.base_color = color_override.0;
92
93                // Override `MeshMaterial3d` with new material
94                commands
95                    .entity(descendant)
96                    .insert(MeshMaterial3d(asset_materials.add(new_material)));
97            }
98            name => {
99                info!("not replacing: {name}");
100            }
101        }
102    }
103}
examples/3d/solari.rs (line 434)
384fn add_raytracing_meshes_on_scene_load(
385    scene_ready: On<WorldInstanceReady>,
386    children: Query<&Children>,
387    mesh_query: Query<(
388        &Mesh3d,
389        &MeshMaterial3d<StandardMaterial>,
390        Option<&GltfMaterialName>,
391    )>,
392    mut meshes: ResMut<Assets<Mesh>>,
393    mut materials: ResMut<Assets<StandardMaterial>>,
394    mut commands: Commands,
395    args: Res<Args>,
396) {
397    for descendant in children.iter_descendants(scene_ready.entity) {
398        if let Ok((Mesh3d(mesh_handle), MeshMaterial3d(material_handle), material_name)) =
399            mesh_query.get(descendant)
400        {
401            // Add raytracing mesh component
402            commands
403                .entity(descendant)
404                .insert(RaytracingMesh3d(mesh_handle.clone()));
405
406            // Ensure meshes are Solari compatible
407            let mut mesh = meshes.get_mut(mesh_handle).unwrap();
408            if !mesh.contains_attribute(Mesh::ATTRIBUTE_UV_0) {
409                let vertex_count = mesh.count_vertices();
410                mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, vec![[0.0, 0.0]; vertex_count]);
411                mesh.insert_attribute(
412                    Mesh::ATTRIBUTE_TANGENT,
413                    vec![[0.0, 0.0, 0.0, 0.0]; vertex_count],
414                );
415            }
416            if !mesh.contains_attribute(Mesh::ATTRIBUTE_TANGENT) {
417                mesh.generate_tangents().unwrap();
418            }
419            if mesh.contains_attribute(Mesh::ATTRIBUTE_UV_1) {
420                mesh.remove_attribute(Mesh::ATTRIBUTE_UV_1);
421            }
422            if let Some(indices) = mesh.indices_mut()
423                && let Indices::U16(_) = indices
424            {
425                *indices = Indices::U32(indices.iter().map(|i| i as u32).collect());
426            }
427
428            // Prevent rasterization if using pathtracer
429            if args.pathtracer == Some(true) {
430                commands.entity(descendant).remove::<Mesh3d>();
431            }
432
433            // Adjust scene materials to better demo Solari features
434            if material_name.map(|s| s.0.as_str()) == Some("material") {
435                let mut material = materials.get_mut(material_handle).unwrap();
436                material.emissive = LinearRgba::BLACK;
437            }
438            if material_name.map(|s| s.0.as_str()) == Some("Lights") {
439                let mut material = materials.get_mut(material_handle).unwrap();
440                material.emissive =
441                    LinearRgba::from(Color::srgb(0.941, 0.714, 0.043)) * 1_000_000.0;
442                material.alpha_mode = AlphaMode::Opaque;
443                material.specular_transmission = 0.0;
444
445                commands.insert_resource(RobotLightMaterial(material_handle.clone()));
446            }
447            if material_name.map(|s| s.0.as_str()) == Some("Glass_Dark_01") {
448                let mut material = materials.get_mut(material_handle).unwrap();
449                material.alpha_mode = AlphaMode::Opaque;
450                material.specular_transmission = 0.0;
451            }
452        }
453    }
454}
examples/3d/tonemapping.rs (line 541)
395fn update_ui(
396    mut text_query: Single<&mut Text, Without<SceneNumber>>,
397    settings: Single<(&Tonemapping, &ColorGrading)>,
398    current_scene: Res<CurrentScene>,
399    selected_parameter: Res<SelectedParameter>,
400    mut hide_ui: Local<bool>,
401    keys: Res<ButtonInput<KeyCode>>,
402) {
403    if keys.just_pressed(KeyCode::KeyH) {
404        *hide_ui = !*hide_ui;
405    }
406
407    if *hide_ui {
408        if !text_query.is_empty() {
409            // single_mut() always triggers change detection,
410            // so only access if text actually needs changing
411            text_query.clear();
412        }
413        return;
414    }
415
416    let (tonemapping, color_grading) = *settings;
417    let tonemapping = *tonemapping;
418
419    let mut text = String::with_capacity(text_query.len());
420
421    let scn = current_scene.0;
422    text.push_str("(H) Hide UI\n\n");
423    text.push_str("Test Scene: \n");
424    text.push_str(&format!(
425        "(Q) {} Basic Scene\n",
426        if scn == 1 { ">" } else { "" }
427    ));
428    text.push_str(&format!(
429        "(W) {} Color Sweep\n",
430        if scn == 2 { ">" } else { "" }
431    ));
432    text.push_str(&format!(
433        "(E) {} Image Viewer\n",
434        if scn == 3 { ">" } else { "" }
435    ));
436
437    text.push_str("\n\nTonemapping Method:\n");
438    text.push_str(&format!(
439        "(1) {} Linear\n",
440        if tonemapping == Tonemapping::Linear {
441            ">"
442        } else {
443            ""
444        }
445    ));
446    text.push_str(&format!(
447        "(2) {} Reinhard\n",
448        if tonemapping == Tonemapping::Reinhard {
449            "> "
450        } else {
451            ""
452        }
453    ));
454    text.push_str(&format!(
455        "(3) {} Reinhard Luminance\n",
456        if tonemapping == Tonemapping::ReinhardLuminance {
457            ">"
458        } else {
459            ""
460        }
461    ));
462    text.push_str(&format!(
463        "(4) {} ACES Fitted\n",
464        if tonemapping == Tonemapping::AcesFitted {
465            ">"
466        } else {
467            ""
468        }
469    ));
470    text.push_str(&format!(
471        "(5) {} AgX\n",
472        if tonemapping == Tonemapping::AgX {
473            ">"
474        } else {
475            ""
476        }
477    ));
478    text.push_str(&format!(
479        "(6) {} SomewhatBoringDisplayTransform\n",
480        if tonemapping == Tonemapping::SomewhatBoringDisplayTransform {
481            ">"
482        } else {
483            ""
484        }
485    ));
486    text.push_str(&format!(
487        "(7) {} TonyMcMapface\n",
488        if tonemapping == Tonemapping::TonyMcMapface {
489            ">"
490        } else {
491            ""
492        }
493    ));
494    text.push_str(&format!(
495        "(8) {} Blender Filmic\n",
496        if tonemapping == Tonemapping::BlenderFilmic {
497            ">"
498        } else {
499            ""
500        }
501    ));
502    text.push_str(&format!(
503        "(9) {} Khronos PBR Neutral\n",
504        if tonemapping == Tonemapping::KhronosPbrNeutral {
505            ">"
506        } else {
507            ""
508        }
509    ));
510
511    text.push_str("\n\nColor Grading:\n");
512    text.push_str("(arrow keys)\n");
513    if selected_parameter.value == 0 {
514        text.push_str("> ");
515    }
516    text.push_str(&format!("Exposure: {:.2}\n", color_grading.global.exposure));
517    if selected_parameter.value == 1 {
518        text.push_str("> ");
519    }
520    text.push_str(&format!("Gamma: {:.2}\n", color_grading.shadows.gamma));
521    if selected_parameter.value == 2 {
522        text.push_str("> ");
523    }
524    text.push_str(&format!(
525        "PreSaturation: {:.2}\n",
526        color_grading.shadows.saturation
527    ));
528    if selected_parameter.value == 3 {
529        text.push_str("> ");
530    }
531    text.push_str(&format!(
532        "PostSaturation: {:.2}\n",
533        color_grading.global.post_saturation
534    ));
535    text.push_str("(Space) Reset all to default\n");
536
537    if current_scene.0 == 1 {
538        text.push_str("(Enter) Reset all to scene recommendation\n");
539    }
540
541    if text != text_query.as_str() {
542        // single_mut() always triggers change detection,
543        // so only access if text actually changed
544        text_query.0 = text;
545    }
546}
1.7.0 · Source

pub fn as_mut_str(&mut self) -> &mut str

Converts a String into a mutable string slice.

§Examples
let mut s = String::from("foobar");
let s_mut_str = s.as_mut_str();

s_mut_str.make_ascii_uppercase();

assert_eq!("FOOBAR", s_mut_str);
1.0.0 · Source

pub fn push_str(&mut self, string: &str)

Available on non-no_global_oom_handling only.

Appends a given string slice onto the end of this String.

§Panics

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

§Examples
let mut s = String::from("foo");

s.push_str("bar");

assert_eq!("foobar", s);
Examples found in repository?
examples/stress_tests/many_text.rs (line 218)
214fn update_lorem_text(mut lorem_text_query: Query<(&mut Text, &mut Lorem)>) {
215    for (mut text, mut lorem) in &mut lorem_text_query {
216        if lorem.0 {
217            text.0.clear();
218            text.0.push_str(LOREM_TEXT_1);
219        } else {
220            text.0.clear();
221            text.0.push_str(LOREM_TEXT_2);
222        }
223
224        lorem.0 = !lorem.0;
225    }
226}
More examples
Hide additional examples
examples/math/bounding_2d.rs (line 82)
75fn update_text(mut text: Single<&mut Text>, cur_state: Res<State<Test>>) {
76    if !cur_state.is_changed() {
77        return;
78    }
79
80    text.clear();
81
82    text.push_str("Intersection test:\n");
83    use Test::*;
84    for &test in &[AabbSweep, CircleSweep, RayCast, AabbCast, CircleCast] {
85        let s = if **cur_state == test { "*" } else { " " };
86        text.push_str(&format!(" {s} {test:?} {s}\n"));
87    }
88    text.push_str("\nPress space to cycle");
89}
examples/shader_advanced/fullscreen_material.rs (line 105)
93fn toggle_effect(
94    mut text: Single<&mut Text>,
95    keys: Res<ButtonInput<KeyCode>>,
96    camera: Single<(Entity, Option<&FullscreenEffect>), With<Camera3d>>,
97    mut commands: Commands,
98) {
99    if keys.just_pressed(KeyCode::KeyT) {
100        let (entity, effect) = *camera;
101
102        if effect.is_some() {
103            commands.entity(entity).remove::<FullscreenEffect>();
104            text.clear();
105            text.push_str("(T) FullscreenEffect: Off");
106        } else {
107            commands.entity(entity).insert(FullscreenEffect::new(0.0));
108            text.clear();
109            text.push_str("(T) FullscreenEffect: On");
110        }
111    }
112}
examples/ecs/entity_disabling.rs (line 68)
59fn list_all_named_entities(
60    query: Query<&Name>,
61    mut name_text_query: Query<&mut Text, With<EntityNameText>>,
62    mut commands: Commands,
63) {
64    let mut text_string = String::from("Named entities found:\n");
65    // Query iteration order is not guaranteed, so we sort the names
66    // to ensure the output is consistent.
67    for name in query.iter().sort::<&Name>() {
68        text_string.push_str(&format!("{name:?}\n"));
69    }
70
71    if let Ok(mut text) = name_text_query.single_mut() {
72        *text = Text::new(text_string);
73    } else {
74        commands.spawn((
75            EntityNameText,
76            Text::default(),
77            Node {
78                position_type: PositionType::Absolute,
79                top: px(12),
80                right: px(12),
81                ..default()
82            },
83        ));
84    }
85}
examples/ui/images/image_node_resizing.rs (lines 229-232)
219fn update_text(
220    event: On<TextUpdate>,
221    mut textmeta: Single<&mut TextData>,
222    mut text: Single<&mut Text>,
223) {
224    let mut new_text = Text::new(TEXT_PREFIX);
225    match event.direction {
226        Direction::Height => {
227            textmeta.height = (textmeta.height + event.change)
228                .clamp(IMAGE_GROUP_BOX_MIN_HEIGHT, IMAGE_GROUP_BOX_MAX_HEIGHT);
229            new_text.push_str(&format!(
230                "height : {}%, width : {}%",
231                textmeta.height, textmeta.width
232            ));
233        }
234        Direction::Width => {
235            textmeta.width = (textmeta.width + event.change)
236                .clamp(IMAGE_GROUP_BOX_MIN_WIDTH, IMAGE_GROUP_BOX_MAX_WIDTH);
237            new_text.push_str(&format!(
238                "height : {}%, width : {}%",
239                textmeta.height, textmeta.width
240            ));
241        }
242    }
243    text.0 = new_text.0;
244}
examples/3d/light_probe_blending.rs (lines 593-595)
588fn set_help_text(app_status: &AppStatus, help_text_query: &mut Query<&mut Text, With<HelpText>>) {
589    for mut ui_text in help_text_query {
590        let mut help_text = String::new();
591        match app_status.camera_mode {
592            CameraMode::Orbit => {
593                help_text.push_str(
594                    "Click and drag to orbit the camera\nUse the mouse wheel to zoom the camera\n",
595                );
596            }
597            CameraMode::Free => {
598                help_text.push_str(
599                    "Click and drag to rotate the camera\nUse WASDEQ to move the camera\n",
600                );
601            }
602        }
603
604        help_text.push('\n');
605
606        if matches!(app_status.gizmos_enabled, GizmosEnabled::On) {
607            help_text.push_str(
608                "\
609Gizmos:
610Tan: Light probe bounds
611Red: Light probe falloff bounds
612Blue: Parallax correction bounds",
613            );
614        }
615
616        *ui_text = Text::new(help_text);
617    }
618}
1.87.0 · Source

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

Available on non-no_global_oom_handling only.

Copies elements from src range to the end of the string.

§Panics

Panics if the range has start_bound > end_bound, if the range is bounded on either end and does not lie on a char boundary, or if the new capacity exceeds isize::MAX bytes.

§Examples
let mut string = String::from("abcde");

string.extend_from_within(2..);
assert_eq!(string, "abcdecde");

string.extend_from_within(..2);
assert_eq!(string, "abcdecdeab");

string.extend_from_within(4..8);
assert_eq!(string, "abcdecdeabecde");
1.0.0 · Source

pub fn capacity(&self) -> usize

Returns this String’s capacity, in bytes.

§Examples
let s = String::with_capacity(10);

assert!(s.capacity() >= 10);
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 bytes more than the current length. The allocator may reserve more space to speculatively avoid frequent allocations. 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

Basic usage:

let mut s = String::new();

s.reserve(10);

assert!(s.capacity() >= 10);

This might not actually increase the capacity:

let mut s = String::with_capacity(10);
s.push('a');
s.push('b');

// s now has a length of 2 and a capacity of at least 10
let capacity = s.capacity();
assert_eq!(2, s.len());
assert!(capacity >= 10);

// Since we already have at least an extra 8 capacity, calling this...
s.reserve(8);

// ... doesn't actually increase.
assert_eq!(capacity, s.capacity());
Examples found in repository?
examples/ui/text/multiple_text_inputs.rs (line 310)
294fn synchronize_output_text(
295    on: On<TextEditChange>,
296    inputs: Query<(&EditableText, &TextInputRow)>,
297    mut outputs: Query<(&mut Text, &TextInputRow), With<TextOutput>>,
298) {
299    if let Ok((editable_text, input_row)) = &inputs.get(on.event_target()) {
300        for (mut text, output_row) in &mut outputs {
301            if output_row.0 == input_row.0 {
302                // `EditableText::value()` returns a `SplitString` because Parley may keep IME preedit text
303                // in a contiguous range of the editor’s internal `String` buffer during composition.
304                // The returned `SplitString` omits that preedit range, exposing only the text before and after it.
305                //
306                // To avoid allocating a new `String`, we reserve the total length of the `SplitString`'s slices,
307                // then append them to the output `Text`.
308                text.0.clear();
309                text.0
310                    .reserve(editable_text.value().into_iter().map(str::len).sum());
311                for sub_str in editable_text.value() {
312                    text.0.push_str(sub_str);
313                }
314            }
315        }
316    }
317}
318
319// Submit the focused input's text when Enter is pressed.
320fn submit_text(
321    mut input_focus: ResMut<InputFocus>,
322    keyboard_input: Res<ButtonInput<Key>>,
323    mut text_input: Query<(&mut EditableText, &TextInputRow)>,
324    mut text_output: Query<(&mut Text, &TextInputRow), With<SubmitOutput>>,
325    tab_navigation: TabNavigation,
326) {
327    if keyboard_input.just_pressed(Key::Enter)
328        && let Some(focused_entity) = input_focus.get()
329        && let Ok((mut editable_text, input_row)) = text_input.get_mut(focused_entity)
330    {
331        for (mut text, output_row) in &mut text_output {
332            if input_row.0 == output_row.0 {
333                text.0.clear();
334                text.0
335                    .reserve(editable_text.value().into_iter().map(str::len).sum());
336                for sub_str in editable_text.value() {
337                    text.0.push_str(sub_str);
338                }
339                break;
340            }
341        }
342        editable_text.clear();
343
344        if let Ok(next) = tab_navigation.navigate(&input_focus, NavAction::Next) {
345            input_focus.set(next, FocusCause::Navigated);
346        }
347    }
348}
More examples
Hide additional examples
examples/ui/text/multiline_text_input.rs (line 139)
55fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
56    commands.spawn(Camera2d);
57
58    commands
59        .spawn(Node {
60            width: percent(100.),
61            height: percent(100.),
62            justify_content: JustifyContent::Center,
63            align_items: AlignItems::Center,
64            ..default()
65        })
66        .with_children(|parent| {
67            parent
68                .spawn((
69                    Node {
70                        flex_direction: FlexDirection::Column,
71                        align_items: AlignItems::End,
72                        row_gap: px(10.),
73                        ..default()
74                    },
75                    TabGroup::default(),
76                ))
77                .with_children(|parent| {
78                    parent
79                        .spawn(Node {
80                            display: Display::Grid,
81                            grid_template_columns: vec![
82                                RepeatedGridTrack::auto(1),
83                                RepeatedGridTrack::auto(1),
84                            ],
85                            column_gap: px(4.),
86                            ..default()
87                        })
88                        .with_children(|parent| {
89                            parent
90                                .spawn((
91                                    Node {
92                                        width: px(450.),
93                                        border: px(2.).all(),
94                                        padding: px(8.).all(),
95                                        ..default()
96                                    },
97                                    TextInput,
98                                    EditableText {
99                                        visible_lines: Some(8.),
100                                        allow_newlines: true,
101                                        ..default()
102                                    },
103                                    TextLayout {
104                                        linebreak: LineBreak::WordOrCharacter,
105                                        ..default()
106                                    },
107                                    TextCursorStyle {
108                                        color: Color::WHITE,
109                                        selected_text_color: Some(Color::BLACK),
110                                        ..default()
111                                    },
112                                    TextFont {
113                                        font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
114                                        font_size: FontSize::Px(30.),
115                                        ..default()
116                                    },
117                                    BackgroundColor(DARK_SLATE_GRAY.into()),
118                                    BorderColor::all(SLATE_300),
119                                    MultilineInput,
120                                    TabIndex(0),
121                                    AutoFocus,
122                                ))
123                                .observe(
124                                    |on: On<FocusedInput<KeyboardInput>>,
125                                     keys: Res<ButtonInput<Key>>,
126                                     input_query: Query<&EditableText, With<MultilineInput>>| {
127                                        if !(on.input.state.is_pressed()
128                                            && on.input.logical_key == Key::Enter
129                                            && keys.pressed(Key::Control))
130                                        {
131                                            return;
132                                        }
133                                        let Ok(input) = input_query.get(on.focused_entity) else {
134                                            return;
135                                        };
136
137                                        let mut output = String::new();
138                                        output
139                                            .reserve(input.value().into_iter().map(str::len).sum());
140                                        for sub_str in input.value() {
141                                            output.push_str(sub_str);
142                                        }
143
144                                        info!("{output}");
145                                    },
146                                );
147
148                            // Vertical scrollbar for the multiline input above. Not part of the
149                            // input's tab group and has no `TabIndex`, so it's unreachable via
150                            // Tab navigation and can't take input focus.
151                            parent
152                                .spawn((
153                                    Node {
154                                        min_width: px(10.),
155                                        ..default()
156                                    },
157                                    BackgroundColor(DARK_SLATE_GRAY.into()),
158                                ))
159                                .with_children(|parent| {
160                                    parent
161                                        .spawn((
162                                            Node {
163                                                position_type: PositionType::Absolute,
164                                                width: percent(100.),
165                                                left: px(0.),
166                                                border_radius: BorderRadius::all(px(4.)),
167                                                ..default()
168                                            },
169                                            BackgroundColor(SLATE_300.into()),
170                                            Visibility::Hidden,
171                                            InputScrollThumb,
172                                            InputScrollDragState::default(),
173                                        ))
174                                        .observe(on_thumb_drag_start)
175                                        .observe(on_thumb_drag)
176                                        .observe(on_thumb_drag_end);
177                                });
178                        });
179
180                    parent
181                        .spawn((
182                            Node {
183                                flex_direction: FlexDirection::Row,
184                                column_gap: px(10.),
185                                ..default()
186                            },
187                            children![
188                                (
189                                    Text::new("visible lines:"),
190                                    TextFont {
191                                        font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
192                                        font_size: FontSize::Px(30.),
193                                        ..default()
194                                    },
195                                ),
196                                (
197                                    Node {
198                                        width: px(100.),
199                                        border: px(2.).all(),
200                                        ..default()
201                                    },
202                                    TextFont {
203                                        font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
204                                        font_size: FontSize::Px(30.),
205                                        ..default()
206                                    },
207                                    TextLayout {
208                                        justify: Justify::End,
209                                        ..default()
210                                    },
211                                    BackgroundColor(DARK_SLATE_GRAY.into()),
212                                    BorderColor::all(SLATE_300),
213                                    TextInput,
214                                    EditableText::new("8"),
215                                    EditableTextFilter::new(|c| c.is_ascii_digit() || c == '.'),
216                                    TextCursorStyle {
217                                        color: Color::WHITE,
218                                        selected_text_color: Some(Color::BLACK),
219                                        unfocused_selection_color: Color::NONE,
220                                        ..default()
221                                    },
222                                    SelectAllOnFocus,
223                                    VisibleLinesInput,
224                                    TabIndex(1),
225                                )
226                            ],
227                        ))
228                        .observe(
229                            |on: On<FocusedInput<KeyboardInput>>,
230                             mut query_set: ParamSet<(
231                                Query<&EditableText, With<VisibleLinesInput>>,
232                                Query<&mut EditableText, With<MultilineInput>>,
233                            )>| {
234                                if !(on.input.state.is_pressed()
235                                    && on.input.logical_key == Key::Enter)
236                                {
237                                    return;
238                                }
239
240                                let visible_lines_query = query_set.p0();
241                                let Ok(input) = visible_lines_query.get(on.original_event_target())
242                                else {
243                                    return;
244                                };
245
246                                let mut output = String::new();
247                                output.reserve(input.value().into_iter().map(str::len).sum());
248                                for sub_str in input.value() {
249                                    output.push_str(sub_str);
250                                }
251
252                                let Ok(lines) = output.parse::<f32>() else {
253                                    return;
254                                };
255
256                                let mut multiline_query = query_set.p1();
257                                let Ok(mut multiline_input) = multiline_query.single_mut() else {
258                                    return;
259                                };
260
261                                multiline_input.visible_lines = Some(lines.clamp(1., 10.));
262                            },
263                        );
264
265                    parent
266                        .spawn((
267                            Node {
268                                flex_direction: FlexDirection::Row,
269                                column_gap: px(10.),
270                                ..default()
271                            },
272                            children![
273                                (
274                                    Text::new("font size:"),
275                                    TextFont {
276                                        font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
277                                        font_size: FontSize::Px(30.),
278                                        ..default()
279                                    },
280                                ),
281                                (
282                                    Node {
283                                        width: px(100.),
284                                        border: px(2.).all(),
285                                        ..default()
286                                    },
287                                    TextFont {
288                                        font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
289                                        font_size: FontSize::Px(30.),
290                                        ..default()
291                                    },
292                                    TextLayout {
293                                        justify: Justify::End,
294                                        ..default()
295                                    },
296                                    BackgroundColor(DARK_SLATE_GRAY.into()),
297                                    BorderColor::all(SLATE_300),
298                                    TextInput,
299                                    EditableText::new("30"),
300                                    EditableTextFilter::new(|c| c.is_ascii_digit()),
301                                    TextCursorStyle {
302                                        color: Color::WHITE,
303                                        selected_text_color: Some(Color::BLACK),
304                                        unfocused_selection_color: Color::NONE,
305                                        ..default()
306                                    },
307                                    SelectAllOnFocus,
308                                    FontSizeInput,
309                                    TabIndex(2),
310                                )
311                            ],
312                        ))
313                        .observe(
314                            |on: On<FocusedInput<KeyboardInput>>,
315                             font_size_input_query: Query<&EditableText, With<FontSizeInput>>,
316                             mut multiline_input_font: Single<
317                                &mut TextFont,
318                                With<MultilineInput>,
319                            >| {
320                                if !(on.input.state.is_pressed()
321                                    && on.input.logical_key == Key::Enter)
322                                {
323                                    return;
324                                }
325
326                                let Ok(input) =
327                                    font_size_input_query.get(on.original_event_target())
328                                else {
329                                    return;
330                                };
331
332                                let mut output = String::new();
333                                output.reserve(input.value().into_iter().map(str::len).sum());
334                                for sub_str in input.value() {
335                                    output.push_str(sub_str);
336                                }
337
338                                let Ok(font_size) = output.parse::<f32>() else {
339                                    return;
340                                };
341
342                                multiline_input_font.font_size =
343                                    FontSize::Px(font_size.clamp(5., 50.));
344                            },
345                        );
346
347                    parent
348                        .spawn((
349                            Node {
350                                flex_direction: FlexDirection::Row,
351                                column_gap: px(10.),
352                                ..default()
353                            },
354                            children![
355                                (
356                                    Text::new("corner radius:"),
357                                    TextFont {
358                                        font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
359                                        font_size: FontSize::Px(30.),
360                                        ..default()
361                                    },
362                                ),
363                                (
364                                    Node {
365                                        width: px(100.),
366                                        border: px(2.).all(),
367                                        ..default()
368                                    },
369                                    TextFont {
370                                        font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
371                                        font_size: FontSize::Px(30.),
372                                        ..default()
373                                    },
374                                    TextLayout {
375                                        justify: Justify::End,
376                                        ..default()
377                                    },
378                                    BackgroundColor(DARK_SLATE_GRAY.into()),
379                                    BorderColor::all(SLATE_300),
380                                    TextInput,
381                                    EditableText::new("0"),
382                                    EditableTextFilter::new(|c| c.is_ascii_digit() || c == '.'),
383                                    TextCursorStyle {
384                                        color: Color::WHITE,
385                                        selected_text_color: Some(Color::BLACK),
386                                        ..default()
387                                    },
388                                    SelectionRadiusInput,
389                                    TabIndex(2),
390                                )
391                            ],
392                        ))
393                        .observe(
394                            |on: On<FocusedInput<KeyboardInput>>,
395                             radius_input_query: Query<
396                                &EditableText,
397                                With<SelectionRadiusInput>,
398                            >,
399                             mut cursor_style: Single<
400                                &mut TextCursorStyle,
401                                With<MultilineInput>,
402                            >| {
403                                if !(on.input.state.is_pressed()
404                                    && on.input.logical_key == Key::Enter)
405                                {
406                                    return;
407                                }
408
409                                let Ok(input) = radius_input_query.get(on.original_event_target())
410                                else {
411                                    return;
412                                };
413
414                                let mut output = String::new();
415                                output.reserve(input.value().into_iter().map(str::len).sum());
416                                for sub_str in input.value() {
417                                    output.push_str(sub_str);
418                                }
419
420                                let Ok(radius) = output.parse::<f32>() else {
421                                    return;
422                                };
423
424                                cursor_style.selection_radius = radius.clamp(0., 0.5);
425                            },
426                        );
427
428                    parent
429                        .spawn(Node::default())
430                        .observe(
431                            |on: On<MenuEvent>,
432                             mut popup: Single<
433                                (&mut Node, &mut MenuFocusState),
434                                With<MenuPopup>,
435                            >,
436                             button: Single<Entity, With<MenuButton>>,
437                             mut focus: ResMut<InputFocus>| {
438                                match on.action {
439                                    MenuAction::Open(direction) => {
440                                        popup.0.display = Display::Flex;
441                                        *popup.1 = MenuFocusState::Opening(direction);
442                                    }
443                                    MenuAction::Toggle => {
444                                        if popup.0.display == Display::None {
445                                            popup.0.display = Display::Flex;
446                                            *popup.1 = MenuFocusState::Opening(
447                                                bevy::input_focus::tab_navigation::NavAction::First,
448                                            );
449                                        } else {
450                                            popup.0.display = Display::None;
451                                        }
452                                    }
453                                    MenuAction::CloseAll => {
454                                        popup.0.display = Display::None;
455                                    }
456                                    MenuAction::FocusRoot => {
457                                        focus.set(*button, FocusCause::Navigated);
458                                    }
459                                }
460                            },
461                        )
462                        .with_children(|parent| {
463                            parent.spawn((
464                                Node {
465                                    border: px(2.).all(),
466                                    padding: px(8.).horizontal(),
467                                    ..default()
468                                },
469                                Button,
470                                MenuButton,
471                                TabIndex(4),
472                                BackgroundColor(DARK_SLATE_GRAY.into()),
473                                BorderColor::all(SLATE_300),
474                                children![(
475                                    Text::new("Justify::Left"),
476                                    TextFont {
477                                        font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
478                                        font_size: FontSize::Px(24.),
479                                        ..default()
480                                    },
481                                    JustifyLabel,
482                                )],
483                            ));
484
485                            parent
486                                .spawn((
487                                    Node {
488                                        display: Display::None,
489                                        flex_direction: FlexDirection::Column,
490                                        min_width: percent(100.),
491                                        border: px(2.).all(),
492                                        position_type: PositionType::Absolute,
493                                        ..default()
494                                    },
495                                    MenuPopup::default(),
496                                    Popover {
497                                        positions: vec![PopoverPlacement {
498                                            side: PopoverSide::Top,
499                                            align: PopoverAlign::End,
500                                            gap: 2.,
501                                        }],
502                                        ..default()
503                                    },
504                                    GlobalZIndex(1),
505                                    BackgroundColor(DARK_SLATE_GRAY.into()),
506                                    BorderColor::all(SLATE_300),
507                                ))
508                                .with_children(|parent| {
509                                    for (label, justify) in [
510                                        ("Justify::Left", Justify::Left),
511                                        ("Justify::Center", Justify::Center),
512                                        ("Justify::Right", Justify::Right),
513                                        ("Justify::Justified", Justify::Justified),
514                                        ("Justify::Start", Justify::Start),
515                                        ("Justify::End", Justify::End),
516                                    ] {
517                                        parent
518                                            .spawn((
519                                                Node {
520                                                    padding: px(8.).horizontal(),
521                                                    ..default()
522                                                },
523                                                MenuItem,
524                                                TabIndex(0),
525                                                children![(
526                                                    Text::new(label),
527                                                    TextFont {
528                                                        font: asset_server
529                                                            .load("fonts/FiraMono-Medium.ttf",)
530                                                            .into(),
531                                                        font_size: FontSize::Px(24.),
532                                                        ..default()
533                                                    },
534                                                )],
535                                            ))
536                                            .observe(
537                                                move |_: On<Activate>,
538                                                      mut layout: Single<
539                                                    &mut TextLayout,
540                                                    With<MultilineInput>,
541                                                >,
542                                                      mut selected: Single<
543                                                    &mut Text,
544                                                    With<JustifyLabel>,
545                                                >| {
546                                                    layout.justify = justify;
547                                                    selected.0 = label.into();
548                                                },
549                                            );
550                                    }
551                                });
552                        });
553                });
554        });
555}
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 bytes more than the current length. 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.

§Panics

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

§Examples

Basic usage:

let mut s = String::new();

s.reserve_exact(10);

assert!(s.capacity() >= 10);

This might not actually increase the capacity:

let mut s = String::with_capacity(10);
s.push('a');
s.push('b');

// s now has a length of 2 and a capacity of at least 10
let capacity = s.capacity();
assert_eq!(2, s.len());
assert!(capacity >= 10);

// Since we already have at least an extra 8 capacity, calling this...
s.reserve_exact(8);

// ... doesn't actually increase.
assert_eq!(capacity, s.capacity());
1.57.0 · Source

pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>

Tries to reserve capacity for at least additional bytes more than the current length. The allocator may reserve more space to speculatively avoid frequent allocations. 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: &str) -> Result<String, TryReserveError> {
    let mut output = String::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.push_str(data);

    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 bytes more than the current length. 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: &str) -> Result<String, TryReserveError> {
    let mut output = String::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.push_str(data);

    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 this String to match its length.

§Examples
let mut s = String::from("foo");

s.reserve(100);
assert!(s.capacity() >= 100);

s.shrink_to_fit();
assert_eq!(3, s.capacity());
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 this String 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 s = String::from("foo");

s.reserve(100);
assert!(s.capacity() >= 100);

s.shrink_to(10);
assert!(s.capacity() >= 10);
s.shrink_to(0);
assert!(s.capacity() >= 3);
1.0.0 · Source

pub fn push(&mut self, ch: char)

Available on non-no_global_oom_handling only.

Appends the given char to the end of this String.

§Panics

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

§Examples
let mut s = String::from("abc");

s.push('1');
s.push('2');
s.push('3');

assert_eq!("abc123", s);
Examples found in repository?
examples/ui/text/font_atlas_debug.rs (line 79)
65fn text_update_system(
66    mut state: ResMut<State>,
67    time: Res<Time>,
68    mut query: Query<&mut Text>,
69    mut seeded_rng: ResMut<SeededRng>,
70) {
71    if !state.timer.tick(time.delta()).just_finished() {
72        return;
73    }
74
75    for mut text in &mut query {
76        let c = seeded_rng.random::<u8>() as char;
77        let string = &mut **text;
78        if !string.contains(c) {
79            string.push(c);
80        }
81    }
82}
More examples
Hide additional examples
examples/3d/light_probe_blending.rs (line 604)
588fn set_help_text(app_status: &AppStatus, help_text_query: &mut Query<&mut Text, With<HelpText>>) {
589    for mut ui_text in help_text_query {
590        let mut help_text = String::new();
591        match app_status.camera_mode {
592            CameraMode::Orbit => {
593                help_text.push_str(
594                    "Click and drag to orbit the camera\nUse the mouse wheel to zoom the camera\n",
595                );
596            }
597            CameraMode::Free => {
598                help_text.push_str(
599                    "Click and drag to rotate the camera\nUse WASDEQ to move the camera\n",
600                );
601            }
602        }
603
604        help_text.push('\n');
605
606        if matches!(app_status.gizmos_enabled, GizmosEnabled::On) {
607            help_text.push_str(
608                "\
609Gizmos:
610Tan: Light probe bounds
611Red: Light probe falloff bounds
612Blue: Parallax correction bounds",
613            );
614        }
615
616        *ui_text = Text::new(help_text);
617    }
618}
1.0.0 · Source

pub fn as_bytes(&self) -> &[u8] ⓘ

Returns a byte slice of this String’s contents.

The inverse of this method is from_utf8.

§Examples
let s = String::from("hello");

assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
Examples found in repository?
examples/asset/processing/asset_processing.rs (line 223)
216    async fn save(
217        &self,
218        writer: &mut Writer,
219        asset: SavedAsset<'_, '_, Self::Asset>,
220        _settings: &Self::Settings,
221        _asset_path: AssetPath<'_>,
222    ) -> Result<TextSettings, Self::Error> {
223        writer.write_all(asset.text.as_bytes()).await?;
224        Ok(TextSettings::default())
225    }
More examples
Hide additional examples
examples/asset/asset_saving_with_subassets.rs (line 191)
169    async fn save(
170        &self,
171        writer: &mut Writer,
172        asset: SavedAsset<'_, '_, Self::Asset>,
173        _settings: &Self::Settings,
174        _asset_path: AssetPath<'_>,
175    ) -> Result<(), Self::Error> {
176        let boxes = asset
177            .boxes
178            .iter()
179            .map(|handle| {
180                asset
181                    .get_labeled_by_id::<OneBox>(handle)
182                    .unwrap()
183                    .get()
184                    .clone()
185            })
186            .collect();
187
188        // Note: serializing to string isn't ideal since we can't do a streaming write, but this is
189        // fine for an example.
190        let serialized = ron::to_string(&SerializableManyBoxes { boxes })?;
191        writer.write_all(serialized.as_bytes()).await?;
192
193        Ok(())
194    }
examples/animation/animation_graph.rs (line 214)
167fn setup_assets_programmatically(
168    commands: &mut Commands,
169    asset_server: &mut AssetServer,
170    animation_graphs: &mut Assets<AnimationGraph>,
171    _save: bool,
172) {
173    // Create the nodes.
174    let mut animation_graph = AnimationGraph::new();
175    let blend_node = animation_graph.add_blend(0.5, animation_graph.root);
176    animation_graph.add_clip(
177        asset_server.load(GltfAssetLabel::Animation(0).from_asset("models/animated/Fox.glb")),
178        1.0,
179        animation_graph.root,
180    );
181    animation_graph.add_clip(
182        asset_server.load(GltfAssetLabel::Animation(1).from_asset("models/animated/Fox.glb")),
183        1.0,
184        blend_node,
185    );
186    animation_graph.add_clip(
187        asset_server.load(GltfAssetLabel::Animation(2).from_asset("models/animated/Fox.glb")),
188        1.0,
189        blend_node,
190    );
191
192    // If asked to save, do so.
193    #[cfg(not(target_arch = "wasm32"))]
194    if _save {
195        let animation_graph = animation_graph.clone();
196
197        IoTaskPool::get()
198            .spawn(async move {
199                use std::io::Write;
200
201                let animation_graph: SerializedAnimationGraph = animation_graph
202                    .try_into()
203                    .expect("The animation graph failed to convert to its serialized form");
204
205                let serialized_graph =
206                    ron::ser::to_string_pretty(&animation_graph, PrettyConfig::default())
207                        .expect("Failed to serialize the animation graph");
208                let mut animation_graph_writer = File::create(Path::join(
209                    &FileAssetReader::get_base_path(),
210                    Path::join(Path::new("assets"), Path::new(ANIMATION_GRAPH_PATH)),
211                ))
212                .expect("Failed to open the animation graph asset");
213                animation_graph_writer
214                    .write_all(serialized_graph.as_bytes())
215                    .expect("Failed to write the animation graph");
216            })
217            .detach();
218    }
219
220    // Add the graph.
221    let handle = animation_graphs.add(animation_graph);
222
223    // Save the assets in a resource.
224    commands.insert_resource(ExampleAnimationGraph(handle));
225}
examples/scene/world_serialization.rs (line 211)
166fn save_world_system(world: &mut World) {
167    let asset_server = world.resource::<AssetServer>().clone();
168    // The `TypeRegistry` resource contains information about all registered types (including components).
169    // This is used to construct worlds, so we'll want to ensure that we use the registry from the
170    // main world. To do this, we can simply clone the `AppTypeRegistry` resource.
171    let type_registry = world.resource::<AppTypeRegistry>().clone();
172
173    // Any ECS World can be serialized.
174    // For demonstration purposes, we'll create a new one.
175    let mut scene_world = World::new();
176
177    let mut component_b = ComponentB::from_world(world);
178    component_b.value = "hello".to_string();
179    scene_world.spawn((
180        component_b,
181        ComponentA { x: 1.0, y: 2.0 },
182        Transform::IDENTITY,
183        Name::new("joe"),
184        WorldAssetRoot(asset_server.load("models/FlightHelmet/FlightHelmet.gltf#Scene0")),
185    ));
186    scene_world.spawn(ComponentA { x: 3.0, y: 4.0 });
187    scene_world.insert_resource(ResourceA { score: 1 });
188
189    // With our sample world ready to go, we can now create a DynamicWorld from it.
190    // For simplicity, we will create our scene using DynamicWorld directly, but if
191    // you need more control, you can use DynamicWorldBuilder.
192    let dynamic_world = DynamicWorld::from_world_with(&scene_world, &type_registry.read());
193
194    // Dynamic Worlds can be serialized like this:
195    let type_registry = world.resource::<AppTypeRegistry>();
196    let type_registry = type_registry.read();
197    let serialized_world = dynamic_world.serialize(&type_registry).unwrap();
198
199    // Shows the serialized world in the console
200    info!("{}", serialized_world);
201
202    // Writing the world to a new file. Using a task to avoid calling the filesystem APIs in a system
203    // as they are blocking.
204    //
205    // This can't work in Wasm as there is no filesystem access.
206    #[cfg(not(target_arch = "wasm32"))]
207    IoTaskPool::get()
208        .spawn(async move {
209            // Write the world RON data to file
210            File::create(format!("assets/{NEW_WORLD_FILE_PATH}"))
211                .and_then(|mut file| file.write(serialized_world.as_bytes()))
212                .expect("Error while writing world to file");
213        })
214        .detach();
215}
1.0.0 · Source

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

Shortens this String to the specified length.

If new_len is greater than or equal to the string’s current length, this has no effect.

Note that this method has no effect on the allocated capacity of the string

§Panics

Panics if new_len does not lie on a char boundary.

§Examples
let mut s = String::from("hello");

s.truncate(2);

assert_eq!("he", s);
1.0.0 · Source

pub fn pop(&mut self) -> Option<char>

Removes the last character from the string buffer and returns it.

Returns None if this String is empty.

§Examples
let mut s = String::from("abč");

assert_eq!(s.pop(), Some('č'));
assert_eq!(s.pop(), Some('b'));
assert_eq!(s.pop(), Some('a'));

assert_eq!(s.pop(), None);
1.0.0 · Source

pub fn remove(&mut self, idx: usize) -> char

Removes a char from this String at byte position idx and returns it.

Copies all bytes after the removed char to new positions.

Note that calling this in a loop can result in quadratic behavior.

§Panics

Panics if idx is larger than or equal to the String’s length, or if it does not lie on a char boundary.

§Examples
let mut s = String::from("abç");

assert_eq!(s.remove(0), 'a');
assert_eq!(s.remove(1), 'ç');
assert_eq!(s.remove(0), 'b');
Source

pub fn remove_matches<P>(&mut self, pat: P)
where P: Pattern,

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

Remove all matches of pattern pat in the String.

§Examples
#![feature(string_remove_matches)]
let mut s = String::from("Trees are not green, the sky is not blue.");
s.remove_matches("not ");
assert_eq!("Trees are green, the sky is blue.", s);

Matches will be detected and removed iteratively, so in cases where patterns overlap, only the first pattern will be removed:

#![feature(string_remove_matches)]
let mut s = String::from("banana");
s.remove_matches("ana");
assert_eq!("bna", s);
1.26.0 · Source

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

Retains only the characters specified by the predicate.

In other words, remove all characters c such that f(c) returns false. This method operates in place, visiting each character exactly once in the original order, and preserves the order of the retained characters.

§Examples
let mut s = String::from("f_o_ob_ar");

s.retain(|c| c != '_');

assert_eq!(s, "foobar");

Because the elements are visited exactly once in the original order, external state may be used to decide which elements to keep.

let mut s = String::from("abcde");
let keep = [false, true, true, false, true];
let mut iter = keep.iter();
s.retain(|_| *iter.next().unwrap());
assert_eq!(s, "bce");
1.0.0 · Source

pub fn insert(&mut self, idx: usize, ch: char)

Available on non-no_global_oom_handling only.

Inserts a character into this String at byte position idx.

Reallocates if self.capacity() is insufficient, which may involve copying all self.capacity() bytes. Makes space for the insertion by copying all bytes of &self[idx..] to new positions.

Note that calling this in a loop can result in quadratic behavior.

§Panics

Panics if idx is larger than the String’s length, or if it does not lie on a char boundary.

§Examples
let mut s = String::with_capacity(3);

s.insert(0, 'f');
s.insert(1, 'o');
s.insert(2, 'o');

assert_eq!("foo", s);
1.16.0 · Source

pub fn insert_str(&mut self, idx: usize, string: &str)

Available on non-no_global_oom_handling only.

Inserts a string slice into this String at byte position idx.

Reallocates if self.capacity() is insufficient, which may involve copying all self.capacity() bytes. Makes space for the insertion by copying all bytes of &self[idx..] to new positions.

Note that calling this in a loop can result in quadratic behavior.

§Panics

Panics if idx is larger than the String’s length, or if it does not lie on a char boundary.

§Examples
let mut s = String::from("bar");

s.insert_str(0, "foo");

assert_eq!("foobar", s);
1.0.0 · Source

pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> ⓘ

Returns a mutable reference to the contents of this String.

§Safety

This function is unsafe because the returned &mut Vec allows writing bytes which are not valid UTF-8. If this constraint is violated, using the original String after dropping the &mut Vec may violate memory safety, as the rest of the standard library assumes that Strings are valid UTF-8.

§Examples
let mut s = String::from("hello");

unsafe {
    let vec = s.as_mut_vec();
    assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);

    vec.reverse();
}
assert_eq!(s, "olleh");
1.0.0 · Source

pub fn len(&self) -> usize

Returns the length of this String, in bytes, not chars or graphemes. In other words, it might not be what a human considers the length of the string.

§Examples
let a = String::from("foo");
assert_eq!(a.len(), 3);

let fancy_f = String::from("ƒoo");
assert_eq!(fancy_f.len(), 4);
assert_eq!(fancy_f.chars().count(), 3);
Examples found in repository?
examples/3d/tonemapping.rs (line 419)
395fn update_ui(
396    mut text_query: Single<&mut Text, Without<SceneNumber>>,
397    settings: Single<(&Tonemapping, &ColorGrading)>,
398    current_scene: Res<CurrentScene>,
399    selected_parameter: Res<SelectedParameter>,
400    mut hide_ui: Local<bool>,
401    keys: Res<ButtonInput<KeyCode>>,
402) {
403    if keys.just_pressed(KeyCode::KeyH) {
404        *hide_ui = !*hide_ui;
405    }
406
407    if *hide_ui {
408        if !text_query.is_empty() {
409            // single_mut() always triggers change detection,
410            // so only access if text actually needs changing
411            text_query.clear();
412        }
413        return;
414    }
415
416    let (tonemapping, color_grading) = *settings;
417    let tonemapping = *tonemapping;
418
419    let mut text = String::with_capacity(text_query.len());
420
421    let scn = current_scene.0;
422    text.push_str("(H) Hide UI\n\n");
423    text.push_str("Test Scene: \n");
424    text.push_str(&format!(
425        "(Q) {} Basic Scene\n",
426        if scn == 1 { ">" } else { "" }
427    ));
428    text.push_str(&format!(
429        "(W) {} Color Sweep\n",
430        if scn == 2 { ">" } else { "" }
431    ));
432    text.push_str(&format!(
433        "(E) {} Image Viewer\n",
434        if scn == 3 { ">" } else { "" }
435    ));
436
437    text.push_str("\n\nTonemapping Method:\n");
438    text.push_str(&format!(
439        "(1) {} Linear\n",
440        if tonemapping == Tonemapping::Linear {
441            ">"
442        } else {
443            ""
444        }
445    ));
446    text.push_str(&format!(
447        "(2) {} Reinhard\n",
448        if tonemapping == Tonemapping::Reinhard {
449            "> "
450        } else {
451            ""
452        }
453    ));
454    text.push_str(&format!(
455        "(3) {} Reinhard Luminance\n",
456        if tonemapping == Tonemapping::ReinhardLuminance {
457            ">"
458        } else {
459            ""
460        }
461    ));
462    text.push_str(&format!(
463        "(4) {} ACES Fitted\n",
464        if tonemapping == Tonemapping::AcesFitted {
465            ">"
466        } else {
467            ""
468        }
469    ));
470    text.push_str(&format!(
471        "(5) {} AgX\n",
472        if tonemapping == Tonemapping::AgX {
473            ">"
474        } else {
475            ""
476        }
477    ));
478    text.push_str(&format!(
479        "(6) {} SomewhatBoringDisplayTransform\n",
480        if tonemapping == Tonemapping::SomewhatBoringDisplayTransform {
481            ">"
482        } else {
483            ""
484        }
485    ));
486    text.push_str(&format!(
487        "(7) {} TonyMcMapface\n",
488        if tonemapping == Tonemapping::TonyMcMapface {
489            ">"
490        } else {
491            ""
492        }
493    ));
494    text.push_str(&format!(
495        "(8) {} Blender Filmic\n",
496        if tonemapping == Tonemapping::BlenderFilmic {
497            ">"
498        } else {
499            ""
500        }
501    ));
502    text.push_str(&format!(
503        "(9) {} Khronos PBR Neutral\n",
504        if tonemapping == Tonemapping::KhronosPbrNeutral {
505            ">"
506        } else {
507            ""
508        }
509    ));
510
511    text.push_str("\n\nColor Grading:\n");
512    text.push_str("(arrow keys)\n");
513    if selected_parameter.value == 0 {
514        text.push_str("> ");
515    }
516    text.push_str(&format!("Exposure: {:.2}\n", color_grading.global.exposure));
517    if selected_parameter.value == 1 {
518        text.push_str("> ");
519    }
520    text.push_str(&format!("Gamma: {:.2}\n", color_grading.shadows.gamma));
521    if selected_parameter.value == 2 {
522        text.push_str("> ");
523    }
524    text.push_str(&format!(
525        "PreSaturation: {:.2}\n",
526        color_grading.shadows.saturation
527    ));
528    if selected_parameter.value == 3 {
529        text.push_str("> ");
530    }
531    text.push_str(&format!(
532        "PostSaturation: {:.2}\n",
533        color_grading.global.post_saturation
534    ));
535    text.push_str("(Space) Reset all to default\n");
536
537    if current_scene.0 == 1 {
538        text.push_str("(Enter) Reset all to scene recommendation\n");
539    }
540
541    if text != text_query.as_str() {
542        // single_mut() always triggers change detection,
543        // so only access if text actually changed
544        text_query.0 = text;
545    }
546}
1.0.0 · Source

pub fn is_empty(&self) -> bool

Returns true if this String has a length of zero, and false otherwise.

§Examples
let mut v = String::new();
assert!(v.is_empty());

v.push('a');
assert!(!v.is_empty());
Examples found in repository?
examples/3d/tonemapping.rs (line 408)
395fn update_ui(
396    mut text_query: Single<&mut Text, Without<SceneNumber>>,
397    settings: Single<(&Tonemapping, &ColorGrading)>,
398    current_scene: Res<CurrentScene>,
399    selected_parameter: Res<SelectedParameter>,
400    mut hide_ui: Local<bool>,
401    keys: Res<ButtonInput<KeyCode>>,
402) {
403    if keys.just_pressed(KeyCode::KeyH) {
404        *hide_ui = !*hide_ui;
405    }
406
407    if *hide_ui {
408        if !text_query.is_empty() {
409            // single_mut() always triggers change detection,
410            // so only access if text actually needs changing
411            text_query.clear();
412        }
413        return;
414    }
415
416    let (tonemapping, color_grading) = *settings;
417    let tonemapping = *tonemapping;
418
419    let mut text = String::with_capacity(text_query.len());
420
421    let scn = current_scene.0;
422    text.push_str("(H) Hide UI\n\n");
423    text.push_str("Test Scene: \n");
424    text.push_str(&format!(
425        "(Q) {} Basic Scene\n",
426        if scn == 1 { ">" } else { "" }
427    ));
428    text.push_str(&format!(
429        "(W) {} Color Sweep\n",
430        if scn == 2 { ">" } else { "" }
431    ));
432    text.push_str(&format!(
433        "(E) {} Image Viewer\n",
434        if scn == 3 { ">" } else { "" }
435    ));
436
437    text.push_str("\n\nTonemapping Method:\n");
438    text.push_str(&format!(
439        "(1) {} Linear\n",
440        if tonemapping == Tonemapping::Linear {
441            ">"
442        } else {
443            ""
444        }
445    ));
446    text.push_str(&format!(
447        "(2) {} Reinhard\n",
448        if tonemapping == Tonemapping::Reinhard {
449            "> "
450        } else {
451            ""
452        }
453    ));
454    text.push_str(&format!(
455        "(3) {} Reinhard Luminance\n",
456        if tonemapping == Tonemapping::ReinhardLuminance {
457            ">"
458        } else {
459            ""
460        }
461    ));
462    text.push_str(&format!(
463        "(4) {} ACES Fitted\n",
464        if tonemapping == Tonemapping::AcesFitted {
465            ">"
466        } else {
467            ""
468        }
469    ));
470    text.push_str(&format!(
471        "(5) {} AgX\n",
472        if tonemapping == Tonemapping::AgX {
473            ">"
474        } else {
475            ""
476        }
477    ));
478    text.push_str(&format!(
479        "(6) {} SomewhatBoringDisplayTransform\n",
480        if tonemapping == Tonemapping::SomewhatBoringDisplayTransform {
481            ">"
482        } else {
483            ""
484        }
485    ));
486    text.push_str(&format!(
487        "(7) {} TonyMcMapface\n",
488        if tonemapping == Tonemapping::TonyMcMapface {
489            ">"
490        } else {
491            ""
492        }
493    ));
494    text.push_str(&format!(
495        "(8) {} Blender Filmic\n",
496        if tonemapping == Tonemapping::BlenderFilmic {
497            ">"
498        } else {
499            ""
500        }
501    ));
502    text.push_str(&format!(
503        "(9) {} Khronos PBR Neutral\n",
504        if tonemapping == Tonemapping::KhronosPbrNeutral {
505            ">"
506        } else {
507            ""
508        }
509    ));
510
511    text.push_str("\n\nColor Grading:\n");
512    text.push_str("(arrow keys)\n");
513    if selected_parameter.value == 0 {
514        text.push_str("> ");
515    }
516    text.push_str(&format!("Exposure: {:.2}\n", color_grading.global.exposure));
517    if selected_parameter.value == 1 {
518        text.push_str("> ");
519    }
520    text.push_str(&format!("Gamma: {:.2}\n", color_grading.shadows.gamma));
521    if selected_parameter.value == 2 {
522        text.push_str("> ");
523    }
524    text.push_str(&format!(
525        "PreSaturation: {:.2}\n",
526        color_grading.shadows.saturation
527    ));
528    if selected_parameter.value == 3 {
529        text.push_str("> ");
530    }
531    text.push_str(&format!(
532        "PostSaturation: {:.2}\n",
533        color_grading.global.post_saturation
534    ));
535    text.push_str("(Space) Reset all to default\n");
536
537    if current_scene.0 == 1 {
538        text.push_str("(Enter) Reset all to scene recommendation\n");
539    }
540
541    if text != text_query.as_str() {
542        // single_mut() always triggers change detection,
543        // so only access if text actually changed
544        text_query.0 = text;
545    }
546}
More examples
Hide additional examples
examples/ecs/dynamic.rs (line 84)
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.16.0 · Source

pub fn split_off(&mut self, at: usize) -> String

Available on non-no_global_oom_handling only.

Splits the string into two at the given byte index.

Returns a newly allocated String. self contains bytes [0, at), and the returned String contains bytes [at, len). at must be on the boundary of a UTF-8 code point.

Note that the capacity of self does not change.

§Panics

Panics if at is not on a UTF-8 code point boundary, or if it is beyond the last code point of the string.

§Examples
let mut hello = String::from("Hello, World!");
let world = hello.split_off(7);
assert_eq!(hello, "Hello, ");
assert_eq!(world, "World!");
1.0.0 · Source

pub fn clear(&mut self)

Truncates this String, removing all contents.

While this means the String will have a length of zero, it does not touch its capacity.

§Examples
let mut s = String::from("foo");

s.clear();

assert!(s.is_empty());
assert_eq!(0, s.len());
assert_eq!(3, s.capacity());
Examples found in repository?
examples/stress_tests/many_text.rs (line 217)
214fn update_lorem_text(mut lorem_text_query: Query<(&mut Text, &mut Lorem)>) {
215    for (mut text, mut lorem) in &mut lorem_text_query {
216        if lorem.0 {
217            text.0.clear();
218            text.0.push_str(LOREM_TEXT_1);
219        } else {
220            text.0.clear();
221            text.0.push_str(LOREM_TEXT_2);
222        }
223
224        lorem.0 = !lorem.0;
225    }
226}
More examples
Hide additional examples
examples/math/bounding_2d.rs (line 80)
75fn update_text(mut text: Single<&mut Text>, cur_state: Res<State<Test>>) {
76    if !cur_state.is_changed() {
77        return;
78    }
79
80    text.clear();
81
82    text.push_str("Intersection test:\n");
83    use Test::*;
84    for &test in &[AabbSweep, CircleSweep, RayCast, AabbCast, CircleCast] {
85        let s = if **cur_state == test { "*" } else { " " };
86        text.push_str(&format!(" {s} {test:?} {s}\n"));
87    }
88    text.push_str("\nPress space to cycle");
89}
examples/shader_advanced/fullscreen_material.rs (line 104)
93fn toggle_effect(
94    mut text: Single<&mut Text>,
95    keys: Res<ButtonInput<KeyCode>>,
96    camera: Single<(Entity, Option<&FullscreenEffect>), With<Camera3d>>,
97    mut commands: Commands,
98) {
99    if keys.just_pressed(KeyCode::KeyT) {
100        let (entity, effect) = *camera;
101
102        if effect.is_some() {
103            commands.entity(entity).remove::<FullscreenEffect>();
104            text.clear();
105            text.push_str("(T) FullscreenEffect: Off");
106        } else {
107            commands.entity(entity).insert(FullscreenEffect::new(0.0));
108            text.clear();
109            text.push_str("(T) FullscreenEffect: On");
110        }
111    }
112}
examples/ui/text/multiple_text_inputs.rs (line 308)
294fn synchronize_output_text(
295    on: On<TextEditChange>,
296    inputs: Query<(&EditableText, &TextInputRow)>,
297    mut outputs: Query<(&mut Text, &TextInputRow), With<TextOutput>>,
298) {
299    if let Ok((editable_text, input_row)) = &inputs.get(on.event_target()) {
300        for (mut text, output_row) in &mut outputs {
301            if output_row.0 == input_row.0 {
302                // `EditableText::value()` returns a `SplitString` because Parley may keep IME preedit text
303                // in a contiguous range of the editor’s internal `String` buffer during composition.
304                // The returned `SplitString` omits that preedit range, exposing only the text before and after it.
305                //
306                // To avoid allocating a new `String`, we reserve the total length of the `SplitString`'s slices,
307                // then append them to the output `Text`.
308                text.0.clear();
309                text.0
310                    .reserve(editable_text.value().into_iter().map(str::len).sum());
311                for sub_str in editable_text.value() {
312                    text.0.push_str(sub_str);
313                }
314            }
315        }
316    }
317}
318
319// Submit the focused input's text when Enter is pressed.
320fn submit_text(
321    mut input_focus: ResMut<InputFocus>,
322    keyboard_input: Res<ButtonInput<Key>>,
323    mut text_input: Query<(&mut EditableText, &TextInputRow)>,
324    mut text_output: Query<(&mut Text, &TextInputRow), With<SubmitOutput>>,
325    tab_navigation: TabNavigation,
326) {
327    if keyboard_input.just_pressed(Key::Enter)
328        && let Some(focused_entity) = input_focus.get()
329        && let Ok((mut editable_text, input_row)) = text_input.get_mut(focused_entity)
330    {
331        for (mut text, output_row) in &mut text_output {
332            if input_row.0 == output_row.0 {
333                text.0.clear();
334                text.0
335                    .reserve(editable_text.value().into_iter().map(str::len).sum());
336                for sub_str in editable_text.value() {
337                    text.0.push_str(sub_str);
338                }
339                break;
340            }
341        }
342        editable_text.clear();
343
344        if let Ok(next) = tab_navigation.navigate(&input_focus, NavAction::Next) {
345            input_focus.set(next, FocusCause::Navigated);
346        }
347    }
348}
examples/3d/post_processing.rs (line 271)
270fn update_help_text(mut text: Single<&mut Text>, app_settings: Res<AppSettings>) {
271    text.clear();
272    let text_list = [
273        format!(
274            "Chromatic aberration intensity: {:.2}\n",
275            app_settings.chromatic_aberration_intensity
276        ),
277        format!(
278            "Vignette intensity: {:.2}\n",
279            app_settings.vignette_intensity
280        ),
281        format!("Vignette radius: {:.2}\n", app_settings.vignette_radius),
282        format!(
283            "Vignette smoothness: {:.2}\n",
284            app_settings.vignette_smoothness
285        ),
286        format!(
287            "Vignette roundness: {:.2}\n",
288            app_settings.vignette_roundness
289        ),
290        format!(
291            "Vignette edge_compensation: {:.2}\n",
292            app_settings.vignette_edge_compensation
293        ),
294        format!(
295            "Lens Distortion intensity: {:.2}\n",
296            app_settings.lens_distortion_intensity
297        ),
298        format!(
299            "Lens Distortion multiplier x: {:.2}\n",
300            app_settings.lens_distortion_multiplier_x
301        ),
302        format!(
303            "Lens Distortion multiplier y: {:.2}\n",
304            app_settings.lens_distortion_multiplier_y
305        ),
306    ];
307    for (i, val) in text_list.iter().enumerate() {
308        if i == app_settings.selected {
309            text.push_str("> ");
310        }
311        text.push_str(val);
312    }
313    text.push_str("\n(Press Up or Down to select)\n(Press Left or Right to change)");
314}
examples/3d/solari.rs (line 584)
568fn update_control_text(
569    mut text: Single<&mut Text, With<ControlText>>,
570    solari_lighting: Single<&SolariLighting>,
571    robot_light_material: Option<Res<RobotLightMaterial>>,
572    materials: Res<Assets<StandardMaterial>>,
573    directional_light: Query<Entity, With<DirectionalLight>>,
574    time: Res<Time<Virtual>>,
575    args: Res<Args>,
576    #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] dlss_rr_supported: Option<
577        Res<DlssRayReconstructionSupported>,
578    >,
579    #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] dlss_camera: Query<
580        Has<Dlss<DlssRayReconstructionFeature>>,
581        With<SolariLighting>,
582    >,
583) {
584    text.0.clear();
585
586    if args.many_lights != Some(true) {
587        if time.is_paused() {
588            text.0.push_str("(Space): Resume");
589        } else {
590            text.0.push_str("(Space): Pause");
591        }
592
593        if directional_light.single().is_ok() {
594            text.0.push_str("\n(1): Disable directional light");
595        } else {
596            text.0.push_str("\n(1): Enable directional light");
597        }
598
599        match robot_light_material.and_then(|m| materials.get(&m.0)) {
600            Some(robot_light_material) if robot_light_material.emissive != LinearRgba::BLACK => {
601                text.0.push_str("\n(2): Disable robot emissive light");
602            }
603            _ => {
604                text.0.push_str("\n(2): Enable robot emissive light");
605            }
606        }
607    }
608
609    #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
610    if dlss_rr_supported.is_some() {
611        if matches!(dlss_camera.single(), Ok(true)) {
612            text.0.push_str("\n(3): Disable DLSS Ray Reconstruction");
613        } else {
614            text.0.push_str("\n(3): Enable DLSS Ray Reconstruction");
615        }
616    } else {
617        text.0
618            .push_str("\nDenoising: DLSS Ray Reconstruction not supported");
619    }
620
621    #[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))]
622    text.0
623        .push_str("\nDenoising: App not compiled with DLSS support");
624
625    if solari_lighting.restir {
626        text.0.push_str("\n(R): Disable ReSTIR");
627    } else {
628        text.0.push_str("\n(R): Enable ReSTIR");
629    }
630}
631
632#[derive(Component)]
633struct PerformanceText;
634
635fn update_performance_text(
636    mut text: Single<&mut Text, With<PerformanceText>>,
637    diagnostics: Res<DiagnosticsStore>,
638    #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] dlss_camera: Query<
639        Has<Dlss<DlssRayReconstructionFeature>>,
640        With<SolariLighting>,
641    >,
642) {
643    text.0.clear();
644
645    let mut total = 0.0;
646    let mut add_diagnostic = |name: &str, path: &'static str| {
647        let path = DiagnosticPath::new(path);
648        if let Some(value) = diagnostics.get(&path).and_then(Diagnostic::smoothed) {
649            text.push_str(&format!("{name:17}  {value:.2} ms\n"));
650            total += value;
651        }
652    };
653
654    (add_diagnostic)(
655        "Light tiles",
656        "render/solari_lighting/presample_light_tiles/elapsed_gpu",
657    );
658    (add_diagnostic)(
659        "World cache",
660        "render/solari_lighting/world_cache/elapsed_gpu",
661    );
662    (add_diagnostic)("Lighting", "render/solari_lighting/lighting/elapsed_gpu");
663    #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
664    if matches!(dlss_camera.single(), Ok(true)) {
665        (add_diagnostic)("DLSS-RR", "render/dlss_ray_reconstruction/elapsed_gpu");
666    }
667    text.push_str(&format!("{:17}  {total:.2} ms\n", "Total"));
668
669    if let Some(world_cache_active_cells_count) = diagnostics
670        .get(&DiagnosticPath::new(
671            "render/solari_lighting/world_cache_active_cells_count",
672        ))
673        .and_then(Diagnostic::smoothed)
674    {
675        text.push_str(&format!(
676            "\nWorld cache cells {} ({:.0}%)",
677            world_cache_active_cells_count as u32,
678            (world_cache_active_cells_count * 100.0) / (2u64.pow(20) as f64)
679        ));
680    }
681}
1.6.0 · Source

pub fn drain<R>(&mut self, range: R) -> Drain<'_> ⓘ
where R: RangeBounds<usize>,

Removes the specified range from the string in bulk, returning all removed characters as an iterator.

The returned iterator keeps a mutable borrow on the string to optimize its implementation.

§Panics

Panics if the range has start_bound > end_bound, or, if the range is bounded on either end and does not lie on a char boundary.

§Leaking

If the returned iterator goes out of scope without being dropped (due to core::mem::forget, for example), the string may still contain a copy of any drained characters, or may have lost characters arbitrarily, including characters outside the range.

§Examples
let mut s = String::from("α is alpha, β is beta");
let beta_offset = s.find('β').unwrap_or(s.len());

// Remove the range up until the β from the string
let t: String = s.drain(..beta_offset).collect();
assert_eq!(t, "α is alpha, ");
assert_eq!(s, "β is beta");

// A full range clears the string, like `clear()` does
s.drain(..);
assert_eq!(s, "");
1.27.0 · Source

pub fn replace_range<R>(&mut self, range: R, replace_with: &str)
where R: RangeBounds<usize>,

Available on non-no_global_oom_handling only.

Removes the specified range in the string, and replaces it with the given string. The given string doesn’t need to be the same length as the range.

§Panics

Panics if the range has start_bound > end_bound, or, if the range is bounded on either end and does not lie on a char boundary.

§Examples
let mut s = String::from("α is alpha, β is beta");
let beta_offset = s.find('β').unwrap_or(s.len());

// Replace the range up until the β from the string
s.replace_range(..beta_offset, "Α is capital alpha; ");
assert_eq!(s, "Α is capital alpha; β is beta");
Source

pub fn replace_first<P>(&mut self, from: P, to: &str)
where P: Pattern,

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

Replaces the leftmost occurrence of a pattern with another string, in-place.

This method can be preferred over string = string.replacen(..., 1);, as it can use the String’s existing capacity to prevent a reallocation if sufficient space is available.

§Examples

Basic usage:

#![feature(string_replace_in_place)]

let mut s = String::from("Test Results: ❌❌❌");

// Replace the leftmost ❌ with a ✅
s.replace_first('❌', "✅");
assert_eq!(s, "Test Results: ✅❌❌");
Source

pub fn replace_last<P>(&mut self, from: P, to: &str)
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

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

Replaces the rightmost occurrence of a pattern with another string, in-place.

§Examples

Basic usage:

#![feature(string_replace_in_place)]

let mut s = String::from("Test Results: ❌❌❌");

// Replace the rightmost ❌ with a ✅
s.replace_last('❌', "✅");
assert_eq!(s, "Test Results: ❌❌✅");

Methods from Deref<Target = str>§

1.0.0 · Source

pub fn len(&self) -> usize

Returns the length of self.

This length is in bytes, not chars or graphemes. In other words, it might not be what a human considers the length of the string.

§Examples
let len = "foo".len();
assert_eq!(3, len);

assert_eq!("ƒoo".len(), 4); // fancy f!
assert_eq!("ƒoo".chars().count(), 3);
1.0.0 · Source

pub fn is_empty(&self) -> bool

Returns true if self has a length of zero bytes.

§Examples
let s = "";
assert!(s.is_empty());

let s = "not empty";
assert!(!s.is_empty());
1.9.0 · Source

pub fn is_char_boundary(&self, index: usize) -> bool

Checks that index-th byte is the first byte in a UTF-8 code point sequence or the end of the string.

The start and end of the string (when index == self.len()) are considered to be boundaries.

Returns false if index is greater than self.len().

§Examples
let s = "Löwe 老虎 Léopard";
assert!(s.is_char_boundary(0));
// start of `老`
assert!(s.is_char_boundary(6));
assert!(s.is_char_boundary(s.len()));

// second byte of `ö`
assert!(!s.is_char_boundary(2));

// third byte of `老`
assert!(!s.is_char_boundary(8));
1.91.0 · Source

pub fn floor_char_boundary(&self, index: usize) -> usize

Finds the closest x not exceeding index where is_char_boundary(x) is true.

This method can help you truncate a string so that it’s still valid UTF-8, but doesn’t exceed a given number of bytes. Note that this is done purely at the character level and can still visually split graphemes, even though the underlying characters aren’t split. For example, the emoji 🧑‍🔬 (scientist) could be split so that the string only includes 🧑 (person) instead.

§Examples
let s = "❤️🧡💛💚💙💜";
assert_eq!(s.len(), 26);
assert!(!s.is_char_boundary(13));

let closest = s.floor_char_boundary(13);
assert_eq!(closest, 10);
assert_eq!(&s[..closest], "❤️🧡");
1.91.0 · Source

pub fn ceil_char_boundary(&self, index: usize) -> usize

Finds the closest x not below index where is_char_boundary(x) is true.

If index is greater than the length of the string, this returns the length of the string.

This method is the natural complement to floor_char_boundary. See that method for more details.

§Examples
let s = "❤️🧡💛💚💙💜";
assert_eq!(s.len(), 26);
assert!(!s.is_char_boundary(13));

let closest = s.ceil_char_boundary(13);
assert_eq!(closest, 14);
assert_eq!(&s[..closest], "❤️🧡💛");
1.0.0 · Source

pub fn as_bytes(&self) -> &[u8] ⓘ

Converts a string slice to a byte slice. To convert the byte slice back into a string slice, use the from_utf8 function.

§Examples
let bytes = "bors".as_bytes();
assert_eq!(b"bors", bytes);
1.20.0 · Source

pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] ⓘ

Converts a mutable string slice to a mutable byte slice.

§Safety

The caller must ensure that the content of the slice is valid UTF-8 before the borrow ends and the underlying str is used.

Use of a str whose contents are not valid UTF-8 is undefined behavior.

§Examples

Basic usage:

let mut s = String::from("Hello");
let bytes = unsafe { s.as_bytes_mut() };

assert_eq!(b"Hello", bytes);

Mutability:

let mut s = String::from("🗻∈🌏");

unsafe {
    let bytes = s.as_bytes_mut();

    bytes[0] = 0xF0;
    bytes[1] = 0x9F;
    bytes[2] = 0x8D;
    bytes[3] = 0x94;
}

assert_eq!("🍔∈🌏", s);
1.0.0 · Source

pub fn as_ptr(&self) -> *const u8

Converts a string slice to a raw pointer.

As string slices are a slice of bytes, the raw pointer points to a u8. This pointer will be pointing to the first byte of the string slice.

The caller must ensure that the returned pointer is never written to. If you need to mutate the contents of the string slice, use as_mut_ptr.

§Examples
let s = "Hello";
let ptr = s.as_ptr();
1.36.0 · Source

pub fn as_mut_ptr(&mut self) -> *mut u8

Converts a mutable string slice to a raw pointer.

As string slices are a slice of bytes, the raw pointer points to a u8. This pointer will be pointing to the first byte of the string slice.

It is your responsibility to make sure that the string slice only gets modified in a way that it remains valid UTF-8.

1.20.0 · Source

pub fn get<I>(&self, i: I) -> Option<&<I as SliceIndex<str>>::Output>
where I: SliceIndex<str>,

Returns a subslice of str.

This is the non-panicking alternative to indexing the str. Returns None whenever equivalent indexing operation would panic.

§Examples
let v = String::from("🗻∈🌏");

assert_eq!(Some("🗻"), v.get(0..4));

// indices not on UTF-8 sequence boundaries
assert!(v.get(1..).is_none());
assert!(v.get(..8).is_none());

// out of bounds
assert!(v.get(..42).is_none());
1.20.0 · Source

pub fn get_mut<I>( &mut self, i: I, ) -> Option<&mut <I as SliceIndex<str>>::Output>
where I: SliceIndex<str>,

Returns a mutable subslice of str.

This is the non-panicking alternative to indexing the str. Returns None whenever equivalent indexing operation would panic.

§Examples
let mut v = String::from("hello");
// correct length
assert!(v.get_mut(0..5).is_some());
// out of bounds
assert!(v.get_mut(..42).is_none());
assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));

assert_eq!("hello", v);
{
    let s = v.get_mut(0..2);
    let s = s.map(|s| {
        s.make_ascii_uppercase();
        &*s
    });
    assert_eq!(Some("HE"), s);
}
assert_eq!("HEllo", v);
1.20.0 · Source

pub unsafe fn get_unchecked<I>(&self, i: I) -> &<I as SliceIndex<str>>::Output
where I: SliceIndex<str>,

Returns an unchecked subslice of str.

This is the unchecked alternative to indexing the str.

§Safety

Callers of this function are responsible that these preconditions are satisfied:

  • The starting index must not exceed the ending index;
  • Indexes must be within bounds of the original slice;
  • Indexes must lie on UTF-8 sequence boundaries.

Failing that, the returned string slice may reference invalid memory or violate the invariants communicated by the str type.

§Examples
let v = "🗻∈🌏";
unsafe {
    assert_eq!("🗻", v.get_unchecked(0..4));
    assert_eq!("∈", v.get_unchecked(4..7));
    assert_eq!("🌏", v.get_unchecked(7..11));
}
1.20.0 · Source

pub unsafe fn get_unchecked_mut<I>( &mut self, i: I, ) -> &mut <I as SliceIndex<str>>::Output
where I: SliceIndex<str>,

Returns a mutable, unchecked subslice of str.

This is the unchecked alternative to indexing the str.

§Safety

Callers of this function are responsible that these preconditions are satisfied:

  • The starting index must not exceed the ending index;
  • Indexes must be within bounds of the original slice;
  • Indexes must lie on UTF-8 sequence boundaries.

Failing that, the returned string slice may reference invalid memory or violate the invariants communicated by the str type.

§Examples
let mut v = String::from("🗻∈🌏");
unsafe {
    assert_eq!("🗻", v.get_unchecked_mut(0..4));
    assert_eq!("∈", v.get_unchecked_mut(4..7));
    assert_eq!("🌏", v.get_unchecked_mut(7..11));
}
1.0.0 · Source

pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str

👎Deprecated since 1.29.0:

use get_unchecked(begin..end) instead

Creates a string slice from another string slice, bypassing safety checks.

This is generally not recommended, use with caution! For a safe alternative see str and Index.

This new slice goes from begin to end, including begin but excluding end.

To get a mutable string slice instead, see the slice_mut_unchecked method.

§Safety

Callers of this function are responsible that three preconditions are satisfied:

  • begin must not exceed end.
  • begin and end must be byte positions within the string slice.
  • begin and end must lie on UTF-8 sequence boundaries.
§Examples
let s = "Löwe 老虎 Léopard";

unsafe {
    assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
}

let s = "Hello, world!";

unsafe {
    assert_eq!("world", s.slice_unchecked(7, 12));
}
1.5.0 · Source

pub unsafe fn slice_mut_unchecked( &mut self, begin: usize, end: usize, ) -> &mut str

👎Deprecated since 1.29.0:

use get_unchecked_mut(begin..end) instead

Creates a string slice from another string slice, bypassing safety checks.

This is generally not recommended, use with caution! For a safe alternative see str and IndexMut.

This new slice goes from begin to end, including begin but excluding end.

To get an immutable string slice instead, see the slice_unchecked method.

§Safety

Callers of this function are responsible that three preconditions are satisfied:

  • begin must not exceed end.
  • begin and end must be byte positions within the string slice.
  • begin and end must lie on UTF-8 sequence boundaries.
1.4.0 · Source

pub fn split_at(&self, mid: usize) -> (&str, &str)

Divides one string slice into two at a byte offset.

The argument, mid, should be a byte offset from the start of the string. It must also be on the boundary of a UTF-8 code point.

The first returned slice contains exactly the first mid bytes, and the second contains all remaining bytes.

To get mutable string slices instead, see the split_at_mut method.

§Panics

Panics if mid is not on a UTF-8 code point boundary, or if it is past the end of the last code point of the string slice. For a non-panicking alternative see split_at_checked.

§Examples
let s = "Per Martin-Löf";

let (first, last) = s.split_at(3);

assert_eq!("Per", first);
assert_eq!(" Martin-Löf", last);
1.4.0 · Source

pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str)

Divides one mutable string slice into two at a byte offset.

The argument, mid, should be a byte offset from the start of the string. It must also be on the boundary of a UTF-8 code point.

The first returned slice contains exactly the first mid bytes, and the second contains all remaining bytes.

To get immutable string slices instead, see the split_at method.

§Panics

Panics if mid is not on a UTF-8 code point boundary, or if it is past the end of the last code point of the string slice. For a non-panicking alternative see split_at_mut_checked.

§Examples
let mut s = "Per Martin-Löf".to_string();
{
    let (first, last) = s.split_at_mut(3);
    first.make_ascii_uppercase();
    assert_eq!("PER", first);
    assert_eq!(" Martin-Löf", last);
}
assert_eq!("PER Martin-Löf", s);
1.80.0 · Source

pub fn split_at_checked(&self, mid: usize) -> Option<(&str, &str)>

Divides one string slice into two at a byte offset.

The argument, mid, should be a valid byte offset from the start of the string. It must also be on the boundary of a UTF-8 code point. The method returns None if that’s not the case.

The first returned slice contains exactly the first mid bytes, and the second contains all remaining bytes.

To get mutable string slices instead, see the split_at_mut_checked method.

§Examples
let s = "Per Martin-Löf";

let (first, last) = s.split_at_checked(3).unwrap();
assert_eq!("Per", first);
assert_eq!(" Martin-Löf", last);

assert_eq!(None, s.split_at_checked(13));  // Inside “ö”
assert_eq!(None, s.split_at_checked(16));  // Beyond the string length
1.80.0 · Source

pub fn split_at_mut_checked( &mut self, mid: usize, ) -> Option<(&mut str, &mut str)>

Divides one mutable string slice into two at a byte offset.

The argument, mid, should be a valid byte offset from the start of the string. It must also be on the boundary of a UTF-8 code point. The method returns None if that’s not the case.

The first returned slice contains exactly the first mid bytes, and the second contains all remaining bytes.

To get immutable string slices instead, see the split_at_checked method.

§Examples
let mut s = "Per Martin-Löf".to_string();
if let Some((first, last)) = s.split_at_mut_checked(3) {
    first.make_ascii_uppercase();
    assert_eq!("PER", first);
    assert_eq!(" Martin-Löf", last);
}
assert_eq!("PER Martin-Löf", s);

assert_eq!(None, s.split_at_mut_checked(13));  // Inside “ö”
assert_eq!(None, s.split_at_mut_checked(16));  // Beyond the string length
1.0.0 · Source

pub fn chars(&self) -> Chars<'_> ⓘ

Returns an iterator over the chars of a string slice.

As a string slice consists of valid UTF-8, we can iterate through a string slice by char. This method returns such an iterator.

It’s important to remember that char represents a Unicode Scalar Value, and might not match your idea of what a ‘character’ is. Iteration over grapheme clusters may be what you actually want. This functionality is not provided by Rust’s standard library, check crates.io instead.

§Examples

Basic usage:

let word = "goodbye";

let count = word.chars().count();
assert_eq!(7, count);

let mut chars = word.chars();

assert_eq!(Some('g'), chars.next());
assert_eq!(Some('o'), chars.next());
assert_eq!(Some('o'), chars.next());
assert_eq!(Some('d'), chars.next());
assert_eq!(Some('b'), chars.next());
assert_eq!(Some('y'), chars.next());
assert_eq!(Some('e'), chars.next());

assert_eq!(None, chars.next());

Remember, chars might not match your intuition about characters:

let y = "y̆";

let mut chars = y.chars();

assert_eq!(Some('y'), chars.next()); // not 'y̆'
assert_eq!(Some('\u{0306}'), chars.next());

assert_eq!(None, chars.next());
1.0.0 · Source

pub fn char_indices(&self) -> CharIndices<'_> ⓘ

Returns an iterator over the chars of a string slice, and their positions.

As a string slice consists of valid UTF-8, we can iterate through a string slice by char. This method returns an iterator of both these chars, as well as their byte positions.

The iterator yields tuples. The position is first, the char is second.

§Examples

Basic usage:

let word = "goodbye";

let count = word.char_indices().count();
assert_eq!(7, count);

let mut char_indices = word.char_indices();

assert_eq!(Some((0, 'g')), char_indices.next());
assert_eq!(Some((1, 'o')), char_indices.next());
assert_eq!(Some((2, 'o')), char_indices.next());
assert_eq!(Some((3, 'd')), char_indices.next());
assert_eq!(Some((4, 'b')), char_indices.next());
assert_eq!(Some((5, 'y')), char_indices.next());
assert_eq!(Some((6, 'e')), char_indices.next());

assert_eq!(None, char_indices.next());

Remember, chars might not match your intuition about characters:

let yes = "y̆es";

let mut char_indices = yes.char_indices();

assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
assert_eq!(Some((1, '\u{0306}')), char_indices.next());

// note the 3 here - the previous character took up two bytes
assert_eq!(Some((3, 'e')), char_indices.next());
assert_eq!(Some((4, 's')), char_indices.next());

assert_eq!(None, char_indices.next());
1.0.0 · Source

pub fn bytes(&self) -> Bytes<'_> ⓘ

Returns an iterator over the bytes of a string slice.

As a string slice consists of a sequence of bytes, we can iterate through a string slice by byte. This method returns such an iterator.

§Examples
let mut bytes = "bors".bytes();

assert_eq!(Some(b'b'), bytes.next());
assert_eq!(Some(b'o'), bytes.next());
assert_eq!(Some(b'r'), bytes.next());
assert_eq!(Some(b's'), bytes.next());

assert_eq!(None, bytes.next());
1.1.0 · Source

pub fn split_whitespace(&self) -> SplitWhitespace<'_> ⓘ

Splits a string slice by whitespace.

The iterator returned will return string slices that are sub-slices of the original string slice, separated by any amount of whitespace.

‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property White_Space. If you only want to split on ASCII whitespace instead, use split_ascii_whitespace.

§Examples

Basic usage:

let mut iter = "A few words".split_whitespace();

assert_eq!(Some("A"), iter.next());
assert_eq!(Some("few"), iter.next());
assert_eq!(Some("words"), iter.next());

assert_eq!(None, iter.next());

All kinds of whitespace are considered:

let mut iter = " Mary   had\ta\u{2009}little  \n\t lamb".split_whitespace();
assert_eq!(Some("Mary"), iter.next());
assert_eq!(Some("had"), iter.next());
assert_eq!(Some("a"), iter.next());
assert_eq!(Some("little"), iter.next());
assert_eq!(Some("lamb"), iter.next());

assert_eq!(None, iter.next());

If the string is empty or all whitespace, the iterator yields no string slices:

assert_eq!("".split_whitespace().next(), None);
assert_eq!("   ".split_whitespace().next(), None);
1.34.0 · Source

pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> ⓘ

Splits a string slice by ASCII whitespace.

The iterator returned will return string slices that are sub-slices of the original string slice, separated by any amount of ASCII whitespace.

This uses the same definition as char::is_ascii_whitespace. To split by Unicode Whitespace instead, use split_whitespace. Note that because of this difference in definition, even if s.is_ascii() is true, s.split_ascii_whitespace() behavior will differ from s.split_whitespace() if s contains U+000B VERTICAL TAB.

§Examples

Basic usage:

let mut iter = "A few words".split_ascii_whitespace();

assert_eq!(Some("A"), iter.next());
assert_eq!(Some("few"), iter.next());
assert_eq!(Some("words"), iter.next());

assert_eq!(None, iter.next());

Various kinds of ASCII whitespace are considered (see char::is_ascii_whitespace):

let mut iter = " Mary   had\ta little  \n\t lamb".split_ascii_whitespace();
assert_eq!(Some("Mary"), iter.next());
assert_eq!(Some("had"), iter.next());
assert_eq!(Some("a"), iter.next());
assert_eq!(Some("little"), iter.next());
assert_eq!(Some("lamb"), iter.next());

assert_eq!(None, iter.next());

If the string is empty or all ASCII whitespace, the iterator yields no string slices:

assert_eq!("".split_ascii_whitespace().next(), None);
assert_eq!("   ".split_ascii_whitespace().next(), None);
1.0.0 · Source

pub fn lines(&self) -> Lines<'_> ⓘ

Returns an iterator over the lines of a string, as string slices.

Lines are split at line endings that are either newlines (\n) or sequences of a carriage return followed by a line feed (\r\n).

Line terminators are not included in the lines returned by the iterator.

Note that any carriage return (\r) not immediately followed by a line feed (\n) does not split a line. These carriage returns are thereby included in the produced lines.

The final line ending is optional. A string that ends with a final line ending will return the same lines as an otherwise identical string without a final line ending.

An empty string returns an empty iterator.

§Examples

Basic usage:

let text = "foo\r\nbar\n\nbaz\r";
let mut lines = text.lines();

assert_eq!(Some("foo"), lines.next());
assert_eq!(Some("bar"), lines.next());
assert_eq!(Some(""), lines.next());
// Trailing carriage return is included in the last line
assert_eq!(Some("baz\r"), lines.next());

assert_eq!(None, lines.next());

The final line does not require any ending:

let text = "foo\nbar\n\r\nbaz";
let mut lines = text.lines();

assert_eq!(Some("foo"), lines.next());
assert_eq!(Some("bar"), lines.next());
assert_eq!(Some(""), lines.next());
assert_eq!(Some("baz"), lines.next());

assert_eq!(None, lines.next());

An empty string returns an empty iterator:

let text = "";
let mut lines = text.lines();

assert_eq!(lines.next(), None);
1.0.0 · Source

pub fn lines_any(&self) -> LinesAny<'_> ⓘ

👎Deprecated since 1.4.0:

use lines() instead now

Returns an iterator over the lines of a string.

1.8.0 · Source

pub fn encode_utf16(&self) -> EncodeUtf16<'_> ⓘ

Returns an iterator of u16 over the string encoded as native endian UTF-16 (without byte-order mark).

§Examples
let text = "Zażółć gęślą jaźń";

let utf8_len = text.len();
let utf16_len = text.encode_utf16().count();

assert!(utf16_len <= utf8_len);
1.0.0 · Source

pub fn contains<P>(&self, pat: P) -> bool
where P: Pattern,

Returns true if the given pattern matches a sub-slice of this string slice.

Returns false if it does not.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Examples
let bananas = "bananas";

assert!(bananas.contains("nana"));
assert!(!bananas.contains("apples"));
1.0.0 · Source

pub fn starts_with<P>(&self, pat: P) -> bool
where P: Pattern,

Returns true if the given pattern matches a prefix of this string slice.

Returns false if it does not.

The pattern can be a &str, in which case this function will return true if the &str is a prefix of this string slice.

The pattern can also be a char, a slice of chars, or a function or closure that determines if a character matches. These will only be checked against the first character of this string slice. Look at the second example below regarding behavior for slices of chars.

§Examples
let bananas = "bananas";

assert!(bananas.starts_with("bana"));
assert!(!bananas.starts_with("nana"));
let bananas = "bananas";

// Note that both of these assert successfully.
assert!(bananas.starts_with(&['b', 'a', 'n', 'a']));
assert!(bananas.starts_with(&['a', 'b', 'c', 'd']));
1.0.0 · Source

pub fn ends_with<P>(&self, pat: P) -> bool
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns true if the given pattern matches a suffix of this string slice.

Returns false if it does not.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Examples
let bananas = "bananas";

assert!(bananas.ends_with("anas"));
assert!(!bananas.ends_with("nana"));
1.0.0 · Source

pub fn find<P>(&self, pat: P) -> Option<usize>
where P: Pattern,

Returns the byte index of the first character of this string slice that matches the pattern.

Returns None if the pattern doesn’t match.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Examples

Simple patterns:

let s = "Löwe 老虎 Léopard Gepardi";

assert_eq!(s.find('L'), Some(0));
assert_eq!(s.find('é'), Some(14));
assert_eq!(s.find("pard"), Some(17));

More complex patterns using point-free style and closures:

let s = "Löwe 老虎 Léopard";

assert_eq!(s.find(char::is_whitespace), Some(5));
assert_eq!(s.find(char::is_lowercase), Some(1));
assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));

Not finding the pattern:

let s = "Löwe 老虎 Léopard";
let x: &[_] = &['1', '2'];

assert_eq!(s.find(x), None);
1.0.0 · Source

pub fn rfind<P>(&self, pat: P) -> Option<usize>
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns the byte index for the first character of the last match of the pattern in this string slice.

Returns None if the pattern doesn’t match.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Examples

Simple patterns:

let s = "Löwe 老虎 Léopard Gepardi";

assert_eq!(s.rfind('L'), Some(13));
assert_eq!(s.rfind('é'), Some(14));
assert_eq!(s.rfind("pard"), Some(24));

More complex patterns with closures:

let s = "Löwe 老虎 Léopard";

assert_eq!(s.rfind(char::is_whitespace), Some(12));
assert_eq!(s.rfind(char::is_lowercase), Some(20));

Not finding the pattern:

let s = "Löwe 老虎 Léopard";
let x: &[_] = &['1', '2'];

assert_eq!(s.rfind(x), None);
1.0.0 · Source

pub fn split<P>(&self, pat: P) -> Split<'_, P> ⓘ
where P: Pattern,

Returns an iterator over substrings of this string slice, separated by characters matched by a pattern.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

If there are no matches the full string slice is returned as the only item in the iterator.

§Iterator behavior

The returned iterator will be a DoubleEndedIterator if the pattern allows a reverse search and forward/reverse search yields the same elements. This is true for, e.g., char, but not for &str.

If the pattern allows a reverse search but its results might differ from a forward search, the rsplit method can be used.

§Examples

Simple patterns:

let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);

let v: Vec<&str> = "".split('X').collect();
assert_eq!(v, [""]);

let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
assert_eq!(v, ["lion", "", "tiger", "leopard"]);

let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
assert_eq!(v, ["lion", "tiger", "leopard"]);

let v: Vec<&str> = "AABBCC".split("DD").collect();
assert_eq!(v, ["AABBCC"]);

let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
assert_eq!(v, ["abc", "def", "ghi"]);

let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
assert_eq!(v, ["lion", "tiger", "leopard"]);

If the pattern is a slice of chars, split on each occurrence of any of the characters:

let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect();
assert_eq!(v, ["2020", "11", "03", "23", "59"]);

A more complex pattern, using a closure:

let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
assert_eq!(v, ["abc", "def", "ghi"]);

If a string contains multiple contiguous separators, you will end up with empty strings in the output:

let x = "||||a||b|c".to_string();
let d: Vec<_> = x.split('|').collect();

assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);

Contiguous separators are separated by the empty string.

let x = "(///)".to_string();
let d: Vec<_> = x.split('/').collect();

assert_eq!(d, &["(", "", "", ")"]);

Separators at the start or end of a string are neighbored by empty strings.

let d: Vec<_> = "010".split("0").collect();
assert_eq!(d, &["", "1", ""]);

When the empty string is used as a separator, it separates every character in the string, along with the beginning and end of the string.

let f: Vec<_> = "rust".split("").collect();
assert_eq!(f, &["", "r", "u", "s", "t", ""]);

Contiguous separators can lead to possibly surprising behavior when whitespace is used as the separator. This code is correct:

let x = "    a  b c".to_string();
let d: Vec<_> = x.split(' ').collect();

assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);

It does not give you:

ⓘ
assert_eq!(d, &["a", "b", "c"]);

Use split_whitespace for this behavior.

1.51.0 · Source

pub fn split_inclusive<P>(&self, pat: P) -> SplitInclusive<'_, P> ⓘ
where P: Pattern,

Returns an iterator over substrings of this string slice, separated by characters matched by a pattern.

Differs from the iterator produced by split in that split_inclusive leaves the matched part as the terminator of the substring.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Examples
let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb."
    .split_inclusive('\n').collect();
assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]);

If the last element of the string is matched, that element will be considered the terminator of the preceding substring. That substring will be the last item returned by the iterator.

let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n"
    .split_inclusive('\n').collect();
assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]);
1.0.0 · Source

pub fn rsplit<P>(&self, pat: P) -> RSplit<'_, P> ⓘ
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns an iterator over substrings of the given string slice, separated by characters matched by a pattern and yielded in reverse order.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Iterator behavior

The returned iterator requires that the pattern supports a reverse search, and it will be a DoubleEndedIterator if a forward/reverse search yields the same elements.

For iterating from the front, the split method can be used.

§Examples

Simple patterns:

let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);

let v: Vec<&str> = "".rsplit('X').collect();
assert_eq!(v, [""]);

let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
assert_eq!(v, ["leopard", "tiger", "", "lion"]);

let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
assert_eq!(v, ["leopard", "tiger", "lion"]);

A more complex pattern, using a closure:

let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
assert_eq!(v, ["ghi", "def", "abc"]);
1.0.0 · Source

pub fn split_terminator<P>(&self, pat: P) -> SplitTerminator<'_, P> ⓘ
where P: Pattern,

Returns an iterator over substrings of the given string slice, separated by characters matched by a pattern.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

Equivalent to split, except that the trailing substring is skipped if empty.

This method can be used for string data that is terminated, rather than separated by a pattern.

§Iterator behavior

The returned iterator will be a DoubleEndedIterator if the pattern allows a reverse search and forward/reverse search yields the same elements. This is true for, e.g., char, but not for &str.

If the pattern allows a reverse search but its results might differ from a forward search, the rsplit_terminator method can be used.

§Examples
let v: Vec<&str> = "A.B.".split_terminator('.').collect();
assert_eq!(v, ["A", "B"]);

let v: Vec<&str> = "A..B..".split_terminator(".").collect();
assert_eq!(v, ["A", "", "B", ""]);

let v: Vec<&str> = "A.B:C.D".split_terminator(&['.', ':'][..]).collect();
assert_eq!(v, ["A", "B", "C", "D"]);
1.0.0 · Source

pub fn rsplit_terminator<P>(&self, pat: P) -> RSplitTerminator<'_, P> ⓘ
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns an iterator over substrings of self, separated by characters matched by a pattern and yielded in reverse order.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

Equivalent to split, except that the trailing substring is skipped if empty.

This method can be used for string data that is terminated, rather than separated by a pattern.

§Iterator behavior

The returned iterator requires that the pattern supports a reverse search, and it will be double ended if a forward/reverse search yields the same elements.

For iterating from the front, the split_terminator method can be used.

§Examples
let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
assert_eq!(v, ["B", "A"]);

let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
assert_eq!(v, ["", "B", "", "A"]);

let v: Vec<&str> = "A.B:C.D".rsplit_terminator(&['.', ':'][..]).collect();
assert_eq!(v, ["D", "C", "B", "A"]);
1.0.0 · Source

pub fn splitn<P>(&self, n: usize, pat: P) -> SplitN<'_, P> ⓘ
where P: Pattern,

Returns an iterator over substrings of the given string slice, separated by a pattern, restricted to returning at most n items.

If n substrings are returned, the last substring (the nth substring) will contain the remainder of the string.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Iterator behavior

The returned iterator will not be double ended, because it is not efficient to support.

If the pattern allows a reverse search, the rsplitn method can be used.

§Examples

Simple patterns:

let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
assert_eq!(v, ["Mary", "had", "a little lambda"]);

let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
assert_eq!(v, ["lion", "", "tigerXleopard"]);

let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
assert_eq!(v, ["abcXdef"]);

let v: Vec<&str> = "".splitn(1, 'X').collect();
assert_eq!(v, [""]);

A more complex pattern, using a closure:

let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
assert_eq!(v, ["abc", "defXghi"]);
1.0.0 · Source

pub fn rsplitn<P>(&self, n: usize, pat: P) -> RSplitN<'_, P> ⓘ
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns an iterator over substrings of this string slice, separated by a pattern, starting from the end of the string, restricted to returning at most n items.

If n substrings are returned, the last substring (the nth substring) will contain the remainder of the string.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Iterator behavior

The returned iterator will not be double ended, because it is not efficient to support.

For splitting from the front, the splitn method can be used.

§Examples

Simple patterns:

let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
assert_eq!(v, ["lamb", "little", "Mary had a"]);

let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
assert_eq!(v, ["leopard", "tiger", "lionX"]);

let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
assert_eq!(v, ["leopard", "lion::tiger"]);

A more complex pattern, using a closure:

let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
assert_eq!(v, ["ghi", "abc1def"]);
1.52.0 · Source

pub fn split_once<P>(&self, delimiter: P) -> Option<(&str, &str)>
where P: Pattern,

Splits the string on the first occurrence of the specified delimiter and returns prefix before delimiter and suffix after delimiter.

§Examples
assert_eq!("cfg".split_once('='), None);
assert_eq!("cfg=".split_once('='), Some(("cfg", "")));
assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
1.52.0 · Source

pub fn rsplit_once<P>(&self, delimiter: P) -> Option<(&str, &str)>
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Splits the string on the last occurrence of the specified delimiter and returns prefix before delimiter and suffix after delimiter.

§Examples
assert_eq!("cfg".rsplit_once('='), None);
assert_eq!("cfg=".rsplit_once('='), Some(("cfg", "")));
assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo")));
assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));
1.2.0 · Source

pub fn matches<P>(&self, pat: P) -> Matches<'_, P> ⓘ
where P: Pattern,

Returns an iterator over the disjoint matches of a pattern within the given string slice.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Iterator behavior

The returned iterator will be a DoubleEndedIterator if the pattern allows a reverse search and forward/reverse search yields the same elements. This is true for, e.g., char, but not for &str.

If the pattern allows a reverse search but its results might differ from a forward search, the rmatches method can be used.

§Examples
let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
assert_eq!(v, ["abc", "abc", "abc"]);

let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
assert_eq!(v, ["1", "2", "3"]);
1.2.0 · Source

pub fn rmatches<P>(&self, pat: P) -> RMatches<'_, P> ⓘ
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns an iterator over the disjoint matches of a pattern within this string slice, yielded in reverse order.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Iterator behavior

The returned iterator requires that the pattern supports a reverse search, and it will be a DoubleEndedIterator if a forward/reverse search yields the same elements.

For iterating from the front, the matches method can be used.

§Examples
let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
assert_eq!(v, ["abc", "abc", "abc"]);

let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
assert_eq!(v, ["3", "2", "1"]);
1.5.0 · Source

pub fn match_indices<P>(&self, pat: P) -> MatchIndices<'_, P> ⓘ
where P: Pattern,

Returns an iterator over the disjoint matches of a pattern within this string slice as well as the index that the match starts at.

For matches of pat within self that overlap, only the indices corresponding to the first match are returned.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Iterator behavior

The returned iterator will be a DoubleEndedIterator if the pattern allows a reverse search and forward/reverse search yields the same elements. This is true for, e.g., char, but not for &str.

If the pattern allows a reverse search but its results might differ from a forward search, the rmatch_indices method can be used.

§Examples
let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);

let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
assert_eq!(v, [(1, "abc"), (4, "abc")]);

let v: Vec<_> = "ababa".match_indices("aba").collect();
assert_eq!(v, [(0, "aba")]); // only the first `aba`
1.5.0 · Source

pub fn rmatch_indices<P>(&self, pat: P) -> RMatchIndices<'_, P> ⓘ
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns an iterator over the disjoint matches of a pattern within self, yielded in reverse order along with the index of the match.

For matches of pat within self that overlap, only the indices corresponding to the last match are returned.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Iterator behavior

The returned iterator requires that the pattern supports a reverse search, and it will be a DoubleEndedIterator if a forward/reverse search yields the same elements.

For iterating from the front, the match_indices method can be used.

§Examples
let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);

let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
assert_eq!(v, [(4, "abc"), (1, "abc")]);

let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
assert_eq!(v, [(2, "aba")]); // only the last `aba`
1.0.0 · Source

pub fn trim(&self) -> &str

Returns a string slice with leading and trailing whitespace removed.

‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property White_Space, which includes newlines.

§Examples
let s = "\n Hello\tworld\t\n";

assert_eq!("Hello\tworld", s.trim());
1.30.0 · Source

pub fn trim_start(&self) -> &str

Returns a string slice with leading whitespace removed.

‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property White_Space, which includes newlines.

§Text directionality

A string is a sequence of bytes. start in this context means the first position of that byte string; for a left-to-right language like English or Russian, this will be left side, and for right-to-left languages like Arabic or Hebrew, this will be the right side.

§Examples

Basic usage:

let s = "\n Hello\tworld\t\n";
assert_eq!("Hello\tworld\t\n", s.trim_start());

Directionality:

let s = "  English  ";
assert!(Some('E') == s.trim_start().chars().next());

let s = "  עברית  ";
assert!(Some('ע') == s.trim_start().chars().next());
1.30.0 · Source

pub fn trim_end(&self) -> &str

Returns a string slice with trailing whitespace removed.

‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property White_Space, which includes newlines.

§Text directionality

A string is a sequence of bytes. end in this context means the last position of that byte string; for a left-to-right language like English or Russian, this will be right side, and for right-to-left languages like Arabic or Hebrew, this will be the left side.

§Examples

Basic usage:

let s = "\n Hello\tworld\t\n";
assert_eq!("\n Hello\tworld", s.trim_end());

Directionality:

let s = "  English  ";
assert!(Some('h') == s.trim_end().chars().rev().next());

let s = "  עברית  ";
assert!(Some('ת') == s.trim_end().chars().rev().next());
1.0.0 · Source

pub fn trim_left(&self) -> &str

👎Deprecated since 1.33.0:

superseded by trim_start

Returns a string slice with leading whitespace removed.

‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property White_Space.

§Text directionality

A string is a sequence of bytes. ‘Left’ in this context means the first position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the right side, not the left.

§Examples

Basic usage:

let s = " Hello\tworld\t";

assert_eq!("Hello\tworld\t", s.trim_left());

Directionality:

let s = "  English";
assert!(Some('E') == s.trim_left().chars().next());

let s = "  עברית";
assert!(Some('ע') == s.trim_left().chars().next());
1.0.0 · Source

pub fn trim_right(&self) -> &str

👎Deprecated since 1.33.0:

superseded by trim_end

Returns a string slice with trailing whitespace removed.

‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property White_Space.

§Text directionality

A string is a sequence of bytes. ‘Right’ in this context means the last position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the left side, not the right.

§Examples

Basic usage:

let s = " Hello\tworld\t";

assert_eq!(" Hello\tworld", s.trim_right());

Directionality:

let s = "English  ";
assert!(Some('h') == s.trim_right().chars().rev().next());

let s = "עברית  ";
assert!(Some('ת') == s.trim_right().chars().rev().next());
1.0.0 · Source

pub fn trim_matches<P>(&self, pat: P) -> &str
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> DoubleEndedSearcher<'a>,

Returns a string slice with all prefixes and suffixes that match a pattern repeatedly removed.

The pattern can be a char, a slice of chars, or a function or closure that determines if a character matches.

§Examples

Simple patterns:

assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");

let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");

A more complex pattern, using a closure:

assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1.30.0 · Source

pub fn trim_start_matches<P>(&self, pat: P) -> &str
where P: Pattern,

Returns a string slice with all prefixes that match a pattern repeatedly removed.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Text directionality

A string is a sequence of bytes. start in this context means the first position of that byte string; for a left-to-right language like English or Russian, this will be left side, and for right-to-left languages like Arabic or Hebrew, this will be the right side.

§Examples
assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");

let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
1.45.0 · Source

pub fn strip_prefix<P>(&self, prefix: P) -> Option<&str>
where P: Pattern,

Returns a string slice with the prefix removed.

If the string starts with the pattern prefix, returns the substring after the prefix, wrapped in Some. Unlike trim_start_matches, this method removes the prefix exactly once.

If the string does not start with prefix, returns None.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Examples
assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
assert_eq!("foo:bar".strip_prefix("bar"), None);
assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
1.45.0 · Source

pub fn strip_suffix<P>(&self, suffix: P) -> Option<&str>
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns a string slice with the suffix removed.

If the string ends with the pattern suffix, returns the substring before the suffix, wrapped in Some. Unlike trim_end_matches, this method removes the suffix exactly once.

If the string does not end with suffix, returns None.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Examples
assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
assert_eq!("bar:foo".strip_suffix("bar"), None);
assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
1.98.0 · Source

pub fn strip_circumfix<P, S>(&self, prefix: P, suffix: S) -> Option<&str>
where P: Pattern, S: Pattern, <S as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns a string slice with the prefix and suffix removed.

If the string starts with the pattern prefix and ends with the pattern suffix, and the prefix and suffix don’t overlap, returns the substring after the prefix and before the suffix, wrapped in Some. Unlike trim_start_matches and trim_end_matches, this method removes both the prefix and suffix exactly once.

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

Each pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Examples
assert_eq!("bar:hello:foo".strip_circumfix("bar:", ":foo"), Some("hello"));
assert_eq!("bar:foo".strip_circumfix("foo", "foo"), None);
assert_eq!("foo:bar;".strip_circumfix("foo:", ';'), Some("bar"));
assert_eq!("foo:bar:baz".strip_circumfix("foo:bar:", ":bar:baz"), None);
1.100.0 · Source

pub fn trim_prefix<P>(&self, prefix: P) -> &str
where P: Pattern,

Returns a string slice with the optional prefix removed.

If the string starts with the pattern prefix, returns the substring after the prefix. Unlike strip_prefix, this method always returns &str for easy method chaining, instead of returning Option<&str>.

If the string does not start with prefix, returns the original string unchanged.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Examples
// Prefix present - removes it
assert_eq!("foo:bar".trim_prefix("foo:"), "bar");
assert_eq!("foofoo".trim_prefix("foo"), "foo");

// Prefix absent - returns original string
assert_eq!("foo:bar".trim_prefix("bar"), "foo:bar");

// Method chaining example
assert_eq!("<https://example.com/>".trim_prefix('<').trim_suffix('>'), "https://example.com/");
1.100.0 · Source

pub fn trim_suffix<P>(&self, suffix: P) -> &str
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns a string slice with the optional suffix removed.

If the string ends with the pattern suffix, returns the substring before the suffix. Unlike strip_suffix, this method always returns &str for easy method chaining, instead of returning Option<&str>.

If the string does not end with suffix, returns the original string unchanged.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Examples
// Suffix present - removes it
assert_eq!("bar:foo".trim_suffix(":foo"), "bar");
assert_eq!("foofoo".trim_suffix("foo"), "foo");

// Suffix absent - returns original string
assert_eq!("bar:foo".trim_suffix("bar"), "bar:foo");

// Method chaining example
assert_eq!("<https://example.com/>".trim_prefix('<').trim_suffix('>'), "https://example.com/");
1.30.0 · Source

pub fn trim_end_matches<P>(&self, pat: P) -> &str
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns a string slice with all suffixes that match a pattern repeatedly removed.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Text directionality

A string is a sequence of bytes. end in this context means the last position of that byte string; for a left-to-right language like English or Russian, this will be right side, and for right-to-left languages like Arabic or Hebrew, this will be the left side.

§Examples

Simple patterns:

assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");

let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");

A more complex pattern, using a closure:

assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
1.0.0 · Source

pub fn trim_left_matches<P>(&self, pat: P) -> &str
where P: Pattern,

👎Deprecated since 1.33.0:

superseded by trim_start_matches

Returns a string slice with all prefixes that match a pattern repeatedly removed.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Text directionality

A string is a sequence of bytes. ‘Left’ in this context means the first position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the right side, not the left.

§Examples
assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");

let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1.0.0 · Source

pub fn trim_right_matches<P>(&self, pat: P) -> &str
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

👎Deprecated since 1.33.0:

superseded by trim_end_matches

Returns a string slice with all suffixes that match a pattern repeatedly removed.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Text directionality

A string is a sequence of bytes. ‘Right’ in this context means the last position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the left side, not the right.

§Examples

Simple patterns:

assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");

let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");

A more complex pattern, using a closure:

assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
1.0.0 · Source

pub fn parse<F>(&self) -> Result<F, <F as FromStr>::Err>
where F: FromStr,

Parses this string slice into another type.

Because parse is so general, it can cause problems with type inference. As such, parse is one of the few times you’ll see the syntax affectionately known as the ‘turbofish’: ::<>. This helps the inference algorithm understand specifically which type you’re trying to parse into.

parse can parse into any type that implements the FromStr trait.

§Errors

Will return Err if it’s not possible to parse this string slice into the desired type.

§Examples

Basic usage:

let four: u32 = "4".parse().unwrap();

assert_eq!(4, four);

Using the ‘turbofish’ instead of annotating four:

let four = "4".parse::<u32>();

assert_eq!(Ok(4), four);

Failing to parse:

let nope = "j".parse::<u32>();

assert!(nope.is_err());
1.23.0 · Source

pub fn is_ascii(&self) -> bool

Checks if all characters in this string are within the ASCII range.

An empty string returns true.

§Examples
let ascii = "hello!\n";
let non_ascii = "Grüße, Jürgen ❤";

assert!(ascii.is_ascii());
assert!(!non_ascii.is_ascii());
Source

pub fn as_ascii(&self) -> Option<&[AsciiChar]>

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

If this string slice is_ascii, returns it as a slice of ASCII characters, otherwise returns None.

Source

pub unsafe fn as_ascii_unchecked(&self) -> &[AsciiChar]

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

Converts this string slice into a slice of ASCII characters, without checking whether they are valid.

§Safety

Every character in this string must be ASCII, or else this is UB.

1.23.0 · Source

pub fn eq_ignore_ascii_case(&self, other: &str) -> bool

Checks that two strings are an ASCII case-insensitive match.

Same as to_ascii_lowercase(a) == to_ascii_lowercase(b), but without allocating and copying temporaries.

For Unicode-aware case-insensitive matching, consider str::eq_ignore_case_unnormalized.

§Examples
assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
Source

pub fn eq_ignore_case_unnormalized(&self, other: &str) -> bool

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

Checks that two strings are a caseless match, according to Definition 144 in Chapter 3 of the Unicode Standard.

Same as a.to_casefold_unnormalized() == b.to_casefold_unnormalized(), but without allocating. See that method’s documentation, as well as char::to_casefold_unnormalized(), for more information about case folding.

No normalization (e.g. NFC) is performed, so visually and semantically identical strings might still compare unequal. For example, "Å" (U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE) is considered distinct from "Å" (A followed by U+030A COMBINING RING ABOVE), even though Unicode considers them canonically equivalent.

In addition, this method is independent of language/locale, so the special behavior of I/ı/İ/i in Turkish and Azeri is not handled.

§Examples
#![feature(casefold)]
assert!("Ferris".eq_ignore_case_unnormalized("FERRIS"));
assert!("Ferrös".eq_ignore_case_unnormalized("FERRÖS"));
assert!("ẞ".eq_ignore_case_unnormalized("ss"));

No NFC normalization is performed:

#![feature(casefold)]
// These two strings are visually and semantically identical...
let comp = "Å";
let decomp = "Å";

// ... but not codepoint-for-codepoint equal.
assert_eq!(comp, "\u{C5}");
assert_eq!(decomp, "A\u{030A}");

// Their case-foldings are likewise unequal:
assert!(!comp.eq_ignore_case_unnormalized(decomp));
1.23.0 · Source

pub fn make_ascii_uppercase(&mut self)

Converts this string to its ASCII upper case equivalent in-place.

ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but all other characters are unchanged.

To return a new uppercased value without modifying the existing one, use to_ascii_uppercase().

§Examples
let mut s = String::from("Grüße, Jürgen ❤");

s.make_ascii_uppercase();

assert_eq!("GRüßE, JüRGEN ❤", s);
1.23.0 · Source

pub fn make_ascii_lowercase(&mut self)

Converts this string to its ASCII lower case equivalent in-place.

ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but all other characters are unchanged.

To return a new lowercased value without modifying the existing one, use to_ascii_lowercase().

§Examples
let mut s = String::from("GRÜßE, JÜRGEN ❤");

s.make_ascii_lowercase();

assert_eq!("grÜße, jÜrgen ❤", s);
Source

pub fn copy_from_str(&mut self, src: &str)

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

Copies the string from src into self, using a memcpy.

The length of src must be the same as self.

§Panics

This function will panic if the two strings have different lengths.

§Examples
#![feature(str_copy_from_str)]
let src = "Saludos";
let mut dst = String::from("Grüße, Jürgen");

// Because the strings have to be the same length,
// we slice the destination slice from sixteen bytes
// to seven. It will panic if we don't do this.
dst[..7].copy_from_str(src);

assert_eq!(src, "Saludos");
assert_eq!(dst, "Saludos, Jürgen");

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_str on a single string will result in a compile failure:

ⓘ
#![feature(str_copy_from_str)]
let mut string = String::from("Abcde");

string[..2].copy_from_str(&string[3..]); // compile fail!

To work around this, we can use split_at_mut to create two distinct sub-slices from a string:

#![feature(str_copy_from_str)]
let mut string = String::from("Abcde");

{
    let (left, right) = string.split_at_mut(2);
    left.copy_from_str(&right[1..]);
}

assert_eq!(string, "decde");
1.80.0 · Source

pub fn trim_ascii_start(&self) -> &str

Returns a string slice with leading ASCII whitespace removed.

‘Whitespace’ refers to the definition used by u8::is_ascii_whitespace. Importantly, this definition excludes the U+000B code point even though it has the Unicode White_Space property and is removed by str::trim_start.

§Examples
assert_eq!(" \t \u{3000}hello world\n".trim_ascii_start(), "\u{3000}hello world\n");
assert_eq!("  ".trim_ascii_start(), "");
assert_eq!("".trim_ascii_start(), "");
1.80.0 · Source

pub fn trim_ascii_end(&self) -> &str

Returns a string slice with trailing ASCII whitespace removed.

‘Whitespace’ refers to the definition used by u8::is_ascii_whitespace. Importantly, this definition excludes the U+000B code point even though it has the Unicode White_Space property and is removed by str::trim_end.

§Examples
assert_eq!("\r hello world\u{3000}\n ".trim_ascii_end(), "\r hello world\u{3000}");
assert_eq!("  ".trim_ascii_end(), "");
assert_eq!("".trim_ascii_end(), "");
1.80.0 · Source

pub fn trim_ascii(&self) -> &str

Returns a string slice with leading and trailing ASCII whitespace removed.

‘Whitespace’ refers to the definition used by u8::is_ascii_whitespace. Importantly, this definition excludes the U+000B code point even though it has the Unicode White_Space property and is removed by str::trim.

§Examples
assert_eq!("\r hello world\n ".trim_ascii(), "hello world");
assert_eq!("  ".trim_ascii(), "");
assert_eq!("".trim_ascii(), "");
1.34.0 · Source

pub fn escape_debug(&self) -> EscapeDebug<'_> ⓘ

Returns an iterator that escapes each char in self with char::escape_debug.

§Examples

As an iterator:

for c in "❤\n!".escape_debug() {
    print!("{c}");
}
println!();

Using println! directly:

println!("{}", "❤\n!".escape_debug());

Both are equivalent to:

println!("❤\\n!");

Using to_string:

assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
1.34.0 · Source

pub fn escape_default(&self) -> EscapeDefault<'_> ⓘ

Returns an iterator that escapes each char in self with char::escape_default.

§Examples

As an iterator:

for c in "❤\n!".escape_default() {
    print!("{c}");
}
println!();

Using println! directly:

println!("{}", "❤\n!".escape_default());

Both are equivalent to:

println!("\\u{{2764}}\\n!");

Using to_string:

assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
1.34.0 · Source

pub fn escape_unicode(&self) -> EscapeUnicode<'_> ⓘ

Returns an iterator that escapes each char in self with char::escape_unicode.

§Examples

As an iterator:

for c in "❤\n!".escape_unicode() {
    print!("{c}");
}
println!();

Using println! directly:

println!("{}", "❤\n!".escape_unicode());

Both are equivalent to:

println!("\\u{{2764}}\\u{{a}}\\u{{21}}");

Using to_string:

assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
1.98.0 · Source

pub fn substr_range(&self, substr: &str) -> Option<Range<usize>>

Returns the range that a substring points to.

Returns None if substr does not point within self.

Unlike str::find, this does not search through the string. Instead, it uses pointer arithmetic to find where in the string substr is derived from.

This is useful for extending str::split and similar methods.

Note that this method may return false positives (typically either Some(0..0) or Some(self.len()..self.len())) if substr is a zero-length str that points at the beginning or end of another, independent, str.

§Examples
use core::range::Range;

let data = "a, b, b, a";
let mut iter = data.split(", ").map(|s| data.substr_range(s).unwrap());

assert_eq!(iter.next(), Some(Range { start: 0, end: 1 }));
assert_eq!(iter.next(), Some(Range { start: 3, end: 4 }));
assert_eq!(iter.next(), Some(Range { start: 6, end: 7 }));
assert_eq!(iter.next(), Some(Range { start: 9, end: 10 }));
Source

pub fn as_str(&self) -> &str

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

Returns the same string as a string slice &str.

This method is redundant when used directly on &str, but it helps dereferencing other string-like types to string slices, for example references to Box<str> or Arc<str>.

1.0.0 · Source

pub fn replace<P>(&self, from: P, to: &str) -> String
where P: Pattern,

Available on non-no_global_oom_handling only.

Replaces all matches of a pattern with another string.

replace creates a new String, and copies the data from this string slice into it. While doing so, it attempts to find matches of a pattern. If it finds any, it replaces them with the replacement string slice.

§Examples
let s = "this is old";

assert_eq!("this is new", s.replace("old", "new"));
assert_eq!("than an old", s.replace("is", "an"));

When the pattern doesn’t match, it returns this string slice as String:

let s = "this is old";
assert_eq!(s, s.replace("cookie monster", "little lamb"));
Examples found in repository?
examples/testbed/ui.rs (line 941)
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    }
1.16.0 · Source

pub fn replacen<P>(&self, pat: P, to: &str, count: usize) -> String
where P: Pattern,

Available on non-no_global_oom_handling only.

Replaces first N matches of a pattern with another string.

replacen creates a new String, and copies the data from this string slice into it. While doing so, it attempts to find matches of a pattern. If it finds any, it replaces them with the replacement string slice at most count times.

§Examples
let s = "foo foo 123 foo";
assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));

When the pattern doesn’t match, it returns this string slice as String:

let s = "this is old";
assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
1.2.0 · Source

pub fn to_lowercase(&self) -> String

Available on non-no_global_oom_handling only.

Returns the lowercase equivalent of this string slice, as a new String.

‘Lowercase’ is defined according to the terms of Chapter 3 (Conformance) of the Unicode standard.

Since some characters can expand into multiple characters when changing the case, this function returns a String instead of modifying the parameter in-place.

Unlike char::to_lowercase(), this method fully handles the context-dependent casing of Greek sigma. However, like that method, it does not handle locale-specific casing, like Turkish and Azeri I/ı/İ/i. See its documentation for more information.

§Examples

Basic usage:

let s = "HELLO WORLD";

assert_eq!("hello world", s.to_lowercase());

Tricky examples, with sigma:

let sigma = "Σ";

assert_eq!("σ", sigma.to_lowercase());

// but at the end of a word, it's ς, not σ:
let odysseus = "ὈΔΥΣΣΕΎΣ";

assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());

let odysseus_king_of_ithaca = "Ο ΟΔΥΣΣΈΑΣ ΒΑΣΙΛΙΆΣ ΤΗΣ ΙΘΆΚΗΣ";

assert_eq!("ο οδυσσέας βασιλιάς της ιθάκης", odysseus_king_of_ithaca.to_lowercase());

Languages without case are not changed:

let new_year = "农历新年";

assert_eq!(new_year, new_year.to_lowercase());
Examples found in repository?
examples/testbed/ui.rs (line 166)
164    fn from_str(s: &str) -> Result<Self, Self::Err> {
165        let mut isit = Self::default();
166        while s.to_lowercase() != format!("{isit:?}").to_lowercase() {
167            isit = isit.next();
168            if isit == Self::default() {
169                return Err(format!("Invalid Scene name: {s}"));
170            }
171        }
172        Ok(isit)
173    }
More examples
Hide additional examples
examples/testbed/2d.rs (line 84)
82    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
83        let mut isit = Self::default();
84        while s.to_lowercase() != format!("{isit:?}").to_lowercase() {
85            isit = isit.next();
86            if isit == Self::default() {
87                return Err(format!("Invalid Scene name: {s}"));
88            }
89        }
90        Ok(isit)
91    }
examples/testbed/3d.rs (line 96)
94    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
95        let mut isit = Self::default();
96        while s.to_lowercase() != format!("{isit:?}").to_lowercase() {
97            isit = isit.next();
98            if isit == Self::default() {
99                return Err(format!("Invalid Scene name: {s}"));
100            }
101        }
102        Ok(isit)
103    }
Source

pub fn word_to_titlecase(&self) -> String

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

Returns the titlecase equivalent of this string slice, which is assumed to represent a single word, as a new String.

Essentially, this consists of uppercasing the first cased letter (with char::to_titlecase()), and lowercasing everything that follows.

‘Titlecase’ is defined according to the terms of Chapter 3 (Conformance) of the Unicode standard.

Since some characters can expand into multiple characters when changing the case, this function returns a String instead of modifying the parameter in-place.

Unlike char::to_lowercase(), this method fully handles the context-dependent casing of Greek sigma. However, like that method, it does not handle locale-specific casing, like Turkish and Azeri I/ı/İ/i. See its documentation for more information.

This method does not perform any kind of word segmentation.

§Examples

Basic usage:

#![feature(titlecase)]
let s = "HELLO WORLD";

assert_eq!("Hello world", s.word_to_titlecase());

The first cased letter is uppercased:

#![feature(titlecase)]
let the_night_before_christmas = "'twas";

assert_eq!("'Twas", the_night_before_christmas.word_to_titlecase());

Languages without case are not changed:

#![feature(titlecase)]
let new_year = "农历新年";

assert_eq!(new_year, new_year.word_to_titlecase());

Georgian uppercase (“Mtavruli”) letters are not used in titlecase:

#![feature(titlecase)]
let georgian = "ერთობაშია";

assert_eq!(georgian, georgian.word_to_titlecase());

No word segmentation is performed, so only the first cased letter in the whole string gets uppercased:

#![feature(titlecase)]
let blazingly_fast = "ferris and I";

assert_eq!("Ferris and i", blazingly_fast.word_to_titlecase());

Tricky examples, with sigma:

#![feature(titlecase)]
let odysseus = "ὈΔΥΣΣΕΎΣ";

assert_eq!("Ὀδυσσεύς", odysseus.word_to_titlecase());

let odysseus_king_of_ithaca = "Ο ΟΔΥΣΣΈΑΣ ΒΑΣΙΛΙΆΣ ΤΗΣ ΙΘΆΚΗΣ";

assert_eq!("Ο οδυσσέας βασιλιάς της ιθάκης", odysseus_king_of_ithaca.word_to_titlecase());
1.2.0 · Source

pub fn to_uppercase(&self) -> String

Available on non-no_global_oom_handling only.

Returns the uppercase equivalent of this string slice, as a new String.

‘Uppercase’ is defined according to the terms of Chapter 3 (Conformance) of the Unicode standard.

Since some characters can expand into multiple characters when changing the case, this function returns a String instead of modifying the parameter in-place.

Like char::to_uppercase() this method does not handle language-specific casing, like Turkish and Azeri I/ı/İ/i. See that method’s documentation for more information.

§Examples

Basic usage:

let s = "hello world";

assert_eq!("HELLO WORLD", s.to_uppercase());

Scripts without case are not changed:

let new_year = "农历新年";

assert_eq!(new_year, new_year.to_uppercase());

One character can become multiple:

let s = "tschüß";

assert_eq!("TSCHÜSS", s.to_uppercase());
Source

pub fn to_casefold_unnormalized(&self) -> String

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

Returns the case-folded equivalent of this string slice, as a new String.

Case folding is a transformation, mostly matching lowercase, that is meant to be used for case-insensitive string comparisons. Case-folded strings should not usually be exposed directly to users.

For the precise specification of case folding, see Chapter 3 (Conformance) of the Unicode standard.

Since some characters can expand into multiple characters when case folding, this function returns a String instead of modifying the parameter in-place.

No normalization (e.g. NFC) is performed, so visually and semantically identical strings might still casefold differently. For example, "Å" (U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE) is considered distinct from "Å" (A followed by U+030A COMBINING RING ABOVE), even though Unicode considers them canonically equivalent.

Like char::to_casefold_unnormalized() this method does not handle language-specific casing, like Turkish and Azeri I/ı/İ/i. See that method’s documentation for more information.

§Examples

Basic usage:

#![feature(casefold)]
let s0 = "HELLO";
let s1 = "Hello";

assert_eq!(s0.to_casefold_unnormalized(), s1.to_casefold_unnormalized());
assert_eq!(s0.to_casefold_unnormalized(), "hello")

Scripts without case are not changed:

#![feature(casefold)]
let new_year = "农历新年";

assert_eq!(new_year, new_year.to_casefold_unnormalized());

One character can become multiple:

#![feature(casefold)]
let s0 = "TSCHÜẞ";
let s1 = "TSCHÜSS";
let s2 = "tschüß";

assert_eq!(s0.to_casefold_unnormalized(), s1.to_casefold_unnormalized());
assert_eq!(s0.to_casefold_unnormalized(), s2.to_casefold_unnormalized());
assert_eq!(s0.to_casefold_unnormalized(), "tschüss");

No NFC normalization is performed:

#![feature(casefold)]
// These two strings are visually and semantically identical...
let comp = "Å";
let decomp = "Å";

// ... but not codepoint-for-codepoint equal.
assert_eq!(comp, "\u{C5}");
assert_eq!(decomp, "A\u{030A}");

// Their case-foldings are likewise unequal:
assert_eq!(comp.to_casefold_unnormalized(), "\u{E5}");
assert_eq!(decomp.to_casefold_unnormalized(), "a\u{030A}");
1.16.0 · Source

pub fn repeat(&self, n: usize) -> String

Available on non-no_global_oom_handling only.

Creates a new String by repeating a string n times.

§Panics

This function will panic if the capacity would overflow.

§Examples

Basic usage:

assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));

A panic upon overflow:

ⓘ
// this will panic at runtime
let huge = "0123456789abcdef".repeat(usize::MAX);
Examples found in repository?
examples/stress_tests/many_glyphs.rs (line 68)
64fn setup(mut commands: Commands, args: Res<Args>) {
65    warn!(include_str!("warning_string.txt"));
66
67    commands.spawn(Camera2d);
68    let text_string = "0123456789".repeat(10_000);
69    let text_font = TextFont {
70        font_size: FontSize::Px(4.),
71        ..Default::default()
72    };
73    let text_block = TextLayout {
74        justify: Justify::Left,
75        linebreak: LineBreak::AnyCharacter,
76    };
77
78    if !args.no_ui {
79        commands
80            .spawn(Node {
81                width: percent(100),
82                align_items: AlignItems::Center,
83                justify_content: JustifyContent::Center,
84                ..default()
85            })
86            .with_children(|commands| {
87                commands
88                    .spawn(Node {
89                        width: px(1000),
90                        ..Default::default()
91                    })
92                    .with_child((Text(text_string.clone()), text_font.clone(), text_block));
93            });
94    }
95
96    if !args.no_text2d {
97        commands.spawn((
98            Text2d::new(text_string),
99            text_font.clone(),
100            TextColor(RED.into()),
101            bevy::sprite::Anchor::CENTER,
102            TextBounds::new_horizontal(1000.),
103            text_block,
104        ));
105    }
106}
More examples
Hide additional examples
examples/stress_tests/text_pipeline.rs (line 42)
34fn spawn(mut commands: Commands, asset_server: Res<AssetServer>) {
35    warn!(include_str!("warning_string.txt"));
36
37    commands.spawn(Camera2d);
38
39    let make_spans = |i| {
40        [
41            (
42                TextSpan("text".repeat(i)),
43                TextFont {
44                    font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
45                    font_size: FontSize::Px((4 + i % 10) as f32),
46                    ..Default::default()
47                },
48                TextColor(BLUE.into()),
49            ),
50            (
51                TextSpan("pipeline".repeat(i)),
52                TextFont {
53                    font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
54                    font_size: FontSize::Px((4 + i % 11) as f32),
55                    ..default()
56                },
57                TextColor(YELLOW.into()),
58            ),
59        ]
60    };
61
62    let spans = (1..50).flat_map(|i| make_spans(i).into_iter());
63
64    commands
65        .spawn((
66            Text2d::default(),
67            TextLayout {
68                justify: Justify::Center,
69                linebreak: LineBreak::AnyCharacter,
70            },
71            TextBounds::default(),
72        ))
73        .with_children(|p| {
74            for span in spans {
75                p.spawn(span);
76            }
77        });
78}
1.23.0 · Source

pub fn to_ascii_uppercase(&self) -> String

Available on non-no_global_oom_handling only.

Returns a copy of this string where each character is mapped to its ASCII upper case equivalent.

ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged.

To uppercase the value in-place, use make_ascii_uppercase.

To uppercase ASCII characters in addition to non-ASCII characters, use to_uppercase.

§Examples
let s = "Grüße, Jürgen ❤";

assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
1.23.0 · Source

pub fn to_ascii_lowercase(&self) -> String

Available on non-no_global_oom_handling only.

Returns a copy of this string where each character is mapped to its ASCII lower case equivalent.

ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but non-ASCII letters are unchanged.

To lowercase the value in-place, use make_ascii_lowercase.

To lowercase ASCII characters in addition to non-ASCII characters, use to_lowercase.

§Examples
let s = "Grüße, Jürgen ❤";

assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());

Trait Implementations§

Source§

impl Clone for TextSpan

Source§

fn clone(&self) -> TextSpan

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Component for TextSpan
where TextSpan: Send + Sync + 'static,

Required Components: TextFont, TextColor, LineHeight, LetterSpacing.

A component’s Required Components are inserted whenever it is inserted. Note that this will also insert the required components of the required components, recursively, in depth-first order.

Source§

const STORAGE_TYPE: StorageType = bevy_ecs::component::StorageType::Table

A constant indicating the storage type used for this component.
Source§

type Mutability = Mutable

A marker type to assist Bevy with determining if this component is mutable, or immutable. Mutable components will have Component<Mutability = Mutable>, while immutable components will instead have Component<Mutability = Immutable>. Read more
Source§

fn register_required_components( _requiree: ComponentId, required_components: &mut RequiredComponentsRegistrator<'_, '_>, )

Registers required components. Read more
Source§

fn clone_behavior() -> ComponentCloneBehavior

Called when registering this component, allowing to override clone function (or disable cloning altogether) for this component. Read more
Source§

fn relationship_accessor() -> Option<ComponentRelationshipAccessor<TextSpan>>

Returns ComponentRelationshipAccessor required for working with relationships in dynamic contexts. Read more
Source§

fn on_add() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_add ComponentHook for this Component if one is defined.
Source§

fn on_insert() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_insert ComponentHook for this Component if one is defined.
Source§

fn on_discard() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_discard ComponentHook for this Component if one is defined.
Source§

fn on_remove() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_remove ComponentHook for this Component if one is defined.
Source§

fn on_despawn() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_despawn ComponentHook for this Component if one is defined.
Source§

fn map_entities<E>(_this: &mut Self, _mapper: &mut E)
where E: EntityMapper,

Maps the entities on this component using the given EntityMapper. This is used to remap entities in contexts like scenes and entity cloning. When deriving Component, this is populated by annotating fields containing entities with #[entities] Read more
Source§

const HAS_SUMMARY_TICK: bool = false

Set this constant to true if the component should track a summary tick. Read more
Source§

impl Debug for TextSpan

Source§

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

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

impl Default for TextSpan

Source§

fn default() -> TextSpan

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

impl Deref for TextSpan

Source§

type Target = String

The resulting type after dereferencing.
Source§

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

Dereferences the value.
Source§

impl DerefMut for TextSpan

Source§

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

Mutably dereferences the value.
Source§

impl From<&str> for TextSpan

Source§

fn from(value: &str) -> TextSpan

Converts to this type from the input type.
Source§

impl From<String> for TextSpan

Source§

fn from(value: String) -> TextSpan

Converts to this type from the input type.
Source§

impl FromArg for TextSpan

Source§

type This<'from_arg> = TextSpan

The type to convert into. Read more
Source§

fn from_arg(arg: Arg<'_>) -> Result<<TextSpan as FromArg>::This<'_>, ArgError>

Creates an item from an argument. Read more
Source§

impl FromReflect for TextSpan

Source§

fn from_reflect(reflect: &(dyn PartialReflect + 'static)) -> Option<TextSpan>

Constructs a concrete instance of Self from a reflected value.
Source§

fn take_from_reflect( reflect: Box<dyn PartialReflect>, ) -> Result<Self, Box<dyn PartialReflect>>

Attempts to downcast the given value to Self using, constructing the value using from_reflect if that fails. Read more
Source§

impl GetOwnership for TextSpan

Source§

fn ownership() -> Ownership

Returns the ownership of Self.
Source§

impl GetTypeRegistration for TextSpan

Source§

fn get_type_registration() -> TypeRegistration

Returns the default TypeRegistration for this type.
Source§

fn register_type_dependencies(registry: &mut TypeRegistry)

Registers other types needed by this type. Read more
Source§

impl IntoReturn for TextSpan

Source§

fn into_return<'into_return>(self) -> Return<'into_return>
where TextSpan: 'into_return,

Converts Self into a Return value.
Source§

impl PartialReflect for TextSpan

Source§

fn get_represented_type_info(&self) -> Option<&'static TypeInfo>

Returns the TypeInfo of the type represented by this value. Read more
Source§

fn try_apply( &mut self, value: &(dyn PartialReflect + 'static), ) -> Result<(), ApplyError>

Tries to apply a reflected value to this value. Read more
Source§

fn reflect_kind(&self) -> ReflectKind

Returns a zero-sized enumeration of “kinds” of type. Read more
Source§

fn reflect_ref(&self) -> ReflectRef<'_>

Returns an immutable enumeration of “kinds” of type. Read more
Source§

fn reflect_mut(&mut self) -> ReflectMut<'_>

Returns a mutable enumeration of “kinds” of type. Read more
Source§

fn reflect_owned(self: Box<TextSpan>) -> ReflectOwned

Returns an owned enumeration of “kinds” of type. Read more
Source§

fn try_into_reflect( self: Box<TextSpan>, ) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>>

Attempts to cast this type to a boxed, fully-reflected value.
Source§

fn try_as_reflect(&self) -> Option<&(dyn Reflect + 'static)>

Attempts to cast this type to a fully-reflected value.
Source§

fn try_as_reflect_mut(&mut self) -> Option<&mut (dyn Reflect + 'static)>

Attempts to cast this type to a mutable, fully-reflected value.
Source§

fn into_partial_reflect(self: Box<TextSpan>) -> Box<dyn PartialReflect>

Casts this type to a boxed, reflected value. Read more
Source§

fn as_partial_reflect(&self) -> &(dyn PartialReflect + 'static)

Casts this type to a reflected value. Read more
Source§

fn as_partial_reflect_mut(&mut self) -> &mut (dyn PartialReflect + 'static)

Casts this type to a mutable, reflected value. Read more
Source§

fn reflect_partial_eq( &self, value: &(dyn PartialReflect + 'static), ) -> Option<bool>

Returns a “partial equality” comparison result. Read more
Source§

fn reflect_partial_cmp( &self, value: &(dyn PartialReflect + 'static), ) -> Option<Ordering>

Returns a “partial comparison” result. Read more
Source§

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

Debug formatter for the value. Read more
Source§

fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError>

Attempts to clone Self using reflection. Read more
Source§

fn apply(&mut self, value: &(dyn PartialReflect + 'static))

Applies a reflected value to this value. Read more
Source§

fn to_dynamic(&self) -> Result<Box<dyn PartialReflect>, ReflectCloneError>

Converts this reflected value into its dynamic representation based on its kind. Read more
Source§

fn reflect_clone_and_take<T>(&self) -> Result<T, ReflectCloneError>
where T: 'static, Self: Sized + TypePath,

For a type implementing PartialReflect, combines reflect_clone and take in a useful fashion, automatically constructing an appropriate ReflectCloneError if the downcast fails.
Source§

fn reflect_hash(&self) -> Option<u64>

Returns a hash of the value (which includes the type). Read more
Source§

fn is_dynamic(&self) -> bool

Indicates whether or not this type is a dynamic type. Read more
Source§

impl Reflect for TextSpan

Source§

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

Returns the value as a Box<dyn Any>. Read more
Source§

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

Returns the value as a &dyn Any. Read more
Source§

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

Returns the value as a &mut dyn Any. Read more
Source§

fn into_reflect(self: Box<TextSpan>) -> Box<dyn Reflect>

Casts this type to a boxed, fully-reflected value.
Source§

fn as_reflect(&self) -> &(dyn Reflect + 'static)

Casts this type to a fully-reflected value.
Source§

fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)

Casts this type to a mutable, fully-reflected value.
Source§

fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>>

Performs a type-checked assignment of a reflected value to this value. Read more
Source§

impl TextSection for TextSpan

Source§

fn get_text(&self) -> &str

Returns the text for this section.
Source§

fn get_text_mut(&mut self) -> &mut String

Returns a mutable reference to the text for this section.
Source§

impl TupleStruct for TextSpan

Source§

fn field(&self, index: usize) -> Option<&(dyn PartialReflect + 'static)>

Returns a reference to the value of the field with index index as a &dyn Reflect.
Source§

fn field_mut( &mut self, index: usize, ) -> Option<&mut (dyn PartialReflect + 'static)>

Returns a mutable reference to the value of the field with index index as a &mut dyn Reflect.
Source§

fn field_len(&self) -> usize

Returns the number of fields in the tuple struct.
Source§

fn iter_fields(&self) -> TupleStructFieldIter<'_> ⓘ

Returns an iterator over the values of the tuple struct’s fields.
Source§

fn to_dynamic_tuple_struct( &self, ) -> Result<DynamicTupleStruct, ReflectCloneError>

Creates a new DynamicTupleStruct from this tuple struct. Read more
Source§

fn get_represented_tuple_struct_info(&self) -> Option<&'static TupleStructInfo>

Will return None if TypeInfo is not available.
Source§

impl TypePath for TextSpan

Source§

fn type_path() -> &'static str

Returns the fully qualified path of the underlying type. Read more
Source§

fn short_type_path() -> &'static str

Returns a short, pretty-print enabled path to the type. Read more
Source§

fn type_ident() -> Option<&'static str>

Returns the name of the type, or None if it is anonymous. Read more
Source§

fn crate_name() -> Option<&'static str>

Returns the name of the crate the type is in, or None if it is anonymous. Read more
Source§

fn module_path() -> Option<&'static str>

Returns the path to the module the type is in, or None if it is anonymous. Read more
Source§

impl Typed for TextSpan

Source§

fn type_info() -> &'static TypeInfo

Returns the compile-time info for the underlying type.

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<C> Bundle for C
where C: Component,

Source§

fn component_ids( components: &mut ComponentsRegistrator<'_>, ) -> impl Iterator<Item = ComponentId> + use<C>

Source§

fn get_component_ids( components: &Components, ) -> impl Iterator<Item = Option<ComponentId>>

Returns an iterator over this Bundle’s component ids. This will be None if the component has not been registered.
Source§

impl<C> BundleFromComponents for C
where C: Component,

Source§

unsafe fn from_components<T, F>(ctx: &mut T, func: &mut F) -> C
where F: for<'a> FnMut(&'a mut T) -> OwningPtr<'a>, C: Sized,

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> 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<C> DynamicBundle for C
where C: Component,

Source§

type Effect = ()

An operation on the entity that happens after inserting this bundle.
Source§

unsafe fn get_components( ptr: MovingPtr<'_, C>, func: &mut impl FnMut(StorageType, OwningPtr<'_>), ) -> <C as DynamicBundle>::Effect

Moves the components out of the bundle. Read more
Source§

unsafe fn apply_effect( _ptr: MovingPtr<'_, MaybeUninit<C>>, _entity: &mut EntityWorldMut<'_>, )

Applies the after-effects of spawning this bundle. Read more
Source§

impl<T> DynamicTypePath for T
where T: TypePath,

Source§

impl<T> DynamicTyped for T
where T: Typed,

Source§

impl<T> ErasedBundleTemplate for T
where T: Template + Send + Sync + 'static, <T as Template>::Output: Bundle,

Source§

unsafe fn apply( &self, context: &mut TemplateContext<'_, '_>, ) -> Result<(), BevyError>

Applies this template to the given entity. Read more
Source§

fn clone_template(&self) -> Box<dyn ErasedBundleTemplate>

Clones this template. See Clone.
Source§

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

Source§

impl<T> ErasedTemplate for T
where T: Template + Send + Sync + 'static, <T as Template>::Output: SceneEffect,

Source§

unsafe fn apply( &self, context: &mut TemplateContext<'_, '_>, bundle_writer: &mut BundleWriter<'_>, ) -> Result<(), BevyError>

Applies this template to the given entity. Read more
Source§

fn clone_template(&self) -> Box<dyn ErasedTemplate>

Clones this template. See Clone.
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> FromTemplate for T
where T: Clone + Default + Unpin,

Source§

type Template = T

The Template for this type.
Source§

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

Source§

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

Creates Self using default().

Source§

impl<T> GetPath for T
where T: Reflect + ?Sized,

Source§

fn reflect_path<'p>( &self, path: impl ReflectPath<'p>, ) -> Result<&(dyn PartialReflect + 'static), ReflectPathError<'p>>

Returns a reference to the value specified by path. Read more
Source§

fn reflect_path_mut<'p>( &mut self, path: impl ReflectPath<'p>, ) -> Result<&mut (dyn PartialReflect + 'static), ReflectPathError<'p>>

Returns a mutable reference to the value specified by path. Read more
Source§

fn path<'p, T>( &self, path: impl ReflectPath<'p>, ) -> Result<&T, ReflectPathError<'p>>
where T: Reflect,

Returns a statically typed reference to the value specified by path. Read more
Source§

fn path_mut<'p, T>( &mut self, path: impl ReflectPath<'p>, ) -> Result<&mut T, ReflectPathError<'p>>
where T: Reflect,

Returns a statically typed mutable reference to the value specified by path. Read more
Source§

impl<S> GetTupleStructField for S
where S: TupleStruct,

Source§

fn get_field<T>(&self, index: usize) -> Option<&T>
where T: Reflect,

Returns a reference to the value of the field with index index, downcast to T.
Source§

fn get_field_mut<T>(&mut self, index: usize) -> Option<&mut T>
where T: Reflect,

Returns a mutable reference to the value of the field with index index, downcast to T.
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> HitDataExtra for T
where T: Send + Sync + Debug + Any + 'static,

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<G> PatchFromTemplate for G
where G: FromTemplate,

Source§

type Template = <G as FromTemplate>::Template

The Template that will be patched.
Source§

fn patch<F>(func: F) -> TemplatePatch<F, <G as PatchFromTemplate>::Template>
where F: FnOnce(&mut <G as PatchFromTemplate>::Template, &mut ResolveContext<'_>),

Takes a “patch function” func, and turns it into a TemplatePatch.
Source§

impl<T> PatchTemplate for T
where T: Template,

Source§

fn patch_template<F>(func: F) -> TemplatePatch<F, T>
where F: FnOnce(&mut T, &mut ResolveContext<'_>),

Takes a “patch function” func that patches this Template, and turns it into a TemplatePatch.
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> Reflectable for T

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<C> SceneEffect for C
where C: Component,

Source§

fn apply( self, context: &mut TemplateContext<'_, '_>, bundle_writer: &mut BundleWriter<'_>, )

Applies the scene effect to the current context.
Source§

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

Source§

impl<T> Source for T
where T: Deref, <T as Deref>::Target: Source,

Source§

type Slice<'a> = <<T as Deref>::Target as Source>::Slice<'a> where T: 'a

A type this Source can be sliced into.
Source§

fn len(&self) -> usize

Length of the source
Source§

fn read<'a, Chunk>(&'a self, offset: usize) -> Option<Chunk>
where Chunk: Chunk<'a>,

Read a chunk of bytes into an array. Returns None when reading out of bounds would occur. Read more
Source§

fn slice(&self, range: Range<usize>) -> Option<<T as Source>::Slice<'_>>

Get a slice of the source at given range. This is analogous to slice::get(range). Read more
Source§

unsafe fn slice_unchecked( &self, range: Range<usize>, ) -> <T as Source>::Slice<'_>

Available on non-crate feature forbid_unsafe only.
Get a slice of the source at given range. This is analogous to slice::get_unchecked(range). Read more
Source§

fn is_boundary(&self, index: usize) -> bool

Check if index is valid for this Source, that is: Read more
Source§

fn find_boundary(&self, index: usize) -> usize

For &str sources attempts to find the closest char boundary at which source can be sliced, starting from index. Read more
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> Template for T
where T: Clone + Unpin,

Source§

type Output = T

The type of value produced by this Template.
Source§

fn build_template( &self, _context: &mut TemplateContext<'_, '_>, ) -> Result<<T as Template>::Output, BevyError>

Uses this template and the given entity context to produce a Template::Output.
Source§

fn clone_template(&self) -> T

Clones this template. See Clone.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> 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<T> TypeData for T
where T: 'static + Send + Sync + Clone,

Source§

fn clone_type_data(&self) -> Box<dyn TypeData>

Creates a type-erased clone of self.
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