Struct Text

Source
pub struct Text(pub String);
Expand description

The top-level UI text component.

Adding Text to an entity will pull in required components for setting up a UI text node.

The string in this component is the first ‘text span’ in a hierarchy of text spans that are collected into a ComputedTextBlock. See TextSpan for the component used by children of entities with Text.

Note that Transform on this entity is managed automatically by the UI layout system.

// Basic usage.
world.spawn(Text::new("hello world!"));

// With non-default style.
world.spawn((
    Text::new("hello world!"),
    TextFont {
        font: font_handle.clone().into(),
        font_size: 60.0,
        ..Default::default()
    },
    TextColor(BLUE.into()),
));

// With text justification.
world.spawn((
    Text::new("hello world\nand bevy!"),
    TextLayout::new_with_justify(JustifyText::Center)
));

// With spans
world.spawn(Text::new("hello ")).with_children(|parent| {
    parent.spawn(TextSpan::new("world"));
    parent.spawn((TextSpan::new("!"), TextColor(BLUE.into())));
});

Tuple Fields§

§0: String

Implementations§

Source§

impl Text

Source

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

Makes a new text component.

Examples found in repository?
examples/3d/specular_tint.rs (line 174)
168    fn create_text(&self) -> Text {
169        let tint_map_help_text = match self.tint_type {
170            TintType::Solid => SWITCH_TO_MAP_HELP_TEXT,
171            TintType::Map => SWITCH_TO_SOLID_TINT_HELP_TEXT,
172        };
173
174        Text::new(tint_map_help_text)
175    }
More examples
Hide additional examples
examples/3d/occlusion_culling.rs (line 408)
406fn spawn_help_text(commands: &mut Commands) {
407    commands.spawn((
408        Text::new(""),
409        Node {
410            position_type: PositionType::Absolute,
411            top: Val::Px(12.0),
412            left: Val::Px(12.0),
413            ..default()
414        },
415    ));
416}
examples/ui/ghost_nodes.rs (line 94)
92fn create_label(text: &str, font: Handle<Font>) -> (Text, TextFont, TextColor) {
93    (
94        Text::new(text),
95        TextFont {
96            font,
97            font_size: 33.0,
98            ..default()
99        },
100        TextColor(Color::srgb(0.9, 0.9, 0.9)),
101    )
102}
examples/animation/animation_graph.rs (line 254)
252fn setup_help_text(commands: &mut Commands) {
253    commands.spawn((
254        Text::new(HELP_TEXT),
255        Node {
256            position_type: PositionType::Absolute,
257            top: Val::Px(12.0),
258            left: Val::Px(12.0),
259            ..default()
260        },
261    ));
262}
263
264/// Initializes the node UI widgets.
265fn setup_node_rects(commands: &mut Commands) {
266    for (node_rect, node_type) in NODE_RECTS.iter().zip(NODE_TYPES.iter()) {
267        let node_string = match *node_type {
268            NodeType::Clip(ref clip) => clip.text,
269            NodeType::Blend(text) => text,
270        };
271
272        let text = commands
273            .spawn((
274                Text::new(node_string),
275                TextFont {
276                    font_size: 16.0,
277                    ..default()
278                },
279                TextColor(ANTIQUE_WHITE.into()),
280                TextLayout::new_with_justify(JustifyText::Center),
281            ))
282            .id();
283
284        let container = {
285            let mut container = commands.spawn((
286                Node {
287                    position_type: PositionType::Absolute,
288                    bottom: Val::Px(node_rect.bottom),
289                    left: Val::Px(node_rect.left),
290                    height: Val::Px(node_rect.height),
291                    width: Val::Px(node_rect.width),
292                    align_items: AlignItems::Center,
293                    justify_items: JustifyItems::Center,
294                    align_content: AlignContent::Center,
295                    justify_content: JustifyContent::Center,
296                    ..default()
297                },
298                BorderColor(WHITE.into()),
299                Outline::new(Val::Px(1.), Val::ZERO, Color::WHITE),
300            ));
301
302            if let NodeType::Clip(clip) = node_type {
303                container.insert((
304                    Interaction::None,
305                    RelativeCursorPosition::default(),
306                    (*clip).clone(),
307                ));
308            }
309
310            container.id()
311        };
312
313        // Create the background color.
314        if let NodeType::Clip(_) = node_type {
315            let background = commands
316                .spawn((
317                    Node {
318                        position_type: PositionType::Absolute,
319                        top: Val::Px(0.),
320                        left: Val::Px(0.),
321                        height: Val::Px(node_rect.height),
322                        width: Val::Px(node_rect.width),
323                        ..default()
324                    },
325                    BackgroundColor(DARK_GREEN.into()),
326                ))
327                .id();
328
329            commands.entity(container).add_child(background);
330        }
331
332        commands.entity(container).add_child(text);
333    }
334}
examples/3d/clearcoat.rs (line 320)
314    fn create_help_text(&self) -> Text {
315        let help_text = match *self {
316            LightMode::Point => "Press Space to switch to a directional light",
317            LightMode::Directional => "Press Space to switch to a point light",
318        };
319
320        Text::new(help_text)
321    }
examples/3d/../helpers/widgets.rs (line 154)
148pub fn spawn_ui_text<'a>(
149    parent: &'a mut ChildSpawnerCommands,
150    label: &str,
151    color: Color,
152) -> EntityCommands<'a> {
153    parent.spawn((
154        Text::new(label),
155        TextFont {
156            font_size: 18.0,
157            ..default()
158        },
159        TextColor(color),
160    ))
161}

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

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

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

s.push_str("bar");

assert_eq!("foobar", s);
Examples found in repository?
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}
More examples
Hide additional examples
examples/ecs/entity_disabling.rs (line 69)
60fn list_all_named_entities(
61    query: Query<&Name>,
62    mut name_text_query: Query<&mut Text, With<EntityNameText>>,
63    mut commands: Commands,
64) {
65    let mut text_string = String::from("Named entities found:\n");
66    // Query iteration order is not guaranteed, so we sort the names
67    // to ensure the output is consistent.
68    for name in query.iter().sort::<&Name>() {
69        text_string.push_str(&format!("{:?}\n", name));
70    }
71
72    if let Ok(mut text) = name_text_query.single_mut() {
73        *text = Text::new(text_string);
74    } else {
75        commands.spawn((
76            EntityNameText,
77            Text::default(),
78            Node {
79                position_type: PositionType::Absolute,
80                top: Val::Px(12.0),
81                right: Val::Px(12.0),
82                ..default()
83            },
84        ));
85    }
86}
examples/input/text_input.rs (line 119)
104fn listen_ime_events(
105    mut events: EventReader<Ime>,
106    status_text: Single<Entity, (With<Node>, With<Text>)>,
107    mut edit_text: Single<&mut Text2d, (Without<Node>, Without<Bubble>)>,
108    mut ui_writer: TextUiWriter,
109) {
110    for event in events.read() {
111        match event {
112            Ime::Preedit { value, cursor, .. } if !cursor.is_none() => {
113                *ui_writer.text(*status_text, 7) = format!("{value}\n");
114            }
115            Ime::Preedit { cursor, .. } if cursor.is_none() => {
116                *ui_writer.text(*status_text, 7) = "\n".to_string();
117            }
118            Ime::Commit { value, .. } => {
119                edit_text.push_str(value);
120            }
121            Ime::Enabled { .. } => {
122                *ui_writer.text(*status_text, 5) = "true\n".to_string();
123            }
124            Ime::Disabled { .. } => {
125                *ui_writer.text(*status_text, 5) = "false\n".to_string();
126            }
127            _ => (),
128        }
129    }
130}
131
132fn listen_keyboard_input_events(
133    mut commands: Commands,
134    mut events: EventReader<KeyboardInput>,
135    edit_text: Single<(&mut Text2d, &TextFont), (Without<Node>, Without<Bubble>)>,
136) {
137    let (mut text, style) = edit_text.into_inner();
138    for event in events.read() {
139        // Only trigger changes when the key is first pressed.
140        if !event.state.is_pressed() {
141            continue;
142        }
143
144        match (&event.logical_key, &event.text) {
145            (Key::Enter, _) => {
146                if text.is_empty() {
147                    continue;
148                }
149                let old_value = mem::take(&mut **text);
150
151                commands.spawn((
152                    Text2d::new(old_value),
153                    style.clone(),
154                    Bubble {
155                        timer: Timer::from_seconds(5.0, TimerMode::Once),
156                    },
157                ));
158            }
159            (Key::Backspace, _) => {
160                text.pop();
161            }
162            (_, Some(inserted_text)) => {
163                // Make sure the text doesn't have any control characters,
164                // which can happen when keys like Escape are pressed
165                if inserted_text.chars().all(is_printable_char) {
166                    text.push_str(inserted_text);
167                }
168            }
169            _ => continue,
170        }
171    }
172}
examples/ecs/relationships.rs (lines 102-104)
78    fn debug_relationships(
79        // Not all of our entities are targeted by something, so we use `Option` in our query to handle this case.
80        relations_query: Query<(&Name, &Targeting, Option<&TargetedBy>)>,
81        name_query: Query<&Name>,
82    ) {
83        let mut relationships = String::new();
84
85        for (name, targeting, maybe_targeted_by) in relations_query.iter() {
86            let targeting_name = name_query.get(targeting.0).unwrap();
87            let targeted_by_string = if let Some(targeted_by) = maybe_targeted_by {
88                let mut vec_of_names = Vec::<&Name>::new();
89
90                for entity in &targeted_by.0 {
91                    let name = name_query.get(*entity).unwrap();
92                    vec_of_names.push(name);
93                }
94
95                // Convert this to a nice string for printing.
96                let vec_of_str: Vec<&str> = vec_of_names.iter().map(|name| name.as_str()).collect();
97                vec_of_str.join(", ")
98            } else {
99                "nobody".to_string()
100            };
101
102            relationships.push_str(&format!(
103                "{name} is targeting {targeting_name}, and is targeted by {targeted_by_string}\n",
104            ));
105        }
106
107        println!("{}", relationships);
108    }
examples/asset/processing/asset_processing.rs (line 157)
141    async fn load(
142        &self,
143        reader: &mut dyn Reader,
144        _settings: &Self::Settings,
145        load_context: &mut LoadContext<'_>,
146    ) -> Result<CoolText, Self::Error> {
147        let mut bytes = Vec::new();
148        reader.read_to_end(&mut bytes).await?;
149        let ron: CoolTextRon = ron::de::from_bytes(&bytes)?;
150        let mut base_text = ron.text;
151        for embedded in ron.embedded_dependencies {
152            let loaded = load_context
153                .loader()
154                .immediate()
155                .load::<Text>(&embedded)
156                .await?;
157            base_text.push_str(&loaded.get().0);
158        }
159        for (path, settings_override) in ron.dependencies_with_settings {
160            let loaded = load_context
161                .loader()
162                .with_settings(move |settings| {
163                    *settings = settings_override.clone();
164                })
165                .immediate()
166                .load::<Text>(&path)
167                .await?;
168            base_text.push_str(&loaded.get().0);
169        }
170        Ok(CoolText {
171            text: base_text,
172            dependencies: ron
173                .dependencies
174                .iter()
175                .map(|p| load_context.load(p))
176                .collect(),
177        })
178    }
examples/3d/occlusion_culling.rs (line 569)
533fn update_status_text(
534    saved_indirect_parameters: Res<SavedIndirectParameters>,
535    mut texts: Query<&mut Text>,
536    meshes: Query<Entity, With<Mesh3d>>,
537    app_status: Res<AppStatus>,
538) {
539    // How many meshes are in the scene?
540    let total_mesh_count = meshes.iter().count();
541
542    // Sample the rendered object count. Note that we don't synchronize beyond
543    // locking the data and therefore this will value will generally at least
544    // one frame behind. This is fine; this app is just a demonstration after
545    // all.
546    let (
547        rendered_object_count,
548        occlusion_culling_supported,
549        occlusion_culling_introspection_supported,
550    ): (u32, bool, bool) = {
551        let saved_indirect_parameters = saved_indirect_parameters.lock().unwrap();
552        (
553            saved_indirect_parameters
554                .data
555                .iter()
556                .take(saved_indirect_parameters.count as usize)
557                .map(|indirect_parameters| indirect_parameters.instance_count)
558                .sum(),
559            saved_indirect_parameters.occlusion_culling_supported,
560            saved_indirect_parameters.occlusion_culling_introspection_supported,
561        )
562    };
563
564    // Change the text.
565    for mut text in &mut texts {
566        text.0 = String::new();
567        if !occlusion_culling_supported {
568            text.0
569                .push_str("Occlusion culling not supported on this platform");
570            continue;
571        }
572
573        let _ = writeln!(
574            &mut text.0,
575            "Occlusion culling {} (Press Space to toggle)",
576            if app_status.occlusion_culling {
577                "ON"
578            } else {
579                "OFF"
580            },
581        );
582
583        if !occlusion_culling_introspection_supported {
584            continue;
585        }
586
587        let _ = write!(
588            &mut text.0,
589            "{}/{} meshes rendered",
590            rendered_object_count, total_mesh_count
591        );
592    }
593}
1.87.0 · Source

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

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

§Panics

Panics if the starting point or end point do not lie on a char boundary, or if they’re out of bounds.

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

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 overflows usize.

§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());
1.0.0 · Source

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

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 overflows usize.

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

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)

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)

Appends the given char to the end of this String.

§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/font_atlas_debug.rs (line 80)
66fn text_update_system(
67    mut state: ResMut<State>,
68    time: Res<Time>,
69    mut query: Query<&mut Text>,
70    mut seeded_rng: ResMut<SeededRng>,
71) {
72    if !state.timer.tick(time.delta()).just_finished() {
73        return;
74    }
75
76    for mut text in &mut query {
77        let c = seeded_rng.r#gen::<u8>() as char;
78        let string = &mut **text;
79        if !string.contains(c) {
80            string.push(c);
81        }
82    }
83}
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)
217    async fn save(
218        &self,
219        writer: &mut Writer,
220        asset: SavedAsset<'_, Self::Asset>,
221        _settings: &Self::Settings,
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/scene/scene.rs (line 205)
160fn save_scene_system(world: &mut World) {
161    // Scenes can be created from any ECS World.
162    // You can either create a new one for the scene or use the current World.
163    // For demonstration purposes, we'll create a new one.
164    let mut scene_world = World::new();
165
166    // The `TypeRegistry` resource contains information about all registered types (including components).
167    // This is used to construct scenes, so we'll want to ensure that our previous type registrations
168    // exist in this new scene world as well.
169    // To do this, we can simply clone the `AppTypeRegistry` resource.
170    let type_registry = world.resource::<AppTypeRegistry>().clone();
171    scene_world.insert_resource(type_registry);
172
173    let mut component_b = ComponentB::from_world(world);
174    component_b.value = "hello".to_string();
175    scene_world.spawn((
176        component_b,
177        ComponentA { x: 1.0, y: 2.0 },
178        Transform::IDENTITY,
179        Name::new("joe"),
180    ));
181    scene_world.spawn(ComponentA { x: 3.0, y: 4.0 });
182    scene_world.insert_resource(ResourceA { score: 1 });
183
184    // With our sample world ready to go, we can now create our scene using DynamicScene or DynamicSceneBuilder.
185    // For simplicity, we will create our scene using DynamicScene:
186    let scene = DynamicScene::from_world(&scene_world);
187
188    // Scenes can be serialized like this:
189    let type_registry = world.resource::<AppTypeRegistry>();
190    let type_registry = type_registry.read();
191    let serialized_scene = scene.serialize(&type_registry).unwrap();
192
193    // Showing the scene in the console
194    info!("{}", serialized_scene);
195
196    // Writing the scene to a new file. Using a task to avoid calling the filesystem APIs in a system
197    // as they are blocking.
198    //
199    // This can't work in Wasm as there is no filesystem access.
200    #[cfg(not(target_arch = "wasm32"))]
201    IoTaskPool::get()
202        .spawn(async move {
203            // Write the scene RON data to file
204            File::create(format!("assets/{NEW_SCENE_FILE_PATH}"))
205                .and_then(|mut file| file.write(serialized_scene.as_bytes()))
206                .expect("Error while writing scene to file");
207        })
208        .detach();
209}
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);
Examples found in repository?
examples/input/text_input.rs (line 160)
132fn listen_keyboard_input_events(
133    mut commands: Commands,
134    mut events: EventReader<KeyboardInput>,
135    edit_text: Single<(&mut Text2d, &TextFont), (Without<Node>, Without<Bubble>)>,
136) {
137    let (mut text, style) = edit_text.into_inner();
138    for event in events.read() {
139        // Only trigger changes when the key is first pressed.
140        if !event.state.is_pressed() {
141            continue;
142        }
143
144        match (&event.logical_key, &event.text) {
145            (Key::Enter, _) => {
146                if text.is_empty() {
147                    continue;
148                }
149                let old_value = mem::take(&mut **text);
150
151                commands.spawn((
152                    Text2d::new(old_value),
153                    style.clone(),
154                    Bubble {
155                        timer: Timer::from_seconds(5.0, TimerMode::Once),
156                    },
157                ));
158            }
159            (Key::Backspace, _) => {
160                text.pop();
161            }
162            (_, Some(inserted_text)) => {
163                // Make sure the text doesn't have any control characters,
164                // which can happen when keys like Escape are pressed
165                if inserted_text.chars().all(is_printable_char) {
166                    text.push_str(inserted_text);
167                }
168            }
169            _ => continue,
170        }
171    }
172}
1.0.0 · Source

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

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

This is an O(n) operation, as it requires copying every element in the buffer.

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

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)

Inserts a character into this String at a byte position.

This is an O(n) operation as it requires copying every element in the buffer.

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

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

This is an O(n) operation as it requires copying every element in the buffer.

§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 412)
388fn update_ui(
389    mut text_query: Single<&mut Text, Without<SceneNumber>>,
390    settings: Single<(&Tonemapping, &ColorGrading)>,
391    current_scene: Res<CurrentScene>,
392    selected_parameter: Res<SelectedParameter>,
393    mut hide_ui: Local<bool>,
394    keys: Res<ButtonInput<KeyCode>>,
395) {
396    if keys.just_pressed(KeyCode::KeyH) {
397        *hide_ui = !*hide_ui;
398    }
399
400    if *hide_ui {
401        if !text_query.is_empty() {
402            // single_mut() always triggers change detection,
403            // so only access if text actually needs changing
404            text_query.clear();
405        }
406        return;
407    }
408
409    let (tonemapping, color_grading) = *settings;
410    let tonemapping = *tonemapping;
411
412    let mut text = String::with_capacity(text_query.len());
413
414    let scn = current_scene.0;
415    text.push_str("(H) Hide UI\n\n");
416    text.push_str("Test Scene: \n");
417    text.push_str(&format!(
418        "(Q) {} Basic Scene\n",
419        if scn == 1 { ">" } else { "" }
420    ));
421    text.push_str(&format!(
422        "(W) {} Color Sweep\n",
423        if scn == 2 { ">" } else { "" }
424    ));
425    text.push_str(&format!(
426        "(E) {} Image Viewer\n",
427        if scn == 3 { ">" } else { "" }
428    ));
429
430    text.push_str("\n\nTonemapping Method:\n");
431    text.push_str(&format!(
432        "(1) {} Disabled\n",
433        if tonemapping == Tonemapping::None {
434            ">"
435        } else {
436            ""
437        }
438    ));
439    text.push_str(&format!(
440        "(2) {} Reinhard\n",
441        if tonemapping == Tonemapping::Reinhard {
442            "> "
443        } else {
444            ""
445        }
446    ));
447    text.push_str(&format!(
448        "(3) {} Reinhard Luminance\n",
449        if tonemapping == Tonemapping::ReinhardLuminance {
450            ">"
451        } else {
452            ""
453        }
454    ));
455    text.push_str(&format!(
456        "(4) {} ACES Fitted\n",
457        if tonemapping == Tonemapping::AcesFitted {
458            ">"
459        } else {
460            ""
461        }
462    ));
463    text.push_str(&format!(
464        "(5) {} AgX\n",
465        if tonemapping == Tonemapping::AgX {
466            ">"
467        } else {
468            ""
469        }
470    ));
471    text.push_str(&format!(
472        "(6) {} SomewhatBoringDisplayTransform\n",
473        if tonemapping == Tonemapping::SomewhatBoringDisplayTransform {
474            ">"
475        } else {
476            ""
477        }
478    ));
479    text.push_str(&format!(
480        "(7) {} TonyMcMapface\n",
481        if tonemapping == Tonemapping::TonyMcMapface {
482            ">"
483        } else {
484            ""
485        }
486    ));
487    text.push_str(&format!(
488        "(8) {} Blender Filmic\n",
489        if tonemapping == Tonemapping::BlenderFilmic {
490            ">"
491        } else {
492            ""
493        }
494    ));
495
496    text.push_str("\n\nColor Grading:\n");
497    text.push_str("(arrow keys)\n");
498    if selected_parameter.value == 0 {
499        text.push_str("> ");
500    }
501    text.push_str(&format!("Exposure: {}\n", color_grading.global.exposure));
502    if selected_parameter.value == 1 {
503        text.push_str("> ");
504    }
505    text.push_str(&format!("Gamma: {}\n", color_grading.shadows.gamma));
506    if selected_parameter.value == 2 {
507        text.push_str("> ");
508    }
509    text.push_str(&format!(
510        "PreSaturation: {}\n",
511        color_grading.shadows.saturation
512    ));
513    if selected_parameter.value == 3 {
514        text.push_str("> ");
515    }
516    text.push_str(&format!(
517        "PostSaturation: {}\n",
518        color_grading.global.post_saturation
519    ));
520    text.push_str("(Space) Reset all to default\n");
521
522    if current_scene.0 == 1 {
523        text.push_str("(Enter) Reset all to scene recommendation\n");
524    }
525
526    if text != text_query.as_str() {
527        // single_mut() always triggers change detection,
528        // so only access if text actually changed
529        text_query.0 = text;
530    }
531}
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/input/text_input.rs (line 146)
132fn listen_keyboard_input_events(
133    mut commands: Commands,
134    mut events: EventReader<KeyboardInput>,
135    edit_text: Single<(&mut Text2d, &TextFont), (Without<Node>, Without<Bubble>)>,
136) {
137    let (mut text, style) = edit_text.into_inner();
138    for event in events.read() {
139        // Only trigger changes when the key is first pressed.
140        if !event.state.is_pressed() {
141            continue;
142        }
143
144        match (&event.logical_key, &event.text) {
145            (Key::Enter, _) => {
146                if text.is_empty() {
147                    continue;
148                }
149                let old_value = mem::take(&mut **text);
150
151                commands.spawn((
152                    Text2d::new(old_value),
153                    style.clone(),
154                    Bubble {
155                        timer: Timer::from_seconds(5.0, TimerMode::Once),
156                    },
157                ));
158            }
159            (Key::Backspace, _) => {
160                text.pop();
161            }
162            (_, Some(inserted_text)) => {
163                // Make sure the text doesn't have any control characters,
164                // which can happen when keys like Escape are pressed
165                if inserted_text.chars().all(is_printable_char) {
166                    text.push_str(inserted_text);
167                }
168            }
169            _ => continue,
170        }
171    }
172}
More examples
Hide additional examples
examples/3d/tonemapping.rs (line 401)
388fn update_ui(
389    mut text_query: Single<&mut Text, Without<SceneNumber>>,
390    settings: Single<(&Tonemapping, &ColorGrading)>,
391    current_scene: Res<CurrentScene>,
392    selected_parameter: Res<SelectedParameter>,
393    mut hide_ui: Local<bool>,
394    keys: Res<ButtonInput<KeyCode>>,
395) {
396    if keys.just_pressed(KeyCode::KeyH) {
397        *hide_ui = !*hide_ui;
398    }
399
400    if *hide_ui {
401        if !text_query.is_empty() {
402            // single_mut() always triggers change detection,
403            // so only access if text actually needs changing
404            text_query.clear();
405        }
406        return;
407    }
408
409    let (tonemapping, color_grading) = *settings;
410    let tonemapping = *tonemapping;
411
412    let mut text = String::with_capacity(text_query.len());
413
414    let scn = current_scene.0;
415    text.push_str("(H) Hide UI\n\n");
416    text.push_str("Test Scene: \n");
417    text.push_str(&format!(
418        "(Q) {} Basic Scene\n",
419        if scn == 1 { ">" } else { "" }
420    ));
421    text.push_str(&format!(
422        "(W) {} Color Sweep\n",
423        if scn == 2 { ">" } else { "" }
424    ));
425    text.push_str(&format!(
426        "(E) {} Image Viewer\n",
427        if scn == 3 { ">" } else { "" }
428    ));
429
430    text.push_str("\n\nTonemapping Method:\n");
431    text.push_str(&format!(
432        "(1) {} Disabled\n",
433        if tonemapping == Tonemapping::None {
434            ">"
435        } else {
436            ""
437        }
438    ));
439    text.push_str(&format!(
440        "(2) {} Reinhard\n",
441        if tonemapping == Tonemapping::Reinhard {
442            "> "
443        } else {
444            ""
445        }
446    ));
447    text.push_str(&format!(
448        "(3) {} Reinhard Luminance\n",
449        if tonemapping == Tonemapping::ReinhardLuminance {
450            ">"
451        } else {
452            ""
453        }
454    ));
455    text.push_str(&format!(
456        "(4) {} ACES Fitted\n",
457        if tonemapping == Tonemapping::AcesFitted {
458            ">"
459        } else {
460            ""
461        }
462    ));
463    text.push_str(&format!(
464        "(5) {} AgX\n",
465        if tonemapping == Tonemapping::AgX {
466            ">"
467        } else {
468            ""
469        }
470    ));
471    text.push_str(&format!(
472        "(6) {} SomewhatBoringDisplayTransform\n",
473        if tonemapping == Tonemapping::SomewhatBoringDisplayTransform {
474            ">"
475        } else {
476            ""
477        }
478    ));
479    text.push_str(&format!(
480        "(7) {} TonyMcMapface\n",
481        if tonemapping == Tonemapping::TonyMcMapface {
482            ">"
483        } else {
484            ""
485        }
486    ));
487    text.push_str(&format!(
488        "(8) {} Blender Filmic\n",
489        if tonemapping == Tonemapping::BlenderFilmic {
490            ">"
491        } else {
492            ""
493        }
494    ));
495
496    text.push_str("\n\nColor Grading:\n");
497    text.push_str("(arrow keys)\n");
498    if selected_parameter.value == 0 {
499        text.push_str("> ");
500    }
501    text.push_str(&format!("Exposure: {}\n", color_grading.global.exposure));
502    if selected_parameter.value == 1 {
503        text.push_str("> ");
504    }
505    text.push_str(&format!("Gamma: {}\n", color_grading.shadows.gamma));
506    if selected_parameter.value == 2 {
507        text.push_str("> ");
508    }
509    text.push_str(&format!(
510        "PreSaturation: {}\n",
511        color_grading.shadows.saturation
512    ));
513    if selected_parameter.value == 3 {
514        text.push_str("> ");
515    }
516    text.push_str(&format!(
517        "PostSaturation: {}\n",
518        color_grading.global.post_saturation
519    ));
520    text.push_str("(Space) Reset all to default\n");
521
522    if current_scene.0 == 1 {
523        text.push_str("(Enter) Reset all to scene recommendation\n");
524    }
525
526    if text != text_query.as_str() {
527        // single_mut() always triggers change detection,
528        // so only access if text actually changed
529        text_query.0 = text;
530    }
531}
examples/ecs/dynamic.rs (line 65)
51fn main() {
52    let mut world = World::new();
53    let mut lines = std::io::stdin().lines();
54    let mut component_names = HashMap::<String, ComponentId>::new();
55    let mut component_info = HashMap::<ComponentId, ComponentInfo>::new();
56
57    println!("{PROMPT}");
58    loop {
59        print!("\n> ");
60        let _ = std::io::stdout().flush();
61        let Some(Ok(line)) = lines.next() else {
62            return;
63        };
64
65        if line.is_empty() {
66            return;
67        };
68
69        let Some((first, rest)) = line.trim().split_once(|c: char| c.is_whitespace()) else {
70            match &line.chars().next() {
71                Some('c') => println!("{COMPONENT_PROMPT}"),
72                Some('s') => println!("{ENTITY_PROMPT}"),
73                Some('q') => println!("{QUERY_PROMPT}"),
74                _ => println!("{PROMPT}"),
75            }
76            continue;
77        };
78
79        match &first[0..1] {
80            "c" => {
81                rest.split(',').for_each(|component| {
82                    let mut component = component.split_whitespace();
83                    let Some(name) = component.next() else {
84                        return;
85                    };
86                    let size = match component.next().map(str::parse) {
87                        Some(Ok(size)) => size,
88                        _ => 0,
89                    };
90                    // Register our new component to the world with a layout specified by it's size
91                    // SAFETY: [u64] is Send + Sync
92                    let id = world.register_component_with_descriptor(unsafe {
93                        ComponentDescriptor::new_with_layout(
94                            name.to_string(),
95                            StorageType::Table,
96                            Layout::array::<u64>(size).unwrap(),
97                            None,
98                            true,
99                            ComponentCloneBehavior::Default,
100                        )
101                    });
102                    let Some(info) = world.components().get_info(id) else {
103                        return;
104                    };
105                    component_names.insert(name.to_string(), id);
106                    component_info.insert(id, info.clone());
107                    println!("Component {} created with id: {}", name, id.index());
108                });
109            }
110            "s" => {
111                let mut to_insert_ids = Vec::new();
112                let mut to_insert_data = Vec::new();
113                rest.split(',').for_each(|component| {
114                    let mut component = component.split_whitespace();
115                    let Some(name) = component.next() else {
116                        return;
117                    };
118
119                    // Get the id for the component with the given name
120                    let Some(&id) = component_names.get(name) else {
121                        println!("Component {name} does not exist");
122                        return;
123                    };
124
125                    // Calculate the length for the array based on the layout created for this component id
126                    let info = world.components().get_info(id).unwrap();
127                    let len = info.layout().size() / size_of::<u64>();
128                    let mut values: Vec<u64> = component
129                        .take(len)
130                        .filter_map(|value| value.parse::<u64>().ok())
131                        .collect();
132                    values.resize(len, 0);
133
134                    // Collect the id and array to be inserted onto our entity
135                    to_insert_ids.push(id);
136                    to_insert_data.push(values);
137                });
138
139                let mut entity = world.spawn_empty();
140
141                // Construct an `OwningPtr` for each component in `to_insert_data`
142                let to_insert_ptr = to_owning_ptrs(&mut to_insert_data);
143
144                // SAFETY:
145                // - Component ids have been taken from the same world
146                // - Each array is created to the layout specified in the world
147                unsafe {
148                    entity.insert_by_ids(&to_insert_ids, to_insert_ptr.into_iter());
149                }
150
151                println!("Entity spawned with id: {}", entity.id());
152            }
153            "q" => {
154                let mut builder = QueryBuilder::<FilteredEntityMut>::new(&mut world);
155                parse_query(rest, &mut builder, &component_names);
156                let mut query = builder.build();
157                query.iter_mut(&mut world).for_each(|filtered_entity| {
158                    let terms = filtered_entity
159                        .access()
160                        .try_iter_component_access()
161                        .unwrap()
162                        .map(|component_access| {
163                            let id = *component_access.index();
164                            let ptr = filtered_entity.get_by_id(id).unwrap();
165                            let info = component_info.get(&id).unwrap();
166                            let len = info.layout().size() / size_of::<u64>();
167
168                            // SAFETY:
169                            // - All components are created with layout [u64]
170                            // - len is calculated from the component descriptor
171                            let data = unsafe {
172                                std::slice::from_raw_parts_mut(
173                                    ptr.assert_unique().as_ptr().cast::<u64>(),
174                                    len,
175                                )
176                            };
177
178                            // If we have write access, increment each value once
179                            if matches!(component_access, ComponentAccessKind::Exclusive(_)) {
180                                data.iter_mut().for_each(|data| {
181                                    *data += 1;
182                                });
183                            }
184
185                            format!("{}: {:?}", info.name(), data[0..len].to_vec())
186                        })
187                        .collect::<Vec<_>>()
188                        .join(", ");
189
190                    println!("{}: {}", filtered_entity.id(), terms);
191                });
192            }
193            _ => continue,
194        }
195    }
196}
1.16.0 · Source

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

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/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}
More examples
Hide additional examples
examples/3d/deferred_rendering.rs (line 294)
283fn switch_mode(
284    mut text: Single<&mut Text>,
285    mut commands: Commands,
286    keys: Res<ButtonInput<KeyCode>>,
287    mut default_opaque_renderer_method: ResMut<DefaultOpaqueRendererMethod>,
288    mut materials: ResMut<Assets<StandardMaterial>>,
289    cameras: Query<Entity, With<Camera>>,
290    mut pause: ResMut<Pause>,
291    mut hide_ui: Local<bool>,
292    mut mode: Local<DefaultRenderMode>,
293) {
294    text.clear();
295
296    if keys.just_pressed(KeyCode::Space) {
297        pause.0 = !pause.0;
298    }
299
300    if keys.just_pressed(KeyCode::Digit1) {
301        *mode = DefaultRenderMode::Deferred;
302        default_opaque_renderer_method.set_to_deferred();
303        println!("DefaultOpaqueRendererMethod: Deferred");
304        for _ in materials.iter_mut() {}
305        for camera in &cameras {
306            commands.entity(camera).remove::<NormalPrepass>();
307            commands.entity(camera).insert(DepthPrepass);
308            commands.entity(camera).insert(MotionVectorPrepass);
309            commands.entity(camera).insert(DeferredPrepass);
310        }
311    }
312    if keys.just_pressed(KeyCode::Digit2) {
313        *mode = DefaultRenderMode::Forward;
314        default_opaque_renderer_method.set_to_forward();
315        println!("DefaultOpaqueRendererMethod: Forward");
316        for _ in materials.iter_mut() {}
317        for camera in &cameras {
318            commands.entity(camera).remove::<NormalPrepass>();
319            commands.entity(camera).remove::<DepthPrepass>();
320            commands.entity(camera).remove::<MotionVectorPrepass>();
321            commands.entity(camera).remove::<DeferredPrepass>();
322        }
323    }
324    if keys.just_pressed(KeyCode::Digit3) {
325        *mode = DefaultRenderMode::ForwardPrepass;
326        default_opaque_renderer_method.set_to_forward();
327        println!("DefaultOpaqueRendererMethod: Forward + Prepass");
328        for _ in materials.iter_mut() {}
329        for camera in &cameras {
330            commands.entity(camera).insert(NormalPrepass);
331            commands.entity(camera).insert(DepthPrepass);
332            commands.entity(camera).insert(MotionVectorPrepass);
333            commands.entity(camera).remove::<DeferredPrepass>();
334        }
335    }
336
337    if keys.just_pressed(KeyCode::KeyH) {
338        *hide_ui = !*hide_ui;
339    }
340
341    if !*hide_ui {
342        text.push_str("(H) Hide UI\n");
343        text.push_str("(Space) Play/Pause\n\n");
344        text.push_str("Rendering Method:\n");
345
346        text.push_str(&format!(
347            "(1) {} Deferred\n",
348            if let DefaultRenderMode::Deferred = *mode {
349                ">"
350            } else {
351                ""
352            }
353        ));
354        text.push_str(&format!(
355            "(2) {} Forward\n",
356            if let DefaultRenderMode::Forward = *mode {
357                ">"
358            } else {
359                ""
360            }
361        ));
362        text.push_str(&format!(
363            "(3) {} Forward + Prepass\n",
364            if let DefaultRenderMode::ForwardPrepass = *mode {
365                ">"
366            } else {
367                ""
368            }
369        ));
370    }
371}
examples/3d/ssao.rs (line 168)
92fn update(
93    camera: Single<
94        (
95            Entity,
96            Option<&ScreenSpaceAmbientOcclusion>,
97            Option<&TemporalJitter>,
98        ),
99        With<Camera>,
100    >,
101    mut text: Single<&mut Text>,
102    mut sphere: Single<&mut Transform, With<SphereMarker>>,
103    mut commands: Commands,
104    keycode: Res<ButtonInput<KeyCode>>,
105    time: Res<Time>,
106) {
107    sphere.translation.y = ops::sin(time.elapsed_secs() / 1.7) * 0.7;
108
109    let (camera_entity, ssao, temporal_jitter) = *camera;
110    let current_ssao = ssao.cloned().unwrap_or_default();
111
112    let mut commands = commands.entity(camera_entity);
113    commands
114        .insert_if(
115            ScreenSpaceAmbientOcclusion {
116                quality_level: ScreenSpaceAmbientOcclusionQualityLevel::Low,
117                ..current_ssao
118            },
119            || keycode.just_pressed(KeyCode::Digit2),
120        )
121        .insert_if(
122            ScreenSpaceAmbientOcclusion {
123                quality_level: ScreenSpaceAmbientOcclusionQualityLevel::Medium,
124                ..current_ssao
125            },
126            || keycode.just_pressed(KeyCode::Digit3),
127        )
128        .insert_if(
129            ScreenSpaceAmbientOcclusion {
130                quality_level: ScreenSpaceAmbientOcclusionQualityLevel::High,
131                ..current_ssao
132            },
133            || keycode.just_pressed(KeyCode::Digit4),
134        )
135        .insert_if(
136            ScreenSpaceAmbientOcclusion {
137                quality_level: ScreenSpaceAmbientOcclusionQualityLevel::Ultra,
138                ..current_ssao
139            },
140            || keycode.just_pressed(KeyCode::Digit5),
141        )
142        .insert_if(
143            ScreenSpaceAmbientOcclusion {
144                constant_object_thickness: (current_ssao.constant_object_thickness * 2.0).min(4.0),
145                ..current_ssao
146            },
147            || keycode.just_pressed(KeyCode::ArrowUp),
148        )
149        .insert_if(
150            ScreenSpaceAmbientOcclusion {
151                constant_object_thickness: (current_ssao.constant_object_thickness * 0.5)
152                    .max(0.0625),
153                ..current_ssao
154            },
155            || keycode.just_pressed(KeyCode::ArrowDown),
156        );
157    if keycode.just_pressed(KeyCode::Digit1) {
158        commands.remove::<ScreenSpaceAmbientOcclusion>();
159    }
160    if keycode.just_pressed(KeyCode::Space) {
161        if temporal_jitter.is_some() {
162            commands.remove::<TemporalJitter>();
163        } else {
164            commands.insert(TemporalJitter::default());
165        }
166    }
167
168    text.clear();
169
170    let (o, l, m, h, u) = match ssao.map(|s| s.quality_level) {
171        None => ("*", "", "", "", ""),
172        Some(ScreenSpaceAmbientOcclusionQualityLevel::Low) => ("", "*", "", "", ""),
173        Some(ScreenSpaceAmbientOcclusionQualityLevel::Medium) => ("", "", "*", "", ""),
174        Some(ScreenSpaceAmbientOcclusionQualityLevel::High) => ("", "", "", "*", ""),
175        Some(ScreenSpaceAmbientOcclusionQualityLevel::Ultra) => ("", "", "", "", "*"),
176        _ => unreachable!(),
177    };
178
179    if let Some(thickness) = ssao.map(|s| s.constant_object_thickness) {
180        text.push_str(&format!(
181            "Constant object thickness: {} (Up/Down)\n\n",
182            thickness
183        ));
184    }
185
186    text.push_str("SSAO Quality:\n");
187    text.push_str(&format!("(1) {o}Off{o}\n"));
188    text.push_str(&format!("(2) {l}Low{l}\n"));
189    text.push_str(&format!("(3) {m}Medium{m}\n"));
190    text.push_str(&format!("(4) {h}High{h}\n"));
191    text.push_str(&format!("(5) {u}Ultra{u}\n\n"));
192
193    text.push_str("Temporal Antialiasing:\n");
194    text.push_str(match temporal_jitter {
195        Some(_) => "(Space) Enabled",
196        None => "(Space) Disabled",
197    });
198}
examples/3d/tonemapping.rs (line 404)
388fn update_ui(
389    mut text_query: Single<&mut Text, Without<SceneNumber>>,
390    settings: Single<(&Tonemapping, &ColorGrading)>,
391    current_scene: Res<CurrentScene>,
392    selected_parameter: Res<SelectedParameter>,
393    mut hide_ui: Local<bool>,
394    keys: Res<ButtonInput<KeyCode>>,
395) {
396    if keys.just_pressed(KeyCode::KeyH) {
397        *hide_ui = !*hide_ui;
398    }
399
400    if *hide_ui {
401        if !text_query.is_empty() {
402            // single_mut() always triggers change detection,
403            // so only access if text actually needs changing
404            text_query.clear();
405        }
406        return;
407    }
408
409    let (tonemapping, color_grading) = *settings;
410    let tonemapping = *tonemapping;
411
412    let mut text = String::with_capacity(text_query.len());
413
414    let scn = current_scene.0;
415    text.push_str("(H) Hide UI\n\n");
416    text.push_str("Test Scene: \n");
417    text.push_str(&format!(
418        "(Q) {} Basic Scene\n",
419        if scn == 1 { ">" } else { "" }
420    ));
421    text.push_str(&format!(
422        "(W) {} Color Sweep\n",
423        if scn == 2 { ">" } else { "" }
424    ));
425    text.push_str(&format!(
426        "(E) {} Image Viewer\n",
427        if scn == 3 { ">" } else { "" }
428    ));
429
430    text.push_str("\n\nTonemapping Method:\n");
431    text.push_str(&format!(
432        "(1) {} Disabled\n",
433        if tonemapping == Tonemapping::None {
434            ">"
435        } else {
436            ""
437        }
438    ));
439    text.push_str(&format!(
440        "(2) {} Reinhard\n",
441        if tonemapping == Tonemapping::Reinhard {
442            "> "
443        } else {
444            ""
445        }
446    ));
447    text.push_str(&format!(
448        "(3) {} Reinhard Luminance\n",
449        if tonemapping == Tonemapping::ReinhardLuminance {
450            ">"
451        } else {
452            ""
453        }
454    ));
455    text.push_str(&format!(
456        "(4) {} ACES Fitted\n",
457        if tonemapping == Tonemapping::AcesFitted {
458            ">"
459        } else {
460            ""
461        }
462    ));
463    text.push_str(&format!(
464        "(5) {} AgX\n",
465        if tonemapping == Tonemapping::AgX {
466            ">"
467        } else {
468            ""
469        }
470    ));
471    text.push_str(&format!(
472        "(6) {} SomewhatBoringDisplayTransform\n",
473        if tonemapping == Tonemapping::SomewhatBoringDisplayTransform {
474            ">"
475        } else {
476            ""
477        }
478    ));
479    text.push_str(&format!(
480        "(7) {} TonyMcMapface\n",
481        if tonemapping == Tonemapping::TonyMcMapface {
482            ">"
483        } else {
484            ""
485        }
486    ));
487    text.push_str(&format!(
488        "(8) {} Blender Filmic\n",
489        if tonemapping == Tonemapping::BlenderFilmic {
490            ">"
491        } else {
492            ""
493        }
494    ));
495
496    text.push_str("\n\nColor Grading:\n");
497    text.push_str("(arrow keys)\n");
498    if selected_parameter.value == 0 {
499        text.push_str("> ");
500    }
501    text.push_str(&format!("Exposure: {}\n", color_grading.global.exposure));
502    if selected_parameter.value == 1 {
503        text.push_str("> ");
504    }
505    text.push_str(&format!("Gamma: {}\n", color_grading.shadows.gamma));
506    if selected_parameter.value == 2 {
507        text.push_str("> ");
508    }
509    text.push_str(&format!(
510        "PreSaturation: {}\n",
511        color_grading.shadows.saturation
512    ));
513    if selected_parameter.value == 3 {
514        text.push_str("> ");
515    }
516    text.push_str(&format!(
517        "PostSaturation: {}\n",
518        color_grading.global.post_saturation
519    ));
520    text.push_str("(Space) Reset all to default\n");
521
522    if current_scene.0 == 1 {
523        text.push_str("(Enter) Reset all to scene recommendation\n");
524    }
525
526    if text != text_query.as_str() {
527        // single_mut() always triggers change detection,
528        // so only access if text actually changed
529        text_query.0 = text;
530    }
531}
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 starting point or end point do not lie on a char boundary, or if they’re out of bounds.

§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>,

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 starting point or end point do not lie on a char boundary, or if they’re out of bounds.

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

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

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

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

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
#![feature(round_char_boundary)]
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], "❤️🧡");
Source

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

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

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
#![feature(round_char_boundary)]
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 an index.

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 two slices returned go from the start of the string slice to mid, and from mid to the end of the string slice.

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 an index.

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 two slices returned go from the start of the string slice to mid, and from mid to the end of the string slice.

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 an index.

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 two slices returned go from the start of the string slice to mid, and from mid to the end of the string slice.

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 an index.

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 two slices returned go from the start of the string slice to mid, and from mid to the end of the string slice.

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.

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

§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());
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.

§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> = "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=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.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.

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

§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"));
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 non-ASCII letters 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 non-ASCII letters 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);
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.

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

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

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

Note: only extended grapheme codepoints that begin the string will be escaped.

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

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

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

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
#![feature(substr_range)]

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

assert_eq!(iter.next(), Some(0..1));
assert_eq!(iter.next(), Some(3..4));
assert_eq!(iter.next(), Some(6..7));
assert_eq!(iter.next(), Some(9..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,

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

Basic usage:

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"));
1.16.0 · Source

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

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

Basic usage:

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

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

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

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

§Examples

Basic usage:

let s = "HELLO";

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

A tricky example, 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());

Languages without case are not changed:

let new_year = "农历新年";

assert_eq!(new_year, new_year.to_lowercase());
1.2.0 · Source

pub fn to_uppercase(&self) -> String

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

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

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

§Examples

Basic usage:

let s = "hello";

assert_eq!("HELLO", 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());
1.16.0 · Source

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

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

pub fn to_ascii_uppercase(&self) -> String

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

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 Text

Source§

fn clone(&self) -> Text

Returns a copy of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

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

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, components: &mut ComponentsRegistrator<'_>, required_components: &mut RequiredComponents, inheritance_depth: u16, recursion_check_stack: &mut Vec<ComponentId>, )

Registers required components.
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 register_component_hooks(hooks: &mut ComponentHooks)

👎Deprecated since 0.16.0: Use the individual hook methods instead (e.g., Component::on_add, etc.)
Called when registering this component, allowing mutable access to its ComponentHooks.
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_replace() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_replace 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§

impl Debug for Text

Source§

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

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

impl Default for Text

Source§

fn default() -> Text

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

impl Deref for Text

Source§

type Target = String

The resulting type after dereferencing.
Source§

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

Dereferences the value.
Source§

impl DerefMut for Text

Source§

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

Mutably dereferences the value.
Source§

impl From<&str> for Text

Source§

fn from(value: &str) -> Text

Converts to this type from the input type.
Source§

impl From<String> for Text

Source§

fn from(value: String) -> Text

Converts to this type from the input type.
Source§

impl FromArg for &'static Text
where Text: Any + Send + Sync, String: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

type This<'from_arg> = &'from_arg Text

The type to convert into. Read more
Source§

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

Creates an item from an argument. Read more
Source§

impl FromArg for &'static mut Text
where Text: Any + Send + Sync, String: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

type This<'from_arg> = &'from_arg mut Text

The type to convert into. Read more
Source§

fn from_arg( arg: Arg<'_>, ) -> Result<<&'static mut Text as FromArg>::This<'_>, ArgError>

Creates an item from an argument. Read more
Source§

impl FromArg for Text
where Text: Any + Send + Sync, String: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

type This<'from_arg> = Text

The type to convert into. Read more
Source§

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

Creates an item from an argument. Read more
Source§

impl FromReflect for Text
where Text: Any + Send + Sync, String: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

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

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 &Text
where Text: Any + Send + Sync, String: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn ownership() -> Ownership

Returns the ownership of Self.
Source§

impl GetOwnership for &mut Text
where Text: Any + Send + Sync, String: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn ownership() -> Ownership

Returns the ownership of Self.
Source§

impl GetOwnership for Text
where Text: Any + Send + Sync, String: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn ownership() -> Ownership

Returns the ownership of Self.
Source§

impl GetTypeRegistration for Text
where Text: Any + Send + Sync, String: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

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 &Text
where Text: Any + Send + Sync, String: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

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

Converts Self into a Return value.
Source§

impl IntoReturn for &mut Text
where Text: Any + Send + Sync, String: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn into_return<'into_return>(self) -> Return<'into_return>
where &mut Text: 'into_return,

Converts Self into a Return value.
Source§

impl IntoReturn for Text
where Text: Any + Send + Sync, String: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

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

Converts Self into a Return value.
Source§

impl PartialEq for Text

Source§

fn eq(&self, other: &Text) -> bool

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

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

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

impl PartialReflect for Text
where Text: Any + Send + Sync, String: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

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<Text>) -> ReflectOwned

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

fn try_into_reflect( self: Box<Text>, ) -> 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<Text>) -> 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 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 clone_value(&self) -> Box<dyn PartialReflect>

👎Deprecated since 0.16.0: to clone reflected values, prefer using reflect_clone. To convert reflected values to dynamic ones, use to_dynamic.
Clones Self into its dynamic representation. Read more
Source§

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

Converts this reflected value into its dynamic representation based on its kind. Read more
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 Text
where Text: Any + Send + Sync, String: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn into_any(self: Box<Text>) -> 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<Text>) -> 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 TextSpanAccess for Text

Source§

fn read_span(&self) -> &str

Gets the text span’s string.
Source§

fn write_span(&mut self) -> &mut String

Gets mutable reference to the text span’s string.
Source§

impl TupleStruct for Text
where Text: Any + Send + Sync, String: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

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

Creates a new DynamicTupleStruct from this tuple struct.
Source§

fn clone_dynamic(&self) -> DynamicTupleStruct

👎Deprecated since 0.16.0: use to_dynamic_tuple_struct instead
Clones the struct into a DynamicTupleStruct.
Source§

fn get_represented_tuple_struct_info(&self) -> Option<&'static TupleStructInfo>

Will return None if TypeInfo is not available.
Source§

impl TypePath for Text
where Text: Any + Send + Sync,

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 Text
where Text: Any + Send + Sync, String: FromReflect + TypePath + MaybeTyped + RegisterForReflection,

Source§

fn type_info() -> &'static TypeInfo

Returns the compile-time info for the underlying type.
Source§

impl StructuralPartialEq for Text

Source§

impl TextRoot for Text

Auto Trait Implementations§

§

impl Freeze for Text

§

impl RefUnwindSafe for Text

§

impl Send for Text

§

impl Sync for Text

§

impl Unpin for Text

§

impl UnwindSafe for Text

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<'_>, ids: &mut impl FnMut(ComponentId), )

Source§

fn register_required_components( components: &mut ComponentsRegistrator<'_>, required_components: &mut RequiredComponents, )

Registers components that are required by the components in this Bundle.
Source§

fn get_component_ids( components: &Components, ids: &mut impl FnMut(Option<ComponentId>), )

Gets 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>,

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

Source§

fn downcast(&self) -> &T

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 + Send + Sync>

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<C> DynamicBundle for C
where C: Component,

Source§

type Effect = ()

An operation on the entity that happens after inserting this bundle.
Source§

fn get_components( self, func: &mut impl FnMut(StorageType, OwningPtr<'_>), ) -> <C as DynamicBundle>::Effect

Source§

impl<T> DynamicTypePath for T
where T: TypePath,

Source§

impl<T> DynamicTyped for T
where T: Typed,

Source§

impl<T> FmtForward for T

Source§

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Formats each item in a sequence. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S> FromSample<S> for S

Source§

fn from_sample_(s: S) -> S

Source§

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

Source§

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

Creates Self using default().

Source§

impl<T> 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> 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<F, T> IntoSample<T> for F
where T: FromSample<F>,

Source§

fn into_sample(self) -> T

Source§

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

Source§

type NoneType = T

Source§

fn null_value() -> T

The none-equivalent value.
Source§

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

Source§

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
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> 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§

unsafe fn read_byte_unchecked(&self, offset: usize) -> u8

Read a byte without doing bounds checks. 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<'_>

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<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> 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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

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

Source§

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

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

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

Performs the conversion.
Source§

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

Source§

impl<T> Upcast<T> for T

Source§

fn upcast(&self) -> Option<&T>

Source§

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

Source§

fn vzip(self) -> V

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

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

Source§

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

Source§

impl<T> Reflectable for T

Source§

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

Source§

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

Source§

impl<T> WasmNotSendSync for T

Source§

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