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: FontSize::Px(60.0),
..Default::default()
},
TextColor(BLUE.into()),
));
// With text justification.
world.spawn((
Text::new("hello world\nand bevy!"),
TextLayout::justify(Justify::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: StringImplementations§
Source§impl Text
impl Text
Sourcepub fn new(text: impl Into<String>) -> Text
pub fn new(text: impl Into<String>) -> Text
Makes a new text component.
Examples found in repository?
More examples
258fn setup_help_text(commands: &mut Commands) {
259 commands.spawn((
260 Text::new(HELP_TEXT),
261 Node {
262 position_type: PositionType::Absolute,
263 top: px(12),
264 left: px(12),
265 ..default()
266 },
267 ));
268}
269
270/// Initializes the node UI widgets.
271fn setup_node_rects(commands: &mut Commands) {
272 for (node_rect, node_type) in NODE_RECTS.iter().zip(NODE_TYPES.iter()) {
273 let node_string = match *node_type {
274 NodeType::Clip(ref clip) => clip.text,
275 NodeType::Blend(text) => text,
276 };
277
278 let text = commands
279 .spawn((
280 Text::new(node_string),
281 TextFont {
282 font_size: FontSize::Px(16.0),
283 ..default()
284 },
285 TextColor(ANTIQUE_WHITE.into()),
286 TextLayout::justify(Justify::Center),
287 ))
288 .id();
289
290 let container = {
291 let mut container = commands.spawn((
292 Node {
293 position_type: PositionType::Absolute,
294 bottom: px(node_rect.bottom),
295 left: px(node_rect.left),
296 height: px(node_rect.height),
297 width: px(node_rect.width),
298 align_items: AlignItems::Center,
299 justify_items: JustifyItems::Center,
300 align_content: AlignContent::Center,
301 justify_content: JustifyContent::Center,
302 ..default()
303 },
304 BorderColor::all(WHITE),
305 Outline::new(px(1), Val::ZERO, Color::WHITE),
306 ));
307
308 if let NodeType::Clip(clip) = node_type {
309 container.insert((
310 Interaction::None,
311 RelativeCursorPosition::default(),
312 (*clip).clone(),
313 ));
314 }
315
316 container.id()
317 };
318
319 // Create the background color.
320 if let NodeType::Clip(_) = node_type {
321 let background = commands
322 .spawn((
323 Node {
324 position_type: PositionType::Absolute,
325 top: px(0),
326 left: px(0),
327 height: px(node_rect.height),
328 width: px(node_rect.width),
329 ..default()
330 },
331 BackgroundColor(DARK_GREEN.into()),
332 ))
333 .id();
334
335 commands.entity(container).add_child(background);
336 }
337
338 commands.entity(container).add_child(text);
339 }
340}377fn spawn_help_text(commands: &mut Commands) {
378 commands.spawn((
379 Text::new(""),
380 Node {
381 position_type: PositionType::Absolute,
382 top: px(12),
383 left: px(12),
384 ..default()
385 },
386 HelpText,
387 ));
388}
389
390/// Moves the sphere a bit every frame.
391fn move_sphere(mut spheres: Query<&mut Transform, With<ReflectiveSphere>>, time: Res<Time>) {
392 let Some(t) = SmoothStepCurve
393 .ping_pong()
394 .unwrap()
395 .forever()
396 .unwrap()
397 .sample(time.elapsed_secs() * SPHERE_MOVEMENT_SPEED)
398 else {
399 return;
400 };
401 for mut sphere_transform in &mut spheres {
402 sphere_transform.translation.z = -ROOM_SEPARATION * t;
403 }
404}
405
406/// Processes requests from the user to move the camera.
407fn orbit_camera(
408 mut cameras: Query<(&mut Transform, &mut OrbitCamera)>,
409 spheres: Query<&Transform, (With<ReflectiveSphere>, Without<OrbitCamera>)>,
410 mouse_buttons: Res<ButtonInput<MouseButton>>,
411 mouse_motion: Res<AccumulatedMouseMotion>,
412 mouse_scroll: Res<AccumulatedMouseScroll>,
413) {
414 // Grab the sphere transform.
415 let Some(sphere_transform) = spheres.iter().next() else {
416 return;
417 };
418
419 for (mut camera_transform, mut orbit_camera) in &mut cameras {
420 // Only pan if the left mouse button is pressed.
421 if mouse_buttons.pressed(MouseButton::Left) {
422 let delta = mouse_motion.delta;
423 orbit_camera.azimuth -= delta.x * CAMERA_ORBIT_SPEED_AZIMUTH;
424 orbit_camera.inclination += delta.y * CAMERA_ORBIT_SPEED_INCLINATION;
425 }
426
427 // Zooming doesn't require a mouse button press, as it uses the mouse
428 // wheel.
429 orbit_camera.radius =
430 (orbit_camera.radius - CAMERA_ZOOM_SPEED * mouse_scroll.delta.y).max(0.01);
431
432 // Calculate the new translation using the [spherical coordinates
433 // formula].
434 //
435 // [spherical coordinates formula]:
436 // https://en.wikipedia.org/wiki/Spherical_coordinate_system#Cartesian_coordinates
437 let new_translation = orbit_camera.radius
438 * vec3(
439 sin(orbit_camera.inclination) * cos(orbit_camera.azimuth),
440 cos(orbit_camera.inclination),
441 sin(orbit_camera.inclination) * sin(orbit_camera.azimuth),
442 );
443
444 // Write in the new transform.
445 *camera_transform =
446 Transform::from_translation(new_translation + sphere_transform.translation)
447 .looking_at(sphere_transform.translation, Vec3::Y);
448 }
449}
450
451/// A system that toggles gizmos on or off when the user clicks on one of the
452/// corresponding radio buttons.
453fn handle_gizmos_enabled_change(
454 mut help_text_query: Query<&mut Text, With<HelpText>>,
455 mut app_status: ResMut<AppStatus>,
456 mut messages: MessageReader<WidgetClickEvent<GizmosEnabled>>,
457) {
458 let mut any_changes = false;
459 for message in messages.read() {
460 app_status.gizmos_enabled = **message;
461 any_changes = true;
462 }
463
464 if any_changes {
465 set_help_text(&app_status, &mut help_text_query);
466 }
467}
468
469/// A system that toggles object visibility when the user clicks on one of the
470/// corresponding radio buttons.
471fn handle_object_to_show_change(
472 mut spheres_query: Query<&mut Visibility, (With<ReflectiveSphere>, Without<ReflectivePrism>)>,
473 mut prisms_query: Query<&mut Visibility, (With<ReflectivePrism>, Without<ReflectiveSphere>)>,
474 mut app_status: ResMut<AppStatus>,
475 mut messages: MessageReader<WidgetClickEvent<ObjectToShow>>,
476) {
477 for message in messages.read() {
478 app_status.object_to_show = **message;
479
480 for mut sphere_visibility in &mut spheres_query {
481 *sphere_visibility = match **message {
482 ObjectToShow::Sphere => Visibility::Inherited,
483 ObjectToShow::Prism => Visibility::Hidden,
484 }
485 }
486 for mut prism_visibility in &mut prisms_query {
487 *prism_visibility = match **message {
488 ObjectToShow::Sphere => Visibility::Hidden,
489 ObjectToShow::Prism => Visibility::Inherited,
490 }
491 }
492 }
493}
494
495/// A system that toggles the camera mode when the user clicks on one of the
496/// corresponding radio buttons.
497fn handle_camera_mode_change(
498 mut commands: Commands,
499 cameras_query: Query<(Entity, &Transform), With<Camera3d>>,
500 sphere_query: Query<&Transform, (With<ReflectiveSphere>, Without<Camera3d>)>,
501 mut help_text_query: Query<&mut Text, With<HelpText>>,
502 mut windows_query: Query<&mut CursorOptions>,
503 mut app_status: ResMut<AppStatus>,
504 mut messages: MessageReader<WidgetClickEvent<CameraMode>>,
505) {
506 let Some(sphere_transform) = sphere_query.iter().next() else {
507 return;
508 };
509
510 let mut any_changes = false;
511 for message in messages.read() {
512 app_status.camera_mode = **message;
513
514 match **message {
515 CameraMode::Orbit => {
516 for (camera_entity, camera_transform) in &cameras_query {
517 // Convert from Cartesian coordinates back to spherical
518 // coordinates.
519 let relative_camera_position =
520 camera_transform.translation - sphere_transform.translation;
521 let radius = relative_camera_position.length();
522 let inclination = atan2(
523 relative_camera_position.xz().length() / radius,
524 relative_camera_position.y / radius,
525 );
526 let azimuth = atan2(
527 relative_camera_position.z * relative_camera_position.xz().length_recip(),
528 relative_camera_position.x * relative_camera_position.xz().length_recip(),
529 );
530
531 commands
532 .entity(camera_entity)
533 .remove::<FreeCamera>()
534 .insert(OrbitCamera {
535 radius,
536 inclination,
537 azimuth,
538 });
539 }
540 }
541
542 CameraMode::Free => {
543 for (camera_entity, _) in &cameras_query {
544 commands
545 .entity(camera_entity)
546 .remove::<OrbitCamera>()
547 .insert(FreeCamera::default());
548 }
549 }
550 }
551
552 any_changes = true;
553 }
554
555 if any_changes {
556 set_help_text(&app_status, &mut help_text_query);
557
558 // Reset the cursor grab mode, because the free camera controller may
559 // have enabled it, and we don't want the cursor to disappear.
560 for mut cursor_options in &mut windows_query {
561 cursor_options.grab_mode = CursorGrabMode::None;
562 cursor_options.visible = true;
563 }
564 }
565}
566
567/// A system that updates the radio buttons at the bottom of the screen to
568/// reflect whether gizmos are enabled or not.
569fn update_radio_buttons(
570 mut widgets_query: Query<(
571 Entity,
572 Option<&mut BackgroundColor>,
573 Has<Text>,
574 AnyOf<(
575 &WidgetClickSender<GizmosEnabled>,
576 &WidgetClickSender<ObjectToShow>,
577 &WidgetClickSender<CameraMode>,
578 )>,
579 )>,
580 app_status: Res<AppStatus>,
581 mut text_ui_writer: TextUiWriter,
582) {
583 for (
584 entity,
585 maybe_bg_color,
586 has_text,
587 (maybe_gizmos_enabled, maybe_object_to_show, maybe_camera_mode),
588 ) in &mut widgets_query
589 {
590 let selected = if let Some(sender) = maybe_gizmos_enabled {
591 app_status.gizmos_enabled == **sender
592 } else if let Some(sender) = maybe_object_to_show {
593 app_status.object_to_show == **sender
594 } else if let Some(sender) = maybe_camera_mode {
595 app_status.camera_mode == **sender
596 } else {
597 continue;
598 };
599
600 if let Some(mut bg_color) = maybe_bg_color {
601 widgets::update_ui_radio_button(&mut bg_color, selected);
602 }
603 if has_text {
604 widgets::update_ui_radio_button_text(entity, &mut text_ui_writer, selected);
605 }
606 }
607}
608
609/// Draws gizmos that show the boundaries of the various boxes associated with
610/// the light probes in the scene.
611fn draw_gizmos(
612 light_probes: Query<(&LightProbe, &ParallaxCorrection, &Transform)>,
613 app_status: Res<AppStatus>,
614 mut gizmos: Gizmos,
615) {
616 // If the user has gizmos disabled, bail.
617 if matches!(app_status.gizmos_enabled, GizmosEnabled::Off) {
618 return;
619 }
620
621 for (light_probe, parallax_correction, transform) in &light_probes {
622 // Draw light probe bounds.
623 gizmos.cube(*transform, TAN);
624
625 // Draw light probe falloff.
626 gizmos.cube(
627 Transform {
628 scale: transform.scale * (Vec3::ONE - light_probe.falloff),
629 ..*transform
630 },
631 CRIMSON,
632 );
633
634 // Draw light probe parallax correction bounds.
635 if let ParallaxCorrection::Custom(parallax_correction_bounds) = *parallax_correction {
636 gizmos.cube(
637 Transform {
638 scale: transform.scale * parallax_correction_bounds,
639 ..*transform
640 },
641 CORNFLOWER_BLUE,
642 );
643 }
644 }
645}
646
647/// Updates the help text at the top of the screen to reflect a change in camera
648/// or gizmo application settings.
649fn set_help_text(app_status: &AppStatus, help_text_query: &mut Query<&mut Text, With<HelpText>>) {
650 for mut ui_text in help_text_query {
651 let mut help_text = String::new();
652 match app_status.camera_mode {
653 CameraMode::Orbit => {
654 help_text.push_str(
655 "Click and drag to orbit the camera\nUse the mouse wheel to zoom the camera\n",
656 );
657 }
658 CameraMode::Free => {
659 help_text.push_str(
660 "Click and drag to rotate the camera\nUse WASDEQ to move the camera\n",
661 );
662 }
663 }
664
665 help_text.push('\n');
666
667 if matches!(app_status.gizmos_enabled, GizmosEnabled::On) {
668 help_text.push_str(
669 "\
670Gizmos:
671Tan: Light probe bounds
672Red: Light probe falloff bounds
673Blue: Parallax correction bounds",
674 );
675 }
676
677 *ui_text = Text::new(help_text);
678 }
679}- examples/app/logs.rs
- examples/ui/layout/ghost_nodes.rs
- examples/shader_advanced/render_depth_to_texture.rs
- examples/3d/clustered_decals.rs
- examples/3d/light_textures.rs
- examples/3d/mirror.rs
- examples/camera/pan_camera_controller.rs
- examples/scene/world_serialization.rs
- examples/camera/2d_top_down_camera.rs
- examples/camera/2d_screen_shake.rs
- examples/asset/multi_asset_sync.rs
- examples/audio/play_sound_effect.rs
- examples/3d/atmospheric_fog.rs
- examples/camera/camera_orbit.rs
- examples/camera/projection_zoom.rs
- examples/asset/alter_mesh.rs
- examples/asset/alter_sprite.rs
- examples/window/window_resizing.rs
- examples/camera/first_person_view_model.rs
- examples/usage/context_menu.rs
- examples/3d/color_grading.rs
- examples/window/custom_cursor_image.rs
- examples/ecs/state_scoped.rs
- examples/ui/layout/flex_layout.rs
- examples/movement/physics_in_fixed_timestep.rs
- examples/dev_tools/fps_overlay.rs
- examples/gizmos/2d_gizmos.rs
- examples/ui/scroll_and_overflow/scrollbars.rs
- examples/ui/window_fallthrough.rs
- examples/showcase/stepping.rs
- examples/audio/audio_control.rs
- examples/showcase/contributors.rs
- examples/ui/layout/anchor_layout.rs
- examples/showcase/loading_screen.rs
- examples/ecs/entity_disabling.rs
- examples/shader_advanced/fullscreen_material.rs
- examples/window/scale_factor_override.rs
- examples/3d/mixed_lighting.rs
- examples/app/settings.rs
- examples/ui/text/font_atlas_debug.rs
- examples/window/screenshot.rs
- examples/3d/tonemapping.rs
- examples/camera/free_camera_controller.rs
- examples/ui/widgets/standard_widgets_observers.rs
- examples/state/custom_transitions.rs
- examples/state/states.rs
- examples/ui/widgets/button.rs
- examples/state/sub_states.rs
- examples/3d/generate_custom_mesh.rs
- examples/audio/spatial_audio_2d.rs
- examples/picking/simple_picking.rs
- examples/ui/relative_cursor_position.rs
- examples/animation/animated_mesh_control.rs
- tests/window/desktop_request_redraw.rs
- examples/ui/text/font_weights.rs
- examples/picking/debug_picking.rs
- examples/remote/app_under_test.rs
- examples/window/multiple_windows.rs
- examples/ui/ui_scaling.rs
- examples/2d/2d_viewport_to_world.rs
- examples/usage/cooldown.rs
- examples/ui/widgets/standard_widgets.rs
- examples/ui/images/ui_texture_atlas.rs
- examples/ui/text/font_variations.rs
- examples/ecs/observers.rs
- examples/animation/animated_ui.rs
- examples/ui/scroll_and_overflow/overflow_debug.rs
- examples/app/render_recovery.rs
- examples/audio/spatial_audio_3d.rs
- examples/ui/text/text_input.rs
- examples/2d/rotation.rs
- examples/3d/rect_light.rs
- examples/ui/images/ui_texture_slice.rs
- examples/2d/sprite_animation.rs
- examples/math/cubic_splines.rs
- examples/ui/text/ime_support.rs
- examples/animation/animation_masks.rs
- tests/3d/test_invalid_skinned_mesh.rs
- examples/time/virtual_time.rs
- examples/ui/layout/size_constraints.rs
- examples/ui/text/generic_font_families.rs
- examples/gizmos/3d_gizmos.rs
- examples/picking/dragdrop_picking.rs
- examples/transforms/align.rs
- examples/ui/styling/transparency_ui.rs
- examples/math/random_sampling.rs
- examples/ui/images/ui_texture_atlas_slice.rs
- examples/state/computed_states.rs
- examples/showcase/alien_cake_addict.rs
- examples/gizmos/transform_gizmo.rs
- examples/3d/spotlight.rs
- examples/showcase/game_menu.rs
- examples/ui/text/system_fonts.rs
- examples/3d/pbr.rs
- examples/ui/ui_target_camera.rs
- examples/math/custom_primitives.rs
- examples/3d/auto_exposure.rs
- examples/window/multi_window_text.rs
- examples/ui/scroll_and_overflow/overflow.rs
- examples/gizmos/light_gizmos.rs
- examples/diagnostics/log_diagnostics.rs
- examples/ui/widgets/vertical_slider.rs
- examples/ui/layout/display_and_visibility.rs
- examples/ui/widgets/tab_navigation.rs
- examples/3d/split_screen.rs
- examples/2d/2d_shapes.rs
- examples/showcase/breakout.rs
- examples/ui/scroll_and_overflow/scroll.rs
- examples/picking/mesh_picking.rs
- examples/ui/render_ui_to_texture.rs
- examples/ui/images/image_node_resizing.rs
- examples/ui/text/strikethrough_and_underline.rs
- examples/ui/navigation/directional_navigation.rs
- examples/stress_tests/many_text.rs
- examples/ui/text/multiple_text_inputs.rs
- examples/ui/ui_drag_and_drop.rs
- examples/ui/styling/box_shadow.rs
- examples/3d/contact_shadows.rs
- examples/ui/text/text.rs
- examples/3d/3d_shapes.rs
- examples/usage/debug_frustum_culling.rs
- examples/3d/blend_modes.rs
- examples/ui/styling/borders.rs
- examples/ui/text/letter_spacing.rs
- examples/ui/navigation/directional_navigation_overrides.rs
- examples/ui/text/text_debug.rs
- examples/ui/layout/grid.rs
- examples/ui/ui_transform.rs
- examples/ui/text/font_query.rs
- examples/ui/text/multiline_text_input.rs
- examples/ui/styling/gradients.rs
- examples/testbed/full_ui.rs
- examples/testbed/ui.rs
Methods from Deref<Target = String>§
1.7.0 · Sourcepub fn as_str(&self) -> &str
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?
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
55fn change_material(
56 scene_ready: On<WorldInstanceReady>,
57 mut commands: Commands,
58 children: Query<&Children>,
59 color_override: Query<&ColorOverride>,
60 mesh_materials: Query<(&MeshMaterial3d<StandardMaterial>, &GltfMaterialName)>,
61 mut asset_materials: ResMut<Assets<StandardMaterial>>,
62) {
63 info!("processing Scene Entity: {}", scene_ready.entity);
64
65 // Get the `ColorOverride` of the entity, if it does not have a color override, return
66 let Ok(color_override) = color_override.get(scene_ready.entity) else {
67 info!("{} does not have a color override", scene_ready.entity);
68 return;
69 };
70
71 // Iterate over all children recursively
72 for descendant in children.iter_descendants(scene_ready.entity) {
73 // Get the material id and name which were created from the glTF file information
74 let Ok((id, material_name)) = mesh_materials.get(descendant) else {
75 continue;
76 };
77 // Get the material of the descendant
78 let Some(material) = asset_materials.get(id.id()) else {
79 continue;
80 };
81
82 // match on the material name, modifying the materials as necessary
83 match material_name.0.as_str() {
84 "LeatherPartsMat" => {
85 info!("editing LeatherPartsMat to use ColorOverride tint");
86 // Create a copy of the material and override base color
87 // If you intend on creating multiple models with the same tint, it
88 // is best to cache the handle somewhere, as having multiple materials
89 // that are identical is expensive
90 let mut new_material = material.clone();
91 new_material.base_color = color_override.0;
92
93 // Override `MeshMaterial3d` with new material
94 commands
95 .entity(descendant)
96 .insert(MeshMaterial3d(asset_materials.add(new_material)));
97 }
98 name => {
99 info!("not replacing: {name}");
100 }
101 }
102 }
103}374fn add_raytracing_meshes_on_scene_load(
375 scene_ready: On<WorldInstanceReady>,
376 children: Query<&Children>,
377 mesh_query: Query<(
378 &Mesh3d,
379 &MeshMaterial3d<StandardMaterial>,
380 Option<&GltfMaterialName>,
381 )>,
382 mut meshes: ResMut<Assets<Mesh>>,
383 mut materials: ResMut<Assets<StandardMaterial>>,
384 mut commands: Commands,
385 args: Res<Args>,
386) {
387 for descendant in children.iter_descendants(scene_ready.entity) {
388 if let Ok((Mesh3d(mesh_handle), MeshMaterial3d(material_handle), material_name)) =
389 mesh_query.get(descendant)
390 {
391 // Add raytracing mesh component
392 commands
393 .entity(descendant)
394 .insert(RaytracingMesh3d(mesh_handle.clone()));
395
396 // Ensure meshes are Solari compatible
397 let mut mesh = meshes.get_mut(mesh_handle).unwrap();
398 if !mesh.contains_attribute(Mesh::ATTRIBUTE_UV_0) {
399 let vertex_count = mesh.count_vertices();
400 mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, vec![[0.0, 0.0]; vertex_count]);
401 mesh.insert_attribute(
402 Mesh::ATTRIBUTE_TANGENT,
403 vec![[0.0, 0.0, 0.0, 0.0]; vertex_count],
404 );
405 }
406 if !mesh.contains_attribute(Mesh::ATTRIBUTE_TANGENT) {
407 mesh.generate_tangents().unwrap();
408 }
409 if mesh.contains_attribute(Mesh::ATTRIBUTE_UV_1) {
410 mesh.remove_attribute(Mesh::ATTRIBUTE_UV_1);
411 }
412 if let Some(indices) = mesh.indices_mut()
413 && let Indices::U16(_) = indices
414 {
415 *indices = Indices::U32(indices.iter().map(|i| i as u32).collect());
416 }
417
418 // Prevent rasterization if using pathtracer
419 if args.pathtracer == Some(true) {
420 commands.entity(descendant).remove::<Mesh3d>();
421 }
422
423 // Adjust scene materials to better demo Solari features
424 if material_name.map(|s| s.0.as_str()) == Some("material") {
425 let mut material = materials.get_mut(material_handle).unwrap();
426 material.emissive = LinearRgba::BLACK;
427 }
428 if material_name.map(|s| s.0.as_str()) == Some("Lights") {
429 let mut material = materials.get_mut(material_handle).unwrap();
430 material.emissive =
431 LinearRgba::from(Color::srgb(0.941, 0.714, 0.043)) * 1_000_000.0;
432 material.alpha_mode = AlphaMode::Opaque;
433 material.specular_transmission = 0.0;
434
435 commands.insert_resource(RobotLightMaterial(material_handle.clone()));
436 }
437 if material_name.map(|s| s.0.as_str()) == Some("Glass_Dark_01") {
438 let mut material = materials.get_mut(material_handle).unwrap();
439 material.alpha_mode = AlphaMode::Opaque;
440 material.specular_transmission = 0.0;
441 }
442 }
443 }
444}395fn update_ui(
396 mut text_query: Single<&mut Text, Without<SceneNumber>>,
397 settings: Single<(&Tonemapping, &ColorGrading)>,
398 current_scene: Res<CurrentScene>,
399 selected_parameter: Res<SelectedParameter>,
400 mut hide_ui: Local<bool>,
401 keys: Res<ButtonInput<KeyCode>>,
402) {
403 if keys.just_pressed(KeyCode::KeyH) {
404 *hide_ui = !*hide_ui;
405 }
406
407 if *hide_ui {
408 if !text_query.is_empty() {
409 // single_mut() always triggers change detection,
410 // so only access if text actually needs changing
411 text_query.clear();
412 }
413 return;
414 }
415
416 let (tonemapping, color_grading) = *settings;
417 let tonemapping = *tonemapping;
418
419 let mut text = String::with_capacity(text_query.len());
420
421 let scn = current_scene.0;
422 text.push_str("(H) Hide UI\n\n");
423 text.push_str("Test Scene: \n");
424 text.push_str(&format!(
425 "(Q) {} Basic Scene\n",
426 if scn == 1 { ">" } else { "" }
427 ));
428 text.push_str(&format!(
429 "(W) {} Color Sweep\n",
430 if scn == 2 { ">" } else { "" }
431 ));
432 text.push_str(&format!(
433 "(E) {} Image Viewer\n",
434 if scn == 3 { ">" } else { "" }
435 ));
436
437 text.push_str("\n\nTonemapping Method:\n");
438 text.push_str(&format!(
439 "(1) {} Disabled\n",
440 if tonemapping == Tonemapping::None {
441 ">"
442 } else {
443 ""
444 }
445 ));
446 text.push_str(&format!(
447 "(2) {} Reinhard\n",
448 if tonemapping == Tonemapping::Reinhard {
449 "> "
450 } else {
451 ""
452 }
453 ));
454 text.push_str(&format!(
455 "(3) {} Reinhard Luminance\n",
456 if tonemapping == Tonemapping::ReinhardLuminance {
457 ">"
458 } else {
459 ""
460 }
461 ));
462 text.push_str(&format!(
463 "(4) {} ACES Fitted\n",
464 if tonemapping == Tonemapping::AcesFitted {
465 ">"
466 } else {
467 ""
468 }
469 ));
470 text.push_str(&format!(
471 "(5) {} AgX\n",
472 if tonemapping == Tonemapping::AgX {
473 ">"
474 } else {
475 ""
476 }
477 ));
478 text.push_str(&format!(
479 "(6) {} SomewhatBoringDisplayTransform\n",
480 if tonemapping == Tonemapping::SomewhatBoringDisplayTransform {
481 ">"
482 } else {
483 ""
484 }
485 ));
486 text.push_str(&format!(
487 "(7) {} TonyMcMapface\n",
488 if tonemapping == Tonemapping::TonyMcMapface {
489 ">"
490 } else {
491 ""
492 }
493 ));
494 text.push_str(&format!(
495 "(8) {} Blender Filmic\n",
496 if tonemapping == Tonemapping::BlenderFilmic {
497 ">"
498 } else {
499 ""
500 }
501 ));
502 text.push_str(&format!(
503 "(9) {} Khronos PBR Neutral\n",
504 if tonemapping == Tonemapping::KhronosPbrNeutral {
505 ">"
506 } else {
507 ""
508 }
509 ));
510
511 text.push_str("\n\nColor Grading:\n");
512 text.push_str("(arrow keys)\n");
513 if selected_parameter.value == 0 {
514 text.push_str("> ");
515 }
516 text.push_str(&format!("Exposure: {:.2}\n", color_grading.global.exposure));
517 if selected_parameter.value == 1 {
518 text.push_str("> ");
519 }
520 text.push_str(&format!("Gamma: {:.2}\n", color_grading.shadows.gamma));
521 if selected_parameter.value == 2 {
522 text.push_str("> ");
523 }
524 text.push_str(&format!(
525 "PreSaturation: {:.2}\n",
526 color_grading.shadows.saturation
527 ));
528 if selected_parameter.value == 3 {
529 text.push_str("> ");
530 }
531 text.push_str(&format!(
532 "PostSaturation: {:.2}\n",
533 color_grading.global.post_saturation
534 ));
535 text.push_str("(Space) Reset all to default\n");
536
537 if current_scene.0 == 1 {
538 text.push_str("(Enter) Reset all to scene recommendation\n");
539 }
540
541 if text != text_query.as_str() {
542 // single_mut() always triggers change detection,
543 // so only access if text actually changed
544 text_query.0 = text;
545 }
546}1.7.0 · Sourcepub fn as_mut_str(&mut self) -> &mut str
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 · Sourcepub fn push_str(&mut self, string: &str)
Available on non-no_global_oom_handling only.
pub fn push_str(&mut self, string: &str)
no_global_oom_handling only.Appends a given string slice onto the end of this String.
§Panics
Panics if the new capacity exceeds isize::MAX bytes.
§Examples
let mut s = String::from("foo");
s.push_str("bar");
assert_eq!("foobar", s);Examples found in repository?
209fn update_lorem_text(mut lorem_text_query: Query<(&mut Text, &mut Lorem)>) {
210 for (mut text, mut lorem) in &mut lorem_text_query {
211 if lorem.0 {
212 text.0.clear();
213 text.0.push_str(LOREM_TEXT_1);
214 } else {
215 text.0.clear();
216 text.0.push_str(LOREM_TEXT_2);
217 }
218
219 lorem.0 = !lorem.0;
220 }
221}More examples
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}93fn toggle_effect(
94 mut text: Single<&mut Text>,
95 keys: Res<ButtonInput<KeyCode>>,
96 camera: Single<(Entity, Option<&FullscreenEffect>), With<Camera3d>>,
97 mut commands: Commands,
98) {
99 if keys.just_pressed(KeyCode::KeyT) {
100 let (entity, effect) = *camera;
101
102 if effect.is_some() {
103 commands.entity(entity).remove::<FullscreenEffect>();
104 text.clear();
105 text.push_str("(T) FullscreenEffect: Off");
106 } else {
107 commands.entity(entity).insert(FullscreenEffect::new(0.0));
108 text.clear();
109 text.push_str("(T) FullscreenEffect: On");
110 }
111 }
112}59fn list_all_named_entities(
60 query: Query<&Name>,
61 mut name_text_query: Query<&mut Text, With<EntityNameText>>,
62 mut commands: Commands,
63) {
64 let mut text_string = String::from("Named entities found:\n");
65 // Query iteration order is not guaranteed, so we sort the names
66 // to ensure the output is consistent.
67 for name in query.iter().sort::<&Name>() {
68 text_string.push_str(&format!("{name:?}\n"));
69 }
70
71 if let Ok(mut text) = name_text_query.single_mut() {
72 *text = Text::new(text_string);
73 } else {
74 commands.spawn((
75 EntityNameText,
76 Text::default(),
77 Node {
78 position_type: PositionType::Absolute,
79 top: px(12),
80 right: px(12),
81 ..default()
82 },
83 ));
84 }
85}219fn update_text(
220 event: On<TextUpdate>,
221 mut textmeta: Single<&mut TextData>,
222 mut text: Single<&mut Text>,
223) {
224 let mut new_text = Text::new(TEXT_PREFIX);
225 match event.direction {
226 Direction::Height => {
227 textmeta.height = (textmeta.height + event.change)
228 .clamp(IMAGE_GROUP_BOX_MIN_HEIGHT, IMAGE_GROUP_BOX_MAX_HEIGHT);
229 new_text.push_str(&format!(
230 "height : {}%, width : {}%",
231 textmeta.height, textmeta.width
232 ));
233 }
234 Direction::Width => {
235 textmeta.width = (textmeta.width + event.change)
236 .clamp(IMAGE_GROUP_BOX_MIN_WIDTH, IMAGE_GROUP_BOX_MAX_WIDTH);
237 new_text.push_str(&format!(
238 "height : {}%, width : {}%",
239 textmeta.height, textmeta.width
240 ));
241 }
242 }
243 text.0 = new_text.0;
244}649fn set_help_text(app_status: &AppStatus, help_text_query: &mut Query<&mut Text, With<HelpText>>) {
650 for mut ui_text in help_text_query {
651 let mut help_text = String::new();
652 match app_status.camera_mode {
653 CameraMode::Orbit => {
654 help_text.push_str(
655 "Click and drag to orbit the camera\nUse the mouse wheel to zoom the camera\n",
656 );
657 }
658 CameraMode::Free => {
659 help_text.push_str(
660 "Click and drag to rotate the camera\nUse WASDEQ to move the camera\n",
661 );
662 }
663 }
664
665 help_text.push('\n');
666
667 if matches!(app_status.gizmos_enabled, GizmosEnabled::On) {
668 help_text.push_str(
669 "\
670Gizmos:
671Tan: Light probe bounds
672Red: Light probe falloff bounds
673Blue: Parallax correction bounds",
674 );
675 }
676
677 *ui_text = Text::new(help_text);
678 }
679}- examples/ui/text/multiple_text_inputs.rs
- examples/asset/processing/asset_processing.rs
- examples/ecs/relationships.rs
- examples/3d/post_processing.rs
- examples/3d/solari.rs
- examples/3d/occlusion_culling.rs
- examples/3d/deferred_rendering.rs
- examples/math/custom_primitives.rs
- examples/3d/ssao.rs
- examples/2d/2d_shapes.rs
- examples/3d/tonemapping.rs
- examples/3d/bloom_3d.rs
- examples/3d/fog.rs
- examples/2d/bloom_2d.rs
- examples/3d/anti_aliasing.rs
- examples/3d/3d_shapes.rs
- examples/ui/text/multiline_text_input.rs
1.87.0 · Sourcepub fn extend_from_within<R>(&mut self, src: R)where
R: RangeBounds<usize>,
Available on non-no_global_oom_handling only.
pub fn extend_from_within<R>(&mut self, src: R)where
R: RangeBounds<usize>,
no_global_oom_handling only.Copies elements from src range to the end of the string.
§Panics
Panics if the range has start_bound > end_bound, if the range is
bounded on either end and does not lie on a char boundary, or if the
new capacity exceeds isize::MAX bytes.
§Examples
let mut string = String::from("abcde");
string.extend_from_within(2..);
assert_eq!(string, "abcdecde");
string.extend_from_within(..2);
assert_eq!(string, "abcdecdeab");
string.extend_from_within(4..8);
assert_eq!(string, "abcdecdeabecde");1.0.0 · Sourcepub fn capacity(&self) -> usize
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 · Sourcepub fn reserve(&mut self, additional: usize)
Available on non-no_global_oom_handling only.
pub fn reserve(&mut self, additional: usize)
no_global_oom_handling only.Reserves capacity for at least additional bytes more than the
current length. The allocator may reserve more space to speculatively
avoid frequent allocations. After calling reserve,
capacity will be greater than or equal to self.len() + additional.
Does nothing if capacity is already sufficient.
§Panics
Panics if the new capacity exceeds isize::MAX bytes.
§Examples
Basic usage:
let mut s = String::new();
s.reserve(10);
assert!(s.capacity() >= 10);This might not actually increase the capacity:
let mut s = String::with_capacity(10);
s.push('a');
s.push('b');
// s now has a length of 2 and a capacity of at least 10
let capacity = s.capacity();
assert_eq!(2, s.len());
assert!(capacity >= 10);
// Since we already have at least an extra 8 capacity, calling this...
s.reserve(8);
// ... doesn't actually increase.
assert_eq!(capacity, s.capacity());Examples found in repository?
177fn synchronize_output_text(
178 changed_inputs: Query<(&EditableText, &TextInputRow), Changed<EditableText>>,
179 mut outputs: Query<(&mut Text, &TextInputRow), With<TextOutput>>,
180) {
181 for (editable_text, input_row) in &changed_inputs {
182 for (mut text, output_row) in &mut outputs {
183 if output_row.0 == input_row.0 {
184 // `EditableText::value()` returns a `SplitString` because Parley may keep IME preedit text
185 // in a contiguous range of the editor’s internal `String` buffer during composition.
186 // The returned `SplitString` omits that preedit range, exposing only the text before and after it.
187 //
188 // To avoid allocating a new `String`, we reserve the total length of the `SplitString`'s slices,
189 // then append them to the output `Text`.
190 text.0.clear();
191 text.0
192 .reserve(editable_text.value().into_iter().map(str::len).sum());
193 for sub_str in editable_text.value() {
194 text.0.push_str(sub_str);
195 }
196 }
197 }
198 }
199}
200
201// Submit the focused input's text when Enter is pressed.
202fn submit_text(
203 mut input_focus: ResMut<InputFocus>,
204 keyboard_input: Res<ButtonInput<Key>>,
205 mut text_input: Query<(&mut EditableText, &TextInputRow)>,
206 mut text_output: Query<(&mut Text, &TextInputRow), With<SubmitOutput>>,
207 tab_navigation: TabNavigation,
208) {
209 if keyboard_input.just_pressed(Key::Enter)
210 && let Some(focused_entity) = input_focus.get()
211 && let Ok((mut editable_text, input_row)) = text_input.get_mut(focused_entity)
212 {
213 for (mut text, output_row) in &mut text_output {
214 if input_row.0 == output_row.0 {
215 text.0.clear();
216 text.0
217 .reserve(editable_text.value().into_iter().map(str::len).sum());
218 for sub_str in editable_text.value() {
219 text.0.push_str(sub_str);
220 }
221 break;
222 }
223 }
224 editable_text.clear();
225
226 if let Ok(next) = tab_navigation.navigate(&input_focus, NavAction::Next) {
227 input_focus.set(next, FocusCause::Navigated);
228 }
229 }
230}More examples
28fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
29 commands.spawn(Camera2d);
30
31 commands
32 .spawn(Node {
33 width: percent(100.),
34 height: percent(100.),
35 justify_content: JustifyContent::Center,
36 align_items: AlignItems::Center,
37 ..default()
38 })
39 .with_children(|parent| {
40 parent
41 .spawn((
42 Node {
43 flex_direction: FlexDirection::Column,
44 align_items: AlignItems::End,
45 row_gap: px(10.),
46 ..default()
47 },
48 TabGroup::default(),
49 ))
50 .with_children(|parent| {
51 parent
52 .spawn((
53 Node {
54 width: px(450.),
55 border: px(2.).all(),
56 padding: px(8.).all(),
57 ..default()
58 },
59 EditableText {
60 visible_lines: Some(8.),
61 allow_newlines: true,
62 ..default()
63 },
64 TextLayout {
65 linebreak: LineBreak::WordOrCharacter,
66 ..default()
67 },
68 TextCursorStyle {
69 color: Color::WHITE,
70 selected_text_color: Some(Color::BLACK),
71 ..default()
72 },
73 TextFont {
74 font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
75 font_size: FontSize::Px(30.),
76 ..default()
77 },
78 BackgroundColor(DARK_SLATE_GRAY.into()),
79 BorderColor::all(SLATE_300),
80 MultilineInput,
81 TabIndex(0),
82 AutoFocus,
83 ))
84 .observe(
85 |on: On<FocusedInput<KeyboardInput>>,
86 keys: Res<ButtonInput<Key>>,
87 input_query: Query<&EditableText, With<MultilineInput>>| {
88 if !(on.input.state.is_pressed()
89 && on.input.logical_key == Key::Enter
90 && keys.pressed(Key::Control))
91 {
92 return;
93 }
94 let Ok(input) = input_query.get(on.focused_entity) else {
95 return;
96 };
97
98 let mut output = String::new();
99 output.reserve(input.value().into_iter().map(str::len).sum());
100 for sub_str in input.value() {
101 output.push_str(sub_str);
102 }
103
104 info!("{output}" );
105 },
106 );
107
108 parent
109 .spawn((
110 Node {
111 flex_direction: FlexDirection::Row,
112 column_gap: px(10.),
113 ..default()
114 },
115 children![
116 (
117 Text::new("visible lines:"),
118 TextFont {
119 font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
120 font_size: FontSize::Px(30.),
121 ..default()
122 },
123 ),
124 (
125 Node {
126 width: px(100.),
127 border: px(2.).all(),
128 ..default()
129 },
130 TextFont {
131 font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
132 font_size: FontSize::Px(30.),
133 ..default()
134 },
135 TextLayout {
136 justify: Justify::End,
137 ..default()
138 },
139 BackgroundColor(DARK_SLATE_GRAY.into()),
140 BorderColor::all(SLATE_300),
141 EditableText::new("8"),
142 EditableTextFilter::new(|c| c.is_ascii_digit() || c == '.'),
143 TextCursorStyle {
144 color: Color::WHITE,
145 selected_text_color: Some(Color::BLACK),
146 unfocused_selection_color: Color::NONE,
147 ..default()
148 },
149 SelectAllOnFocus,
150 VisibleLinesInput,
151 TabIndex(1),
152 )
153 ],
154 ))
155 .observe(
156 |on: On<FocusedInput<KeyboardInput>>,
157 mut query_set: ParamSet<(
158 Query<&EditableText, With<VisibleLinesInput>>,
159 Query<&mut EditableText, With<MultilineInput>>,
160 )>| {
161 if !(on.input.state.is_pressed()
162 && on.input.logical_key == Key::Enter)
163 {
164 return;
165 }
166
167 let visible_lines_query = query_set.p0();
168 let Ok(input) = visible_lines_query.get(on.original_event_target())
169 else {
170 return;
171 };
172
173 let mut output = String::new();
174 output.reserve(input.value().into_iter().map(str::len).sum());
175 for sub_str in input.value() {
176 output.push_str(sub_str);
177 }
178
179 let Ok(lines) = output.parse::<f32>() else {
180 return;
181 };
182
183 let mut multiline_query = query_set.p1();
184 let Ok(mut multiline_input) = multiline_query.single_mut() else {
185 return;
186 };
187
188 multiline_input.visible_lines = Some(lines.clamp(1., 10.));
189 },
190 );
191
192 parent
193 .spawn((
194 Node {
195 flex_direction: FlexDirection::Row,
196 column_gap: px(10.),
197 ..default()
198 },
199 children![
200 (
201 Text::new("font size:"),
202 TextFont {
203 font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
204 font_size: FontSize::Px(30.),
205 ..default()
206 },
207 ),
208 (
209 Node {
210 width: px(100.),
211 border: px(2.).all(),
212 ..default()
213 },
214 TextFont {
215 font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
216 font_size: FontSize::Px(30.),
217 ..default()
218 },
219 TextLayout {
220 justify: Justify::End,
221 ..default()
222 },
223 BackgroundColor(DARK_SLATE_GRAY.into()),
224 BorderColor::all(SLATE_300),
225 EditableText::new("30"),
226 EditableTextFilter::new(|c| c.is_ascii_digit()),
227 TextCursorStyle {
228 color: Color::WHITE,
229 selected_text_color: Some(Color::BLACK),
230 unfocused_selection_color: Color::NONE,
231 ..default()
232 },
233 SelectAllOnFocus,
234 FontSizeInput,
235 TabIndex(2),
236 )
237 ],
238 ))
239 .observe(
240 |on: On<FocusedInput<KeyboardInput>>,
241 font_size_input_query: Query<&EditableText, With<FontSizeInput>>,
242 mut multiline_input_font: Single<
243 &mut TextFont,
244 With<MultilineInput>,
245 >| {
246 if !(on.input.state.is_pressed()
247 && on.input.logical_key == Key::Enter)
248 {
249 return;
250 }
251
252 let Ok(input) =
253 font_size_input_query.get(on.original_event_target())
254 else {
255 return;
256 };
257
258 let mut output = String::new();
259 output.reserve(input.value().into_iter().map(str::len).sum());
260 for sub_str in input.value() {
261 output.push_str(sub_str);
262 }
263
264 let Ok(font_size) = output.parse::<f32>() else {
265 return;
266 };
267
268 multiline_input_font.font_size =
269 FontSize::Px(font_size.clamp(5., 50.));
270 },
271 );
272 });
273 });
274}1.0.0 · Sourcepub fn reserve_exact(&mut self, additional: usize)
Available on non-no_global_oom_handling only.
pub fn reserve_exact(&mut self, additional: usize)
no_global_oom_handling only.Reserves the minimum capacity for at least additional bytes more than
the current length. Unlike reserve, this will not
deliberately over-allocate to speculatively avoid frequent allocations.
After calling reserve_exact, capacity will be greater than or equal to
self.len() + additional. Does nothing if the capacity is already
sufficient.
§Panics
Panics if the new capacity exceeds isize::MAX bytes.
§Examples
Basic usage:
let mut s = String::new();
s.reserve_exact(10);
assert!(s.capacity() >= 10);This might not actually increase the capacity:
let mut s = String::with_capacity(10);
s.push('a');
s.push('b');
// s now has a length of 2 and a capacity of at least 10
let capacity = s.capacity();
assert_eq!(2, s.len());
assert!(capacity >= 10);
// Since we already have at least an extra 8 capacity, calling this...
s.reserve_exact(8);
// ... doesn't actually increase.
assert_eq!(capacity, s.capacity());1.57.0 · Sourcepub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
Tries to reserve capacity for at least additional 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 · Sourcepub fn try_reserve_exact(
&mut self,
additional: usize,
) -> Result<(), TryReserveError>
pub fn try_reserve_exact( &mut self, additional: usize, ) -> Result<(), TryReserveError>
Tries to reserve the minimum capacity for at least additional 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 · Sourcepub fn shrink_to_fit(&mut self)
Available on non-no_global_oom_handling only.
pub fn shrink_to_fit(&mut self)
no_global_oom_handling only.Shrinks the capacity of this String to match its length.
§Examples
let mut s = String::from("foo");
s.reserve(100);
assert!(s.capacity() >= 100);
s.shrink_to_fit();
assert_eq!(3, s.capacity());1.56.0 · Sourcepub fn shrink_to(&mut self, min_capacity: usize)
Available on non-no_global_oom_handling only.
pub fn shrink_to(&mut self, min_capacity: usize)
no_global_oom_handling only.Shrinks the capacity of this String with a lower bound.
The capacity will remain at least as large as both the length and the supplied value.
If the current capacity is less than the lower limit, this is a no-op.
§Examples
let mut s = String::from("foo");
s.reserve(100);
assert!(s.capacity() >= 100);
s.shrink_to(10);
assert!(s.capacity() >= 10);
s.shrink_to(0);
assert!(s.capacity() >= 3);1.0.0 · Sourcepub fn push(&mut self, ch: char)
Available on non-no_global_oom_handling only.
pub fn push(&mut self, ch: char)
no_global_oom_handling only.Appends the given char to the end of this String.
§Panics
Panics if the new capacity exceeds isize::MAX bytes.
§Examples
let mut s = String::from("abc");
s.push('1');
s.push('2');
s.push('3');
assert_eq!("abc123", s);Examples found in repository?
65fn text_update_system(
66 mut state: ResMut<State>,
67 time: Res<Time>,
68 mut query: Query<&mut Text>,
69 mut seeded_rng: ResMut<SeededRng>,
70) {
71 if !state.timer.tick(time.delta()).just_finished() {
72 return;
73 }
74
75 for mut text in &mut query {
76 let c = seeded_rng.random::<u8>() as char;
77 let string = &mut **text;
78 if !string.contains(c) {
79 string.push(c);
80 }
81 }
82}More examples
649fn set_help_text(app_status: &AppStatus, help_text_query: &mut Query<&mut Text, With<HelpText>>) {
650 for mut ui_text in help_text_query {
651 let mut help_text = String::new();
652 match app_status.camera_mode {
653 CameraMode::Orbit => {
654 help_text.push_str(
655 "Click and drag to orbit the camera\nUse the mouse wheel to zoom the camera\n",
656 );
657 }
658 CameraMode::Free => {
659 help_text.push_str(
660 "Click and drag to rotate the camera\nUse WASDEQ to move the camera\n",
661 );
662 }
663 }
664
665 help_text.push('\n');
666
667 if matches!(app_status.gizmos_enabled, GizmosEnabled::On) {
668 help_text.push_str(
669 "\
670Gizmos:
671Tan: Light probe bounds
672Red: Light probe falloff bounds
673Blue: Parallax correction bounds",
674 );
675 }
676
677 *ui_text = Text::new(help_text);
678 }
679}1.0.0 · Sourcepub fn as_bytes(&self) -> &[u8] ⓘ
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?
More examples
169 async fn save(
170 &self,
171 writer: &mut Writer,
172 asset: SavedAsset<'_, '_, Self::Asset>,
173 _settings: &Self::Settings,
174 _asset_path: AssetPath<'_>,
175 ) -> Result<(), Self::Error> {
176 let boxes = asset
177 .boxes
178 .iter()
179 .map(|handle| {
180 asset
181 .get_labeled_by_id::<OneBox>(handle)
182 .unwrap()
183 .get()
184 .clone()
185 })
186 .collect();
187
188 // Note: serializing to string isn't ideal since we can't do a streaming write, but this is
189 // fine for an example.
190 let serialized = ron::to_string(&SerializableManyBoxes { boxes })?;
191 writer.write_all(serialized.as_bytes()).await?;
192
193 Ok(())
194 }151fn setup_assets_programmatically(
152 commands: &mut Commands,
153 asset_server: &mut AssetServer,
154 animation_graphs: &mut Assets<AnimationGraph>,
155 _save: bool,
156) {
157 // Create the nodes.
158 let mut animation_graph = AnimationGraph::new();
159 let blend_node = animation_graph.add_blend(0.5, animation_graph.root);
160 animation_graph.add_clip(
161 asset_server.load(GltfAssetLabel::Animation(0).from_asset("models/animated/Fox.glb")),
162 1.0,
163 animation_graph.root,
164 );
165 animation_graph.add_clip(
166 asset_server.load(GltfAssetLabel::Animation(1).from_asset("models/animated/Fox.glb")),
167 1.0,
168 blend_node,
169 );
170 animation_graph.add_clip(
171 asset_server.load(GltfAssetLabel::Animation(2).from_asset("models/animated/Fox.glb")),
172 1.0,
173 blend_node,
174 );
175
176 // If asked to save, do so.
177 #[cfg(not(target_arch = "wasm32"))]
178 if _save {
179 let animation_graph = animation_graph.clone();
180
181 IoTaskPool::get()
182 .spawn(async move {
183 use std::io::Write;
184
185 let animation_graph: SerializedAnimationGraph = animation_graph
186 .try_into()
187 .expect("The animation graph failed to convert to its serialized form");
188
189 let serialized_graph =
190 ron::ser::to_string_pretty(&animation_graph, PrettyConfig::default())
191 .expect("Failed to serialize the animation graph");
192 let mut animation_graph_writer = File::create(Path::join(
193 &FileAssetReader::get_base_path(),
194 Path::join(Path::new("assets"), Path::new(ANIMATION_GRAPH_PATH)),
195 ))
196 .expect("Failed to open the animation graph asset");
197 animation_graph_writer
198 .write_all(serialized_graph.as_bytes())
199 .expect("Failed to write the animation graph");
200 })
201 .detach();
202 }
203
204 // Add the graph.
205 let handle = animation_graphs.add(animation_graph);
206
207 // Save the assets in a resource.
208 commands.insert_resource(ExampleAnimationGraph(handle));
209}166fn save_world_system(world: &mut World) {
167 let asset_server = world.resource::<AssetServer>().clone();
168 // The `TypeRegistry` resource contains information about all registered types (including components).
169 // This is used to construct worlds, so we'll want to ensure that we use the registry from the
170 // main world. To do this, we can simply clone the `AppTypeRegistry` resource.
171 let type_registry = world.resource::<AppTypeRegistry>().clone();
172
173 // Any ECS World can be serialized.
174 // For demonstration purposes, we'll create a new one.
175 let mut scene_world = World::new();
176
177 let mut component_b = ComponentB::from_world(world);
178 component_b.value = "hello".to_string();
179 scene_world.spawn((
180 component_b,
181 ComponentA { x: 1.0, y: 2.0 },
182 Transform::IDENTITY,
183 Name::new("joe"),
184 WorldAssetRoot(asset_server.load("models/FlightHelmet/FlightHelmet.gltf#Scene0")),
185 ));
186 scene_world.spawn(ComponentA { x: 3.0, y: 4.0 });
187 scene_world.insert_resource(ResourceA { score: 1 });
188
189 // With our sample world ready to go, we can now create a DynamicWorld from it.
190 // For simplicity, we will create our scene using DynamicWorld directly, but if
191 // you need more control, you can use DynamicWorldBuilder.
192 let dynamic_world = DynamicWorld::from_world_with(&scene_world, &type_registry.read());
193
194 // Dynamic Worlds can be serialized like this:
195 let type_registry = world.resource::<AppTypeRegistry>();
196 let type_registry = type_registry.read();
197 let serialized_world = dynamic_world.serialize(&type_registry).unwrap();
198
199 // Shows the serialized world in the console
200 info!("{}", serialized_world);
201
202 // Writing the world to a new file. Using a task to avoid calling the filesystem APIs in a system
203 // as they are blocking.
204 //
205 // This can't work in Wasm as there is no filesystem access.
206 #[cfg(not(target_arch = "wasm32"))]
207 IoTaskPool::get()
208 .spawn(async move {
209 // Write the world RON data to file
210 File::create(format!("assets/{NEW_WORLD_FILE_PATH}"))
211 .and_then(|mut file| file.write(serialized_world.as_bytes()))
212 .expect("Error while writing world to file");
213 })
214 .detach();
215}1.0.0 · Sourcepub fn truncate(&mut self, new_len: usize)
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 · Sourcepub fn remove(&mut self, idx: usize) -> char
pub fn remove(&mut self, idx: usize) -> char
Removes a char from this String at byte position idx and returns it.
Copies all bytes after the removed char to new positions.
Note that calling this in a loop can result in quadratic behavior.
§Panics
Panics if idx is larger than or equal to the String’s length,
or if it does not lie on a char boundary.
§Examples
let mut s = String::from("abç");
assert_eq!(s.remove(0), 'a');
assert_eq!(s.remove(1), 'ç');
assert_eq!(s.remove(0), 'b');Sourcepub fn remove_matches<P>(&mut self, pat: P)where
P: Pattern,
🔬This is a nightly-only experimental API. (string_remove_matches)Available on non-no_global_oom_handling only.
pub fn remove_matches<P>(&mut self, pat: P)where
P: Pattern,
string_remove_matches)no_global_oom_handling only.Remove all matches of pattern pat in the String.
§Examples
#![feature(string_remove_matches)]
let mut s = String::from("Trees are not green, the sky is not blue.");
s.remove_matches("not ");
assert_eq!("Trees are green, the sky is blue.", s);Matches will be detected and removed iteratively, so in cases where patterns overlap, only the first pattern will be removed:
#![feature(string_remove_matches)]
let mut s = String::from("banana");
s.remove_matches("ana");
assert_eq!("bna", s);1.26.0 · Sourcepub fn retain<F>(&mut self, f: F)
pub fn retain<F>(&mut self, f: F)
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 · Sourcepub fn insert(&mut self, idx: usize, ch: char)
Available on non-no_global_oom_handling only.
pub fn insert(&mut self, idx: usize, ch: char)
no_global_oom_handling only.Inserts a character into this String at byte position idx.
Reallocates if self.capacity() is insufficient, which may involve copying all
self.capacity() bytes. Makes space for the insertion by copying all bytes of
&self[idx..] to new positions.
Note that calling this in a loop can result in quadratic behavior.
§Panics
Panics if idx is larger than the String’s length, or if it does not
lie on a char boundary.
§Examples
let mut s = String::with_capacity(3);
s.insert(0, 'f');
s.insert(1, 'o');
s.insert(2, 'o');
assert_eq!("foo", s);1.16.0 · Sourcepub fn insert_str(&mut self, idx: usize, string: &str)
Available on non-no_global_oom_handling only.
pub fn insert_str(&mut self, idx: usize, string: &str)
no_global_oom_handling only.Inserts a string slice into this String at byte position idx.
Reallocates if self.capacity() is insufficient, which may involve copying all
self.capacity() bytes. Makes space for the insertion by copying all bytes of
&self[idx..] to new positions.
Note that calling this in a loop can result in quadratic behavior.
§Panics
Panics if idx is larger than the String’s length, or if it does not
lie on a char boundary.
§Examples
let mut s = String::from("bar");
s.insert_str(0, "foo");
assert_eq!("foobar", s);1.0.0 · Sourcepub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> ⓘ
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 · Sourcepub fn len(&self) -> usize
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?
395fn update_ui(
396 mut text_query: Single<&mut Text, Without<SceneNumber>>,
397 settings: Single<(&Tonemapping, &ColorGrading)>,
398 current_scene: Res<CurrentScene>,
399 selected_parameter: Res<SelectedParameter>,
400 mut hide_ui: Local<bool>,
401 keys: Res<ButtonInput<KeyCode>>,
402) {
403 if keys.just_pressed(KeyCode::KeyH) {
404 *hide_ui = !*hide_ui;
405 }
406
407 if *hide_ui {
408 if !text_query.is_empty() {
409 // single_mut() always triggers change detection,
410 // so only access if text actually needs changing
411 text_query.clear();
412 }
413 return;
414 }
415
416 let (tonemapping, color_grading) = *settings;
417 let tonemapping = *tonemapping;
418
419 let mut text = String::with_capacity(text_query.len());
420
421 let scn = current_scene.0;
422 text.push_str("(H) Hide UI\n\n");
423 text.push_str("Test Scene: \n");
424 text.push_str(&format!(
425 "(Q) {} Basic Scene\n",
426 if scn == 1 { ">" } else { "" }
427 ));
428 text.push_str(&format!(
429 "(W) {} Color Sweep\n",
430 if scn == 2 { ">" } else { "" }
431 ));
432 text.push_str(&format!(
433 "(E) {} Image Viewer\n",
434 if scn == 3 { ">" } else { "" }
435 ));
436
437 text.push_str("\n\nTonemapping Method:\n");
438 text.push_str(&format!(
439 "(1) {} Disabled\n",
440 if tonemapping == Tonemapping::None {
441 ">"
442 } else {
443 ""
444 }
445 ));
446 text.push_str(&format!(
447 "(2) {} Reinhard\n",
448 if tonemapping == Tonemapping::Reinhard {
449 "> "
450 } else {
451 ""
452 }
453 ));
454 text.push_str(&format!(
455 "(3) {} Reinhard Luminance\n",
456 if tonemapping == Tonemapping::ReinhardLuminance {
457 ">"
458 } else {
459 ""
460 }
461 ));
462 text.push_str(&format!(
463 "(4) {} ACES Fitted\n",
464 if tonemapping == Tonemapping::AcesFitted {
465 ">"
466 } else {
467 ""
468 }
469 ));
470 text.push_str(&format!(
471 "(5) {} AgX\n",
472 if tonemapping == Tonemapping::AgX {
473 ">"
474 } else {
475 ""
476 }
477 ));
478 text.push_str(&format!(
479 "(6) {} SomewhatBoringDisplayTransform\n",
480 if tonemapping == Tonemapping::SomewhatBoringDisplayTransform {
481 ">"
482 } else {
483 ""
484 }
485 ));
486 text.push_str(&format!(
487 "(7) {} TonyMcMapface\n",
488 if tonemapping == Tonemapping::TonyMcMapface {
489 ">"
490 } else {
491 ""
492 }
493 ));
494 text.push_str(&format!(
495 "(8) {} Blender Filmic\n",
496 if tonemapping == Tonemapping::BlenderFilmic {
497 ">"
498 } else {
499 ""
500 }
501 ));
502 text.push_str(&format!(
503 "(9) {} Khronos PBR Neutral\n",
504 if tonemapping == Tonemapping::KhronosPbrNeutral {
505 ">"
506 } else {
507 ""
508 }
509 ));
510
511 text.push_str("\n\nColor Grading:\n");
512 text.push_str("(arrow keys)\n");
513 if selected_parameter.value == 0 {
514 text.push_str("> ");
515 }
516 text.push_str(&format!("Exposure: {:.2}\n", color_grading.global.exposure));
517 if selected_parameter.value == 1 {
518 text.push_str("> ");
519 }
520 text.push_str(&format!("Gamma: {:.2}\n", color_grading.shadows.gamma));
521 if selected_parameter.value == 2 {
522 text.push_str("> ");
523 }
524 text.push_str(&format!(
525 "PreSaturation: {:.2}\n",
526 color_grading.shadows.saturation
527 ));
528 if selected_parameter.value == 3 {
529 text.push_str("> ");
530 }
531 text.push_str(&format!(
532 "PostSaturation: {:.2}\n",
533 color_grading.global.post_saturation
534 ));
535 text.push_str("(Space) Reset all to default\n");
536
537 if current_scene.0 == 1 {
538 text.push_str("(Enter) Reset all to scene recommendation\n");
539 }
540
541 if text != text_query.as_str() {
542 // single_mut() always triggers change detection,
543 // so only access if text actually changed
544 text_query.0 = text;
545 }
546}1.0.0 · Sourcepub fn is_empty(&self) -> bool
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?
395fn update_ui(
396 mut text_query: Single<&mut Text, Without<SceneNumber>>,
397 settings: Single<(&Tonemapping, &ColorGrading)>,
398 current_scene: Res<CurrentScene>,
399 selected_parameter: Res<SelectedParameter>,
400 mut hide_ui: Local<bool>,
401 keys: Res<ButtonInput<KeyCode>>,
402) {
403 if keys.just_pressed(KeyCode::KeyH) {
404 *hide_ui = !*hide_ui;
405 }
406
407 if *hide_ui {
408 if !text_query.is_empty() {
409 // single_mut() always triggers change detection,
410 // so only access if text actually needs changing
411 text_query.clear();
412 }
413 return;
414 }
415
416 let (tonemapping, color_grading) = *settings;
417 let tonemapping = *tonemapping;
418
419 let mut text = String::with_capacity(text_query.len());
420
421 let scn = current_scene.0;
422 text.push_str("(H) Hide UI\n\n");
423 text.push_str("Test Scene: \n");
424 text.push_str(&format!(
425 "(Q) {} Basic Scene\n",
426 if scn == 1 { ">" } else { "" }
427 ));
428 text.push_str(&format!(
429 "(W) {} Color Sweep\n",
430 if scn == 2 { ">" } else { "" }
431 ));
432 text.push_str(&format!(
433 "(E) {} Image Viewer\n",
434 if scn == 3 { ">" } else { "" }
435 ));
436
437 text.push_str("\n\nTonemapping Method:\n");
438 text.push_str(&format!(
439 "(1) {} Disabled\n",
440 if tonemapping == Tonemapping::None {
441 ">"
442 } else {
443 ""
444 }
445 ));
446 text.push_str(&format!(
447 "(2) {} Reinhard\n",
448 if tonemapping == Tonemapping::Reinhard {
449 "> "
450 } else {
451 ""
452 }
453 ));
454 text.push_str(&format!(
455 "(3) {} Reinhard Luminance\n",
456 if tonemapping == Tonemapping::ReinhardLuminance {
457 ">"
458 } else {
459 ""
460 }
461 ));
462 text.push_str(&format!(
463 "(4) {} ACES Fitted\n",
464 if tonemapping == Tonemapping::AcesFitted {
465 ">"
466 } else {
467 ""
468 }
469 ));
470 text.push_str(&format!(
471 "(5) {} AgX\n",
472 if tonemapping == Tonemapping::AgX {
473 ">"
474 } else {
475 ""
476 }
477 ));
478 text.push_str(&format!(
479 "(6) {} SomewhatBoringDisplayTransform\n",
480 if tonemapping == Tonemapping::SomewhatBoringDisplayTransform {
481 ">"
482 } else {
483 ""
484 }
485 ));
486 text.push_str(&format!(
487 "(7) {} TonyMcMapface\n",
488 if tonemapping == Tonemapping::TonyMcMapface {
489 ">"
490 } else {
491 ""
492 }
493 ));
494 text.push_str(&format!(
495 "(8) {} Blender Filmic\n",
496 if tonemapping == Tonemapping::BlenderFilmic {
497 ">"
498 } else {
499 ""
500 }
501 ));
502 text.push_str(&format!(
503 "(9) {} Khronos PBR Neutral\n",
504 if tonemapping == Tonemapping::KhronosPbrNeutral {
505 ">"
506 } else {
507 ""
508 }
509 ));
510
511 text.push_str("\n\nColor Grading:\n");
512 text.push_str("(arrow keys)\n");
513 if selected_parameter.value == 0 {
514 text.push_str("> ");
515 }
516 text.push_str(&format!("Exposure: {:.2}\n", color_grading.global.exposure));
517 if selected_parameter.value == 1 {
518 text.push_str("> ");
519 }
520 text.push_str(&format!("Gamma: {:.2}\n", color_grading.shadows.gamma));
521 if selected_parameter.value == 2 {
522 text.push_str("> ");
523 }
524 text.push_str(&format!(
525 "PreSaturation: {:.2}\n",
526 color_grading.shadows.saturation
527 ));
528 if selected_parameter.value == 3 {
529 text.push_str("> ");
530 }
531 text.push_str(&format!(
532 "PostSaturation: {:.2}\n",
533 color_grading.global.post_saturation
534 ));
535 text.push_str("(Space) Reset all to default\n");
536
537 if current_scene.0 == 1 {
538 text.push_str("(Enter) Reset all to scene recommendation\n");
539 }
540
541 if text != text_query.as_str() {
542 // single_mut() always triggers change detection,
543 // so only access if text actually changed
544 text_query.0 = text;
545 }
546}More examples
69fn main() {
70 let mut world = World::new();
71 let mut lines = std::io::stdin().lines();
72 let mut component_names = HashMap::<String, ComponentId>::new();
73 let mut component_info = HashMap::<ComponentId, ComponentInfo>::new();
74 let mut event_names = HashMap::<String, EventKey>::new();
75
76 println!("{PROMPT}");
77 loop {
78 print!("\n> ");
79 let _ = std::io::stdout().flush();
80 let Some(Ok(line)) = lines.next() else {
81 return;
82 };
83
84 if line.is_empty() {
85 return;
86 };
87
88 let Some((first, rest)) = line.trim().split_once(|c: char| c.is_whitespace()) else {
89 match &line.chars().next() {
90 Some('c') => println!("{COMPONENT_PROMPT}"),
91 Some('s') => println!("{ENTITY_PROMPT}"),
92 Some('q') => println!("{QUERY_PROMPT}"),
93 Some('e') => println!("{EVENT_PROMPT}"),
94 Some('t') => println!("{EMIT_PROMPT}"),
95 _ => println!("{PROMPT}"),
96 }
97 continue;
98 };
99
100 match &first[0..1] {
101 "c" => {
102 rest.split(',').for_each(|component| {
103 let mut component = component.split_whitespace();
104 let Some(name) = component.next() else {
105 return;
106 };
107 let size = match component.next().map(str::parse) {
108 Some(Ok(size)) => size,
109 _ => 0,
110 };
111 // Register our new component to the world with a layout specified by it's size
112 // SAFETY: [u64] is Send + Sync
113 let id = world.register_component_with_descriptor(unsafe {
114 ComponentDescriptor::new_with_layout(
115 name.to_string(),
116 StorageType::Table,
117 Layout::array::<u64>(size).unwrap(),
118 None,
119 true,
120 ComponentCloneBehavior::Default,
121 None,
122 )
123 });
124 let Some(info) = world.components().get_info(id) else {
125 return;
126 };
127 component_names.insert(name.to_string(), id);
128 component_info.insert(id, info.clone());
129 println!("Component {} created with id: {}", name, id.index());
130 });
131 }
132 "s" => {
133 let mut to_insert_ids = Vec::new();
134 let mut to_insert_data = Vec::new();
135 rest.split(',').for_each(|component| {
136 let mut component = component.split_whitespace();
137 let Some(name) = component.next() else {
138 return;
139 };
140
141 // Get the id for the component with the given name
142 let Some(&id) = component_names.get(name) else {
143 println!("Component {name} does not exist");
144 return;
145 };
146
147 // Calculate the length for the array based on the layout created for this component id
148 let info = world.components().get_info(id).unwrap();
149 let len = info.layout().size() / size_of::<u64>();
150 let mut values: Vec<u64> = component
151 .take(len)
152 .filter_map(|value| value.parse::<u64>().ok())
153 .collect();
154 values.resize(len, 0);
155
156 // Collect the id and array to be inserted onto our entity
157 to_insert_ids.push(id);
158 to_insert_data.push(values);
159 });
160
161 let mut entity = world.spawn_empty();
162
163 // Construct an `OwningPtr` for each component in `to_insert_data`
164 let to_insert_ptr = to_owning_ptrs(&mut to_insert_data);
165
166 // SAFETY:
167 // - Component ids have been taken from the same world
168 // - Each array is created to the layout specified in the world
169 unsafe {
170 entity.insert_by_ids(&to_insert_ids, to_insert_ptr.into_iter());
171 }
172
173 println!("Entity spawned with id: {}", entity.id());
174 }
175 "q" => {
176 let mut builder = QueryBuilder::<FilteredEntityMut>::new(&mut world);
177 parse_query(rest, &mut builder, &component_names);
178 let mut query = builder.build();
179 query.iter_mut(&mut world).for_each(|filtered_entity| {
180 let terms = filtered_entity
181 .access()
182 .try_iter_access()
183 .unwrap()
184 .map(|component_access| {
185 let id = *component_access.index();
186 let ptr = filtered_entity.get_by_id(id).unwrap();
187 let info = component_info.get(&id).unwrap();
188 let len = info.layout().size() / size_of::<u64>();
189
190 // SAFETY:
191 // - All components are created with layout [u64]
192 // - len is calculated from the component descriptor
193 let data = unsafe {
194 std::slice::from_raw_parts_mut(
195 ptr.assert_unique().as_ptr().cast::<u64>(),
196 len,
197 )
198 };
199
200 // If we have write access, increment each value once
201 if matches!(component_access, ComponentAccessKind::Exclusive(_)) {
202 data.iter_mut().for_each(|data| {
203 *data += 1;
204 });
205 }
206
207 format!("{}: {:?}", info.name(), data[0..len].to_vec())
208 })
209 .collect::<Vec<_>>()
210 .join(", ");
211
212 println!("{}: {}", filtered_entity.id(), terms);
213 });
214 }
215 "e" => {
216 rest.split(',').for_each(|event| {
217 let name = event.trim();
218 if name.is_empty() {
219 return;
220 }
221
222 // Register a ComponentId for this event, no Rust type needed.
223 // SAFETY: ZST with no drop
224 let event_component_id = world.register_component_with_descriptor(unsafe {
225 ComponentDescriptor::new_with_layout(
226 format!("event:{name}"),
227 StorageType::Table,
228 Layout::new::<()>(),
229 None,
230 false,
231 ComponentCloneBehavior::Ignore,
232 None,
233 )
234 });
235 // SAFETY: event_component_id was just registered for this event
236 let event_key = unsafe { EventKey::new(event_component_id) };
237 event_names.insert(name.to_string(), event_key);
238
239 // Build a dynamic observer that prints when the event fires.
240 let runner: ObserverRunner = |mut world, _observer, ctx, _event, _trigger| {
241 println!(" Observer fired!");
242 if let Some(mut counts) = world.get_resource_mut::<EventFireCount>() {
243 *counts.0.entry(ctx.event_key).or_insert(0) += 1;
244 }
245 };
246
247 // SAFETY: event_key was just registered, runner ignores pointers
248 let observer =
249 unsafe { Observer::with_dynamic_runner(runner).with_event_key(event_key) };
250 world.spawn(observer);
251
252 println!(
253 "Event '{name}' registered (key: {}) with a dynamic observer",
254 event_component_id.index()
255 );
256 });
257
258 // Ensure the counter resource exists.
259 world.init_resource::<EventFireCount>();
260 }
261 "t" => {
262 let name = rest.trim();
263 let Some(&event_key) = event_names.get(name) else {
264 println!(
265 "Event '{name}' does not exist. Register it first with 'event {name}'"
266 );
267 continue;
268 };
269
270 let mut event_data = ();
271 let mut trigger_data = ();
272 // SAFETY: event_key was registered in this world, both pointers are valid ZSTs
273 unsafe {
274 world.trigger_dynamic(
275 event_key,
276 PtrMut::from(&mut event_data),
277 PtrMut::from(&mut trigger_data),
278 );
279 }
280
281 let count = world
282 .get_resource::<EventFireCount>()
283 .map_or(0, |c| c.0.get(&event_key).copied().unwrap_or(0));
284 println!("Event '{name}' triggered ({count} fires)");
285 }
286 _ => continue,
287 }
288 }
289}1.16.0 · Sourcepub fn split_off(&mut self, at: usize) -> String
Available on non-no_global_oom_handling only.
pub fn split_off(&mut self, at: usize) -> String
no_global_oom_handling only.Splits the string into two at the given byte index.
Returns a newly allocated String. self contains bytes [0, at), and
the returned String contains bytes [at, len). at must be on the
boundary of a UTF-8 code point.
Note that the capacity of self does not change.
§Panics
Panics if at is not on a UTF-8 code point boundary, or if it is beyond the last
code point of the string.
§Examples
let mut hello = String::from("Hello, World!");
let world = hello.split_off(7);
assert_eq!(hello, "Hello, ");
assert_eq!(world, "World!");1.0.0 · Sourcepub fn clear(&mut self)
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?
209fn update_lorem_text(mut lorem_text_query: Query<(&mut Text, &mut Lorem)>) {
210 for (mut text, mut lorem) in &mut lorem_text_query {
211 if lorem.0 {
212 text.0.clear();
213 text.0.push_str(LOREM_TEXT_1);
214 } else {
215 text.0.clear();
216 text.0.push_str(LOREM_TEXT_2);
217 }
218
219 lorem.0 = !lorem.0;
220 }
221}More examples
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}93fn toggle_effect(
94 mut text: Single<&mut Text>,
95 keys: Res<ButtonInput<KeyCode>>,
96 camera: Single<(Entity, Option<&FullscreenEffect>), With<Camera3d>>,
97 mut commands: Commands,
98) {
99 if keys.just_pressed(KeyCode::KeyT) {
100 let (entity, effect) = *camera;
101
102 if effect.is_some() {
103 commands.entity(entity).remove::<FullscreenEffect>();
104 text.clear();
105 text.push_str("(T) FullscreenEffect: Off");
106 } else {
107 commands.entity(entity).insert(FullscreenEffect::new(0.0));
108 text.clear();
109 text.push_str("(T) FullscreenEffect: On");
110 }
111 }
112}177fn synchronize_output_text(
178 changed_inputs: Query<(&EditableText, &TextInputRow), Changed<EditableText>>,
179 mut outputs: Query<(&mut Text, &TextInputRow), With<TextOutput>>,
180) {
181 for (editable_text, input_row) in &changed_inputs {
182 for (mut text, output_row) in &mut outputs {
183 if output_row.0 == input_row.0 {
184 // `EditableText::value()` returns a `SplitString` because Parley may keep IME preedit text
185 // in a contiguous range of the editor’s internal `String` buffer during composition.
186 // The returned `SplitString` omits that preedit range, exposing only the text before and after it.
187 //
188 // To avoid allocating a new `String`, we reserve the total length of the `SplitString`'s slices,
189 // then append them to the output `Text`.
190 text.0.clear();
191 text.0
192 .reserve(editable_text.value().into_iter().map(str::len).sum());
193 for sub_str in editable_text.value() {
194 text.0.push_str(sub_str);
195 }
196 }
197 }
198 }
199}
200
201// Submit the focused input's text when Enter is pressed.
202fn submit_text(
203 mut input_focus: ResMut<InputFocus>,
204 keyboard_input: Res<ButtonInput<Key>>,
205 mut text_input: Query<(&mut EditableText, &TextInputRow)>,
206 mut text_output: Query<(&mut Text, &TextInputRow), With<SubmitOutput>>,
207 tab_navigation: TabNavigation,
208) {
209 if keyboard_input.just_pressed(Key::Enter)
210 && let Some(focused_entity) = input_focus.get()
211 && let Ok((mut editable_text, input_row)) = text_input.get_mut(focused_entity)
212 {
213 for (mut text, output_row) in &mut text_output {
214 if input_row.0 == output_row.0 {
215 text.0.clear();
216 text.0
217 .reserve(editable_text.value().into_iter().map(str::len).sum());
218 for sub_str in editable_text.value() {
219 text.0.push_str(sub_str);
220 }
221 break;
222 }
223 }
224 editable_text.clear();
225
226 if let Ok(next) = tab_navigation.navigate(&input_focus, NavAction::Next) {
227 input_focus.set(next, FocusCause::Navigated);
228 }
229 }
230}270fn update_help_text(mut text: Single<&mut Text>, app_settings: Res<AppSettings>) {
271 text.clear();
272 let text_list = [
273 format!(
274 "Chromatic aberration intensity: {:.2}\n",
275 app_settings.chromatic_aberration_intensity
276 ),
277 format!(
278 "Vignette intensity: {:.2}\n",
279 app_settings.vignette_intensity
280 ),
281 format!("Vignette radius: {:.2}\n", app_settings.vignette_radius),
282 format!(
283 "Vignette smoothness: {:.2}\n",
284 app_settings.vignette_smoothness
285 ),
286 format!(
287 "Vignette roundness: {:.2}\n",
288 app_settings.vignette_roundness
289 ),
290 format!(
291 "Vignette edge_compensation: {:.2}\n",
292 app_settings.vignette_edge_compensation
293 ),
294 format!(
295 "Lens Distortion intensity: {:.2}\n",
296 app_settings.lens_distortion_intensity
297 ),
298 format!(
299 "Lens Distortion multiplier x: {:.2}\n",
300 app_settings.lens_distortion_multiplier_x
301 ),
302 format!(
303 "Lens Distortion multiplier y: {:.2}\n",
304 app_settings.lens_distortion_multiplier_y
305 ),
306 ];
307 for (i, val) in text_list.iter().enumerate() {
308 if i == app_settings.selected {
309 text.push_str("> ");
310 }
311 text.push_str(val);
312 }
313 text.push_str("\n(Press Up or Down to select)\n(Press Left or Right to change)");
314}528fn update_control_text(
529 mut text: Single<&mut Text, With<ControlText>>,
530 robot_light_material: Option<Res<RobotLightMaterial>>,
531 materials: Res<Assets<StandardMaterial>>,
532 directional_light: Query<Entity, With<DirectionalLight>>,
533 time: Res<Time<Virtual>>,
534 #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] dlss_rr_supported: Option<
535 Res<DlssRayReconstructionSupported>,
536 >,
537) {
538 text.0.clear();
539
540 if time.is_paused() {
541 text.0.push_str("(Space): Resume");
542 } else {
543 text.0.push_str("(Space): Pause");
544 }
545
546 if directional_light.single().is_ok() {
547 text.0.push_str("\n(1): Disable directional light");
548 } else {
549 text.0.push_str("\n(1): Enable directional light");
550 }
551
552 match robot_light_material.and_then(|m| materials.get(&m.0)) {
553 Some(robot_light_material) if robot_light_material.emissive != LinearRgba::BLACK => {
554 text.0.push_str("\n(2): Disable robot emissive light");
555 }
556 _ => {
557 text.0.push_str("\n(2): Enable robot emissive light");
558 }
559 }
560
561 #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
562 if dlss_rr_supported.is_some() {
563 text.0
564 .push_str("\nDenoising: DLSS Ray Reconstruction enabled");
565 } else {
566 text.0
567 .push_str("\nDenoising: DLSS Ray Reconstruction not supported");
568 }
569
570 #[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))]
571 text.0
572 .push_str("\nDenoising: App not compiled with DLSS support");
573}
574
575#[derive(Component)]
576struct PerformanceText;
577
578fn update_performance_text(
579 mut text: Single<&mut Text, With<PerformanceText>>,
580 diagnostics: Res<DiagnosticsStore>,
581) {
582 text.0.clear();
583
584 let mut total = 0.0;
585 let mut add_diagnostic = |name: &str, path: &'static str| {
586 let path = DiagnosticPath::new(path);
587 if let Some(value) = diagnostics.get(&path).and_then(Diagnostic::smoothed) {
588 text.push_str(&format!("{name:17} {value:.2} ms\n"));
589 total += value;
590 }
591 };
592
593 (add_diagnostic)(
594 "Light tiles",
595 "render/solari_lighting/presample_light_tiles/elapsed_gpu",
596 );
597 (add_diagnostic)(
598 "World cache",
599 "render/solari_lighting/world_cache/elapsed_gpu",
600 );
601 (add_diagnostic)(
602 "Direct lighting",
603 "render/solari_lighting/direct_lighting/elapsed_gpu",
604 );
605 (add_diagnostic)(
606 "Diffuse indirect",
607 "render/solari_lighting/diffuse_indirect_lighting/elapsed_gpu",
608 );
609 (add_diagnostic)(
610 "Specular indirect",
611 "render/solari_lighting/specular_indirect_lighting/elapsed_gpu",
612 );
613 (add_diagnostic)("DLSS-RR", "render/dlss_ray_reconstruction/elapsed_gpu");
614 text.push_str(&format!("{:17} {total:.2} ms\n", "Total"));
615
616 if let Some(world_cache_active_cells_count) = diagnostics
617 .get(&DiagnosticPath::new(
618 "render/solari_lighting/world_cache_active_cells_count",
619 ))
620 .and_then(Diagnostic::smoothed)
621 {
622 text.push_str(&format!(
623 "\nWorld cache cells {} ({:.0}%)",
624 world_cache_active_cells_count as u32,
625 (world_cache_active_cells_count * 100.0) / (2u64.pow(20) as f64)
626 ));
627 }
628}1.6.0 · Sourcepub fn drain<R>(&mut self, range: R) -> Drain<'_> ⓘwhere
R: RangeBounds<usize>,
pub fn drain<R>(&mut self, range: R) -> Drain<'_> ⓘwhere
R: RangeBounds<usize>,
Removes the specified range from the string in bulk, returning all removed characters as an iterator.
The returned iterator keeps a mutable borrow on the string to optimize its implementation.
§Panics
Panics if the range has start_bound > end_bound, or, if the range is
bounded on either end and does not lie on a char boundary.
§Leaking
If the returned iterator goes out of scope without being dropped (due to
core::mem::forget, for example), the string may still contain a copy
of any drained characters, or may have lost characters arbitrarily,
including characters outside the range.
§Examples
let mut s = String::from("α is alpha, β is beta");
let beta_offset = s.find('β').unwrap_or(s.len());
// Remove the range up until the β from the string
let t: String = s.drain(..beta_offset).collect();
assert_eq!(t, "α is alpha, ");
assert_eq!(s, "β is beta");
// A full range clears the string, like `clear()` does
s.drain(..);
assert_eq!(s, "");1.27.0 · Sourcepub fn replace_range<R>(&mut self, range: R, replace_with: &str)where
R: RangeBounds<usize>,
Available on non-no_global_oom_handling only.
pub fn replace_range<R>(&mut self, range: R, replace_with: &str)where
R: RangeBounds<usize>,
no_global_oom_handling only.Removes the specified range in the string, and replaces it with the given string. The given string doesn’t need to be the same length as the range.
§Panics
Panics if the range has start_bound > end_bound, or, if the range is
bounded on either end and does not lie on a char boundary.
§Examples
let mut s = String::from("α is alpha, β is beta");
let beta_offset = s.find('β').unwrap_or(s.len());
// Replace the range up until the β from the string
s.replace_range(..beta_offset, "Α is capital alpha; ");
assert_eq!(s, "Α is capital alpha; β is beta");Sourcepub fn replace_first<P>(&mut self, from: P, to: &str)where
P: Pattern,
🔬This is a nightly-only experimental API. (string_replace_in_place)Available on non-no_global_oom_handling only.
pub fn replace_first<P>(&mut self, from: P, to: &str)where
P: Pattern,
string_replace_in_place)no_global_oom_handling only.Replaces the leftmost occurrence of a pattern with another string, in-place.
This method can be preferred over string = string.replacen(..., 1);,
as it can use the String’s existing capacity to prevent a reallocation if
sufficient space is available.
§Examples
Basic usage:
#![feature(string_replace_in_place)]
let mut s = String::from("Test Results: ❌❌❌");
// Replace the leftmost ❌ with a ✅
s.replace_first('❌', "✅");
assert_eq!(s, "Test Results: ✅❌❌");Sourcepub fn replace_last<P>(&mut self, from: P, to: &str)
🔬This is a nightly-only experimental API. (string_replace_in_place)Available on non-no_global_oom_handling only.
pub fn replace_last<P>(&mut self, from: P, to: &str)
string_replace_in_place)no_global_oom_handling only.Replaces the rightmost occurrence of a pattern with another string, in-place.
§Examples
Basic usage:
#![feature(string_replace_in_place)]
let mut s = String::from("Test Results: ❌❌❌");
// Replace the rightmost ❌ with a ✅
s.replace_last('❌', "✅");
assert_eq!(s, "Test Results: ❌❌✅");Methods from Deref<Target = str>§
1.0.0 · Sourcepub fn is_empty(&self) -> bool
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 · Sourcepub fn is_char_boundary(&self, index: usize) -> bool
pub fn is_char_boundary(&self, index: usize) -> bool
Checks that index-th byte is the first byte in a UTF-8 code point
sequence or the end of the string.
The start and end of the string (when index == self.len()) are
considered to be boundaries.
Returns false if index is greater than self.len().
§Examples
let s = "Löwe 老虎 Léopard";
assert!(s.is_char_boundary(0));
// start of `老`
assert!(s.is_char_boundary(6));
assert!(s.is_char_boundary(s.len()));
// second byte of `ö`
assert!(!s.is_char_boundary(2));
// third byte of `老`
assert!(!s.is_char_boundary(8));1.91.0 · Sourcepub fn floor_char_boundary(&self, index: usize) -> usize
pub fn floor_char_boundary(&self, index: usize) -> usize
Finds the closest x not exceeding index where is_char_boundary(x) is true.
This method can help you truncate a string so that it’s still valid UTF-8, but doesn’t exceed a given number of bytes. Note that this is done purely at the character level and can still visually split graphemes, even though the underlying characters aren’t split. For example, the emoji 🧑🔬 (scientist) could be split so that the string only includes 🧑 (person) instead.
§Examples
let s = "❤️🧡💛💚💙💜";
assert_eq!(s.len(), 26);
assert!(!s.is_char_boundary(13));
let closest = s.floor_char_boundary(13);
assert_eq!(closest, 10);
assert_eq!(&s[..closest], "❤️🧡");1.91.0 · Sourcepub fn ceil_char_boundary(&self, index: usize) -> usize
pub fn ceil_char_boundary(&self, index: usize) -> usize
Finds the closest x not below index where is_char_boundary(x) is true.
If index is greater than the length of the string, this returns the length of the string.
This method is the natural complement to floor_char_boundary. See that method
for more details.
§Examples
let s = "❤️🧡💛💚💙💜";
assert_eq!(s.len(), 26);
assert!(!s.is_char_boundary(13));
let closest = s.ceil_char_boundary(13);
assert_eq!(closest, 14);
assert_eq!(&s[..closest], "❤️🧡💛");1.20.0 · Sourcepub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] ⓘ
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 · Sourcepub fn as_ptr(&self) -> *const u8
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 · Sourcepub fn as_mut_ptr(&mut self) -> *mut u8
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 · Sourcepub fn get<I>(&self, i: I) -> Option<&<I as SliceIndex<str>>::Output>where
I: SliceIndex<str>,
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 · Sourcepub fn get_mut<I>(
&mut self,
i: I,
) -> Option<&mut <I as SliceIndex<str>>::Output>where
I: SliceIndex<str>,
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 · Sourcepub unsafe fn get_unchecked<I>(&self, i: I) -> &<I as SliceIndex<str>>::Outputwhere
I: SliceIndex<str>,
pub unsafe fn get_unchecked<I>(&self, i: I) -> &<I as SliceIndex<str>>::Outputwhere
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 · Sourcepub unsafe fn get_unchecked_mut<I>(
&mut self,
i: I,
) -> &mut <I as SliceIndex<str>>::Outputwhere
I: SliceIndex<str>,
pub unsafe fn get_unchecked_mut<I>(
&mut self,
i: I,
) -> &mut <I as SliceIndex<str>>::Outputwhere
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 · Sourcepub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str
👎Deprecated since 1.29.0: use get_unchecked(begin..end) instead
pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str
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:
beginmust not exceedend.beginandendmust be byte positions within the string slice.beginandendmust 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 · Sourcepub 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
pub unsafe fn slice_mut_unchecked( &mut self, begin: usize, end: usize, ) -> &mut str
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:
beginmust not exceedend.beginandendmust be byte positions within the string slice.beginandendmust lie on UTF-8 sequence boundaries.
1.4.0 · Sourcepub fn split_at(&self, mid: usize) -> (&str, &str)
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 · Sourcepub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str)
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 · Sourcepub fn split_at_checked(&self, mid: usize) -> Option<(&str, &str)>
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 length1.80.0 · Sourcepub fn split_at_mut_checked(
&mut self,
mid: usize,
) -> Option<(&mut str, &mut str)>
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 length1.0.0 · Sourcepub fn chars(&self) -> Chars<'_> ⓘ
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 · Sourcepub fn char_indices(&self) -> CharIndices<'_> ⓘ
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 · Sourcepub fn bytes(&self) -> Bytes<'_> ⓘ
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 · Sourcepub fn split_whitespace(&self) -> SplitWhitespace<'_> ⓘ
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 · Sourcepub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> ⓘ
pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> ⓘ
Splits a string slice by ASCII whitespace.
The iterator returned will return string slices that are sub-slices of the original string slice, separated by any amount of ASCII whitespace.
This uses the same definition as char::is_ascii_whitespace.
To split by Unicode Whitespace instead, use split_whitespace.
Note that because of this difference in definition, even if s.is_ascii()
is true, s.split_ascii_whitespace() behavior will differ from s.split_whitespace()
if s contains U+000B VERTICAL TAB.
§Examples
Basic usage:
let mut iter = "A few words".split_ascii_whitespace();
assert_eq!(Some("A"), iter.next());
assert_eq!(Some("few"), iter.next());
assert_eq!(Some("words"), iter.next());
assert_eq!(None, iter.next());Various kinds of ASCII whitespace are considered
(see char::is_ascii_whitespace):
let mut iter = " Mary had\ta little \n\t lamb".split_ascii_whitespace();
assert_eq!(Some("Mary"), iter.next());
assert_eq!(Some("had"), iter.next());
assert_eq!(Some("a"), iter.next());
assert_eq!(Some("little"), iter.next());
assert_eq!(Some("lamb"), iter.next());
assert_eq!(None, iter.next());If the string is empty or all ASCII whitespace, the iterator yields no string slices:
assert_eq!("".split_ascii_whitespace().next(), None);
assert_eq!(" ".split_ascii_whitespace().next(), None);1.0.0 · Sourcepub fn lines(&self) -> Lines<'_> ⓘ
pub fn lines(&self) -> Lines<'_> ⓘ
Returns an iterator over the lines of a string, as string slices.
Lines are split at line endings that are either newlines (\n) or
sequences of a carriage return followed by a line feed (\r\n).
Line terminators are not included in the lines returned by the iterator.
Note that any carriage return (\r) not immediately followed by a
line feed (\n) does not split a line. These carriage returns are
thereby included in the produced lines.
The final line ending is optional. A string that ends with a final line ending will return the same lines as an otherwise identical string without a final line ending.
An empty string returns an empty iterator.
§Examples
Basic usage:
let text = "foo\r\nbar\n\nbaz\r";
let mut lines = text.lines();
assert_eq!(Some("foo"), lines.next());
assert_eq!(Some("bar"), lines.next());
assert_eq!(Some(""), lines.next());
// Trailing carriage return is included in the last line
assert_eq!(Some("baz\r"), lines.next());
assert_eq!(None, lines.next());The final line does not require any ending:
let text = "foo\nbar\n\r\nbaz";
let mut lines = text.lines();
assert_eq!(Some("foo"), lines.next());
assert_eq!(Some("bar"), lines.next());
assert_eq!(Some(""), lines.next());
assert_eq!(Some("baz"), lines.next());
assert_eq!(None, lines.next());An empty string returns an empty iterator:
let text = "";
let mut lines = text.lines();
assert_eq!(lines.next(), None);1.0.0 · Sourcepub fn lines_any(&self) -> LinesAny<'_> ⓘ
👎Deprecated since 1.4.0: use lines() instead now
pub fn lines_any(&self) -> LinesAny<'_> ⓘ
use lines() instead now
Returns an iterator over the lines of a string.
1.8.0 · Sourcepub fn encode_utf16(&self) -> EncodeUtf16<'_> ⓘ
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 · Sourcepub fn contains<P>(&self, pat: P) -> boolwhere
P: Pattern,
pub fn contains<P>(&self, pat: P) -> boolwhere
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 · Sourcepub fn starts_with<P>(&self, pat: P) -> boolwhere
P: Pattern,
pub fn starts_with<P>(&self, pat: P) -> boolwhere
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 · Sourcepub fn ends_with<P>(&self, pat: P) -> bool
pub fn ends_with<P>(&self, pat: P) -> bool
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 · Sourcepub fn find<P>(&self, pat: P) -> Option<usize>where
P: Pattern,
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 · Sourcepub fn rfind<P>(&self, pat: P) -> Option<usize>
pub fn rfind<P>(&self, pat: P) -> Option<usize>
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 · Sourcepub fn split<P>(&self, pat: P) -> Split<'_, P> ⓘwhere
P: Pattern,
pub fn split<P>(&self, pat: P) -> Split<'_, P> ⓘwhere
P: Pattern,
Returns an iterator over substrings of this string slice, separated by characters matched by a pattern.
The pattern can be a &str, char, a slice of chars, or a
function or closure that determines if a character matches.
If there are no matches the full string slice is returned as the only item in the iterator.
§Iterator behavior
The returned iterator will be a DoubleEndedIterator if the pattern
allows a reverse search and forward/reverse search yields the same
elements. This is true for, e.g., char, but not for &str.
If the pattern allows a reverse search but its results might differ
from a forward search, the rsplit method can be used.
§Examples
Simple patterns:
let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
let v: Vec<&str> = "".split('X').collect();
assert_eq!(v, [""]);
let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
assert_eq!(v, ["lion", "", "tiger", "leopard"]);
let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
assert_eq!(v, ["lion", "tiger", "leopard"]);
let v: Vec<&str> = "AABBCC".split("DD").collect();
assert_eq!(v, ["AABBCC"]);
let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
assert_eq!(v, ["abc", "def", "ghi"]);
let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
assert_eq!(v, ["lion", "tiger", "leopard"]);If the pattern is a slice of chars, split on each occurrence of any of the characters:
let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect();
assert_eq!(v, ["2020", "11", "03", "23", "59"]);A more complex pattern, using a closure:
let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
assert_eq!(v, ["abc", "def", "ghi"]);If a string contains multiple contiguous separators, you will end up with empty strings in the output:
let x = "||||a||b|c".to_string();
let d: Vec<_> = x.split('|').collect();
assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);Contiguous separators are separated by the empty string.
let x = "(///)".to_string();
let d: Vec<_> = x.split('/').collect();
assert_eq!(d, &["(", "", "", ")"]);Separators at the start or end of a string are neighbored by empty strings.
let d: Vec<_> = "010".split("0").collect();
assert_eq!(d, &["", "1", ""]);When the empty string is used as a separator, it separates every character in the string, along with the beginning and end of the string.
let f: Vec<_> = "rust".split("").collect();
assert_eq!(f, &["", "r", "u", "s", "t", ""]);Contiguous separators can lead to possibly surprising behavior when whitespace is used as the separator. This code is correct:
let x = " a b c".to_string();
let d: Vec<_> = x.split(' ').collect();
assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);It does not give you:
assert_eq!(d, &["a", "b", "c"]);Use split_whitespace for this behavior.
1.51.0 · Sourcepub fn split_inclusive<P>(&self, pat: P) -> SplitInclusive<'_, P> ⓘwhere
P: Pattern,
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 · Sourcepub fn rsplit<P>(&self, pat: P) -> RSplit<'_, P> ⓘ
pub fn rsplit<P>(&self, pat: P) -> RSplit<'_, P> ⓘ
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 · Sourcepub fn split_terminator<P>(&self, pat: P) -> SplitTerminator<'_, P> ⓘwhere
P: Pattern,
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 · Sourcepub fn rsplit_terminator<P>(&self, pat: P) -> RSplitTerminator<'_, P> ⓘ
pub fn rsplit_terminator<P>(&self, pat: P) -> RSplitTerminator<'_, P> ⓘ
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 · Sourcepub fn splitn<P>(&self, n: usize, pat: P) -> SplitN<'_, P> ⓘwhere
P: Pattern,
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 · Sourcepub fn rsplitn<P>(&self, n: usize, pat: P) -> RSplitN<'_, P> ⓘ
pub fn rsplitn<P>(&self, n: usize, pat: P) -> RSplitN<'_, P> ⓘ
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 · Sourcepub fn split_once<P>(&self, delimiter: P) -> Option<(&str, &str)>where
P: Pattern,
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 · Sourcepub fn rsplit_once<P>(&self, delimiter: P) -> Option<(&str, &str)>
pub fn rsplit_once<P>(&self, delimiter: P) -> Option<(&str, &str)>
Splits the string on the last occurrence of the specified delimiter and returns prefix before delimiter and suffix after delimiter.
§Examples
assert_eq!("cfg".rsplit_once('='), None);
assert_eq!("cfg=".rsplit_once('='), Some(("cfg", "")));
assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo")));
assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));1.2.0 · Sourcepub fn matches<P>(&self, pat: P) -> Matches<'_, P> ⓘwhere
P: Pattern,
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 · Sourcepub fn rmatches<P>(&self, pat: P) -> RMatches<'_, P> ⓘ
pub fn rmatches<P>(&self, pat: P) -> RMatches<'_, P> ⓘ
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 · Sourcepub fn match_indices<P>(&self, pat: P) -> MatchIndices<'_, P> ⓘwhere
P: Pattern,
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 · Sourcepub fn rmatch_indices<P>(&self, pat: P) -> RMatchIndices<'_, P> ⓘ
pub fn rmatch_indices<P>(&self, pat: P) -> RMatchIndices<'_, P> ⓘ
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 · Sourcepub fn trim(&self) -> &str
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 · Sourcepub fn trim_start(&self) -> &str
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 · Sourcepub fn trim_end(&self) -> &str
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 · Sourcepub fn trim_left(&self) -> &str
👎Deprecated since 1.33.0: superseded by trim_start
pub fn trim_left(&self) -> &str
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 · Sourcepub fn trim_right(&self) -> &str
👎Deprecated since 1.33.0: superseded by trim_end
pub fn trim_right(&self) -> &str
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 · Sourcepub fn trim_matches<P>(&self, pat: P) -> &str
pub fn trim_matches<P>(&self, pat: P) -> &str
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 · Sourcepub fn trim_start_matches<P>(&self, pat: P) -> &strwhere
P: Pattern,
pub fn trim_start_matches<P>(&self, pat: P) -> &strwhere
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 · Sourcepub fn strip_prefix<P>(&self, prefix: P) -> Option<&str>where
P: Pattern,
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 · Sourcepub fn strip_suffix<P>(&self, suffix: P) -> Option<&str>
pub fn strip_suffix<P>(&self, suffix: P) -> Option<&str>
Returns a string slice with the suffix removed.
If the string ends with the pattern suffix, returns the substring before the suffix,
wrapped in Some. Unlike trim_end_matches, this method removes the suffix exactly once.
If the string does not end with suffix, returns None.
The pattern can be a &str, char, a slice of chars, or a
function or closure that determines if a character matches.
§Examples
assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
assert_eq!("bar:foo".strip_suffix("bar"), None);
assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));1.98.0 · Sourcepub fn strip_circumfix<P, S>(&self, prefix: P, suffix: S) -> Option<&str>
pub fn strip_circumfix<P, S>(&self, prefix: P, suffix: S) -> Option<&str>
Returns a string slice with the prefix and suffix removed.
If the string starts with the pattern prefix and ends with
the pattern suffix, and the prefix and suffix don’t overlap, returns
the substring after the prefix and before the suffix, wrapped in Some.
Unlike trim_start_matches and trim_end_matches, this method removes both the prefix
and suffix exactly once.
If the string does not start with prefix, does not end with suffix,
or the prefix and suffix overlap in the string, returns None.
Each pattern can be a &str, char, a slice of chars, or a
function or closure that determines if a character matches.
§Examples
assert_eq!("bar:hello:foo".strip_circumfix("bar:", ":foo"), Some("hello"));
assert_eq!("bar:foo".strip_circumfix("foo", "foo"), None);
assert_eq!("foo:bar;".strip_circumfix("foo:", ';'), Some("bar"));
assert_eq!("foo:bar:baz".strip_circumfix("foo:bar:", ":bar:baz"), None);Sourcepub fn trim_prefix<P>(&self, prefix: P) -> &strwhere
P: Pattern,
🔬This is a nightly-only experimental API. (trim_prefix_suffix)
pub fn trim_prefix<P>(&self, prefix: P) -> &strwhere
P: Pattern,
trim_prefix_suffix)Returns a string slice with the optional prefix removed.
If the string starts with the pattern prefix, returns the substring after the prefix.
Unlike strip_prefix, this method always returns &str for easy method chaining,
instead of returning Option<&str>.
If the string does not start with prefix, returns the original string unchanged.
The pattern can be a &str, char, a slice of chars, or a
function or closure that determines if a character matches.
§Examples
#![feature(trim_prefix_suffix)]
// Prefix present - removes it
assert_eq!("foo:bar".trim_prefix("foo:"), "bar");
assert_eq!("foofoo".trim_prefix("foo"), "foo");
// Prefix absent - returns original string
assert_eq!("foo:bar".trim_prefix("bar"), "foo:bar");
// Method chaining example
assert_eq!("<https://example.com/>".trim_prefix('<').trim_suffix('>'), "https://example.com/");Sourcepub fn trim_suffix<P>(&self, suffix: P) -> &str
🔬This is a nightly-only experimental API. (trim_prefix_suffix)
pub fn trim_suffix<P>(&self, suffix: P) -> &str
trim_prefix_suffix)Returns a string slice with the optional suffix removed.
If the string ends with the pattern suffix, returns the substring before the suffix.
Unlike strip_suffix, this method always returns &str for easy method chaining,
instead of returning Option<&str>.
If the string does not end with suffix, returns the original string unchanged.
The pattern can be a &str, char, a slice of chars, or a
function or closure that determines if a character matches.
§Examples
#![feature(trim_prefix_suffix)]
// Suffix present - removes it
assert_eq!("bar:foo".trim_suffix(":foo"), "bar");
assert_eq!("foofoo".trim_suffix("foo"), "foo");
// Suffix absent - returns original string
assert_eq!("bar:foo".trim_suffix("bar"), "bar:foo");
// Method chaining example
assert_eq!("<https://example.com/>".trim_prefix('<').trim_suffix('>'), "https://example.com/");1.30.0 · Sourcepub fn trim_end_matches<P>(&self, pat: P) -> &str
pub fn trim_end_matches<P>(&self, pat: P) -> &str
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 · Sourcepub fn trim_left_matches<P>(&self, pat: P) -> &strwhere
P: Pattern,
👎Deprecated since 1.33.0: superseded by trim_start_matches
pub fn trim_left_matches<P>(&self, pat: P) -> &strwhere
P: Pattern,
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 · Sourcepub fn trim_right_matches<P>(&self, pat: P) -> &str
👎Deprecated since 1.33.0: superseded by trim_end_matches
pub fn trim_right_matches<P>(&self, pat: P) -> &str
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 · Sourcepub fn parse<F>(&self) -> Result<F, <F as FromStr>::Err>where
F: FromStr,
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 · Sourcepub fn is_ascii(&self) -> bool
pub fn is_ascii(&self) -> bool
Checks if all characters in this string are within the ASCII range.
An empty string returns true.
§Examples
let ascii = "hello!\n";
let non_ascii = "Grüße, Jürgen ❤";
assert!(ascii.is_ascii());
assert!(!non_ascii.is_ascii());Sourcepub fn as_ascii(&self) -> Option<&[AsciiChar]>
🔬This is a nightly-only experimental API. (ascii_char)
pub fn as_ascii(&self) -> Option<&[AsciiChar]>
ascii_char)If this string slice is_ascii, returns it as a slice
of ASCII characters, otherwise returns None.
Sourcepub unsafe fn as_ascii_unchecked(&self) -> &[AsciiChar]
🔬This is a nightly-only experimental API. (ascii_char)
pub unsafe fn as_ascii_unchecked(&self) -> &[AsciiChar]
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 · Sourcepub fn eq_ignore_ascii_case(&self, other: &str) -> bool
pub fn eq_ignore_ascii_case(&self, other: &str) -> bool
Checks that two strings are an ASCII case-insensitive match.
Same as to_ascii_lowercase(a) == to_ascii_lowercase(b),
but without allocating and copying temporaries.
For Unicode-aware case-insensitive matching, consider
str::eq_ignore_case_unnormalized.
§Examples
assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));Sourcepub fn eq_ignore_case_unnormalized(&self, other: &str) -> bool
🔬This is a nightly-only experimental API. (casefold)
pub fn eq_ignore_case_unnormalized(&self, other: &str) -> bool
casefold)Checks that two strings are a caseless match, according to Definition 144 in Chapter 3 of the Unicode Standard.
Same as a.to_casefold_unnormalized() == b.to_casefold_unnormalized(),
but without allocating. See that method’s documentation,
as well as char::to_casefold_unnormalized(),
for more information about case folding.
No normalization (e.g. NFC) is performed, so visually and semantically identical strings
might still compare unequal. For example, "Å" (U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE)
is considered distinct from "Å" (A followed by U+030A COMBINING RING ABOVE),
even though Unicode considers them canonically equivalent.
In addition, this method is independent of language/locale, so the special behavior of I/ı/İ/i in Turkish and Azeri is not handled.
§Examples
#![feature(casefold)]
assert!("Ferris".eq_ignore_case_unnormalized("FERRIS"));
assert!("Ferrös".eq_ignore_case_unnormalized("FERRÖS"));
assert!("ẞ".eq_ignore_case_unnormalized("ss"));No NFC normalization is performed:
#![feature(casefold)]
// These two strings are visually and semantically identical...
let comp = "Å";
let decomp = "Å";
// ... but not codepoint-for-codepoint equal.
assert_eq!(comp, "\u{C5}");
assert_eq!(decomp, "A\u{030A}");
// Their case-foldings are likewise unequal:
assert!(!comp.eq_ignore_case_unnormalized(decomp));1.23.0 · Sourcepub fn make_ascii_uppercase(&mut self)
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 · Sourcepub fn make_ascii_lowercase(&mut self)
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);Sourcepub fn copy_from_str(&mut self, src: &str)
🔬This is a nightly-only experimental API. (str_copy_from_str)
pub fn copy_from_str(&mut self, src: &str)
str_copy_from_str)Copies the string from src into self, using a memcpy.
The length of src must be the same as self.
§Panics
This function will panic if the two strings have different lengths.
§Examples
#![feature(str_copy_from_str)]
let src = "Saludos";
let mut dst = String::from("Grüße, Jürgen");
// Because the strings have to be the same length,
// we slice the destination slice from sixteen bytes
// to seven. It will panic if we don't do this.
dst[..7].copy_from_str(src);
assert_eq!(src, "Saludos");
assert_eq!(dst, "Saludos, Jürgen");Rust enforces that there can only be one mutable reference with no
immutable references to a particular piece of data in a particular
scope. Because of this, attempting to use copy_from_str on a
single string will result in a compile failure:
#![feature(str_copy_from_str)]
let mut string = String::from("Abcde");
string[..2].copy_from_str(&string[3..]); // compile fail!To work around this, we can use split_at_mut to create two distinct
sub-slices from a string:
#![feature(str_copy_from_str)]
let mut string = String::from("Abcde");
{
let (left, right) = string.split_at_mut(2);
left.copy_from_str(&right[1..]);
}
assert_eq!(string, "decde");1.80.0 · Sourcepub fn trim_ascii_start(&self) -> &str
pub fn trim_ascii_start(&self) -> &str
Returns a string slice with leading ASCII whitespace removed.
‘Whitespace’ refers to the definition used by
u8::is_ascii_whitespace. Importantly, this definition excludes
the U+000B code point even though it has the Unicode White_Space property
and is removed by str::trim_start.
§Examples
assert_eq!(" \t \u{3000}hello world\n".trim_ascii_start(), "\u{3000}hello world\n");
assert_eq!(" ".trim_ascii_start(), "");
assert_eq!("".trim_ascii_start(), "");1.80.0 · Sourcepub fn trim_ascii_end(&self) -> &str
pub fn trim_ascii_end(&self) -> &str
Returns a string slice with trailing ASCII whitespace removed.
‘Whitespace’ refers to the definition used by
u8::is_ascii_whitespace. Importantly, this definition excludes
the U+000B code point even though it has the Unicode White_Space property
and is removed by str::trim_end.
§Examples
assert_eq!("\r hello world\u{3000}\n ".trim_ascii_end(), "\r hello world\u{3000}");
assert_eq!(" ".trim_ascii_end(), "");
assert_eq!("".trim_ascii_end(), "");1.80.0 · Sourcepub fn trim_ascii(&self) -> &str
pub fn trim_ascii(&self) -> &str
Returns a string slice with leading and trailing ASCII whitespace removed.
‘Whitespace’ refers to the definition used by
u8::is_ascii_whitespace. Importantly, this definition excludes
the U+000B code point even though it has the Unicode White_Space property
and is removed by str::trim.
§Examples
assert_eq!("\r hello world\n ".trim_ascii(), "hello world");
assert_eq!(" ".trim_ascii(), "");
assert_eq!("".trim_ascii(), "");1.34.0 · Sourcepub fn escape_debug(&self) -> EscapeDebug<'_> ⓘ
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 · Sourcepub fn escape_default(&self) -> EscapeDefault<'_> ⓘ
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 · Sourcepub fn escape_unicode(&self) -> EscapeUnicode<'_> ⓘ
pub fn escape_unicode(&self) -> EscapeUnicode<'_> ⓘ
Returns an iterator that escapes each char in self with char::escape_unicode.
§Examples
As an iterator:
for c in "❤\n!".escape_unicode() {
print!("{c}");
}
println!();Using println! directly:
println!("{}", "❤\n!".escape_unicode());Both are equivalent to:
println!("\\u{{2764}}\\u{{a}}\\u{{21}}");Using to_string:
assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");1.98.0 · Sourcepub fn substr_range(&self, substr: &str) -> Option<Range<usize>>
pub fn substr_range(&self, substr: &str) -> Option<Range<usize>>
Returns the range that a substring points to.
Returns None if substr does not point within self.
Unlike str::find, this does not search through the string.
Instead, it uses pointer arithmetic to find where in the string
substr is derived from.
This is useful for extending str::split and similar methods.
Note that this method may return false positives (typically either
Some(0..0) or Some(self.len()..self.len())) if substr is a
zero-length str that points at the beginning or end of another,
independent, str.
§Examples
use core::range::Range;
let data = "a, b, b, a";
let mut iter = data.split(", ").map(|s| data.substr_range(s).unwrap());
assert_eq!(iter.next(), Some(Range { start: 0, end: 1 }));
assert_eq!(iter.next(), Some(Range { start: 3, end: 4 }));
assert_eq!(iter.next(), Some(Range { start: 6, end: 7 }));
assert_eq!(iter.next(), Some(Range { start: 9, end: 10 }));Sourcepub fn as_str(&self) -> &str
🔬This is a nightly-only experimental API. (str_as_str)
pub fn as_str(&self) -> &str
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 · Sourcepub fn replace<P>(&self, from: P, to: &str) -> Stringwhere
P: Pattern,
Available on non-no_global_oom_handling only.
pub fn replace<P>(&self, from: P, to: &str) -> Stringwhere
P: Pattern,
no_global_oom_handling only.Replaces all matches of a pattern with another string.
replace creates a new String, and copies the data from this string slice into it.
While doing so, it attempts to find matches of a pattern. If it finds any, it
replaces them with the replacement string slice.
§Examples
let s = "this is old";
assert_eq!("this is new", s.replace("old", "new"));
assert_eq!("than an old", s.replace("is", "an"));When the pattern doesn’t match, it returns this string slice as String:
let s = "this is old";
assert_eq!(s, s.replace("cookie monster", "little lamb"));1.16.0 · Sourcepub fn replacen<P>(&self, pat: P, to: &str, count: usize) -> Stringwhere
P: Pattern,
Available on non-no_global_oom_handling only.
pub fn replacen<P>(&self, pat: P, to: &str, count: usize) -> Stringwhere
P: Pattern,
no_global_oom_handling only.Replaces first N matches of a pattern with another string.
replacen creates a new String, and copies the data from this string slice into it.
While doing so, it attempts to find matches of a pattern. If it finds any, it
replaces them with the replacement string slice at most count times.
§Examples
let s = "foo foo 123 foo";
assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));When the pattern doesn’t match, it returns this string slice as String:
let s = "this is old";
assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));1.2.0 · Sourcepub fn to_lowercase(&self) -> String
Available on non-no_global_oom_handling only.
pub fn to_lowercase(&self) -> String
no_global_oom_handling only.Returns the lowercase equivalent of this string slice, as a new String.
‘Lowercase’ is defined according to the terms of Chapter 3 (Conformance) of the Unicode standard.
Since some characters can expand into multiple characters when changing
the case, this function returns a String instead of modifying the
parameter in-place.
Unlike char::to_lowercase(), this method fully handles the context-dependent
casing of Greek sigma. However, like that method, it does not handle locale-specific
casing, like Turkish and Azeri I/ı/İ/i. See its documentation
for more information.
§Examples
Basic usage:
let s = "HELLO WORLD";
assert_eq!("hello world", s.to_lowercase());Tricky examples, with sigma:
let sigma = "Σ";
assert_eq!("σ", sigma.to_lowercase());
// but at the end of a word, it's ς, not σ:
let odysseus = "ὈΔΥΣΣΕΎΣ";
assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
let odysseus_king_of_ithaca = "Ο ΟΔΥΣΣΈΑΣ ΒΑΣΙΛΙΆΣ ΤΗΣ ΙΘΆΚΗΣ";
assert_eq!("ο οδυσσέας βασιλιάς της ιθάκης", odysseus_king_of_ithaca.to_lowercase());Languages without case are not changed:
let new_year = "农历新年";
assert_eq!(new_year, new_year.to_lowercase());Examples found in repository?
More examples
Sourcepub fn word_to_titlecase(&self) -> String
🔬This is a nightly-only experimental API. (titlecase)Available on non-no_global_oom_handling only.
pub fn word_to_titlecase(&self) -> String
titlecase)no_global_oom_handling only.Returns the titlecase equivalent of this string slice,
which is assumed to represent a single word,
as a new String.
Essentially, this consists of uppercasing the first cased letter
(with char::to_titlecase()), and lowercasing everything that follows.
‘Titlecase’ is defined according to the terms of Chapter 3 (Conformance) of the Unicode standard.
Since some characters can expand into multiple characters when changing
the case, this function returns a String instead of modifying the
parameter in-place.
Unlike char::to_lowercase(), this method fully handles the context-dependent
casing of Greek sigma. However, like that method, it does not handle locale-specific
casing, like Turkish and Azeri I/ı/İ/i. See its documentation
for more information.
This method does not perform any kind of word segmentation.
§Examples
Basic usage:
#![feature(titlecase)]
let s = "HELLO WORLD";
assert_eq!("Hello world", s.word_to_titlecase());The first cased letter is uppercased:
#![feature(titlecase)]
let the_night_before_christmas = "'twas";
assert_eq!("'Twas", the_night_before_christmas.word_to_titlecase());Languages without case are not changed:
#![feature(titlecase)]
let new_year = "农历新年";
assert_eq!(new_year, new_year.word_to_titlecase());Georgian uppercase (“Mtavruli”) letters are not used in titlecase:
#![feature(titlecase)]
let georgian = "ერთობაშია";
assert_eq!(georgian, georgian.word_to_titlecase());No word segmentation is performed, so only the first cased letter in the whole string gets uppercased:
#![feature(titlecase)]
let blazingly_fast = "ferris and I";
assert_eq!("Ferris and i", blazingly_fast.word_to_titlecase());Tricky examples, with sigma:
#![feature(titlecase)]
let odysseus = "ὈΔΥΣΣΕΎΣ";
assert_eq!("Ὀδυσσεύς", odysseus.word_to_titlecase());
let odysseus_king_of_ithaca = "Ο ΟΔΥΣΣΈΑΣ ΒΑΣΙΛΙΆΣ ΤΗΣ ΙΘΆΚΗΣ";
assert_eq!("Ο οδυσσέας βασιλιάς της ιθάκης", odysseus_king_of_ithaca.word_to_titlecase());1.2.0 · Sourcepub fn to_uppercase(&self) -> String
Available on non-no_global_oom_handling only.
pub fn to_uppercase(&self) -> String
no_global_oom_handling only.Returns the uppercase equivalent of this string slice, as a new String.
‘Uppercase’ is defined according to the terms of Chapter 3 (Conformance) of the Unicode standard.
Since some characters can expand into multiple characters when changing
the case, this function returns a String instead of modifying the
parameter in-place.
Like char::to_uppercase() this method does not handle language-specific
casing, like Turkish and Azeri I/ı/İ/i. See that method’s documentation
for more information.
§Examples
Basic usage:
let s = "hello world";
assert_eq!("HELLO WORLD", s.to_uppercase());Scripts without case are not changed:
let new_year = "农历新年";
assert_eq!(new_year, new_year.to_uppercase());One character can become multiple:
let s = "tschüß";
assert_eq!("TSCHÜSS", s.to_uppercase());Sourcepub fn to_casefold_unnormalized(&self) -> String
🔬This is a nightly-only experimental API. (casefold)Available on non-no_global_oom_handling only.
pub fn to_casefold_unnormalized(&self) -> String
casefold)no_global_oom_handling only.Returns the case-folded equivalent of this string slice, as a new String.
Case folding is a transformation, mostly matching lowercase, that is meant to be used for case-insensitive string comparisons. Case-folded strings should not usually be exposed directly to users.
For the precise specification of case folding, see Chapter 3 (Conformance) of the Unicode standard.
Since some characters can expand into multiple characters when case folding,
this function returns a String instead of modifying the parameter in-place.
No normalization (e.g. NFC) is performed, so visually and semantically identical strings
might still casefold differently. For example, "Å" (U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE)
is considered distinct from "Å" (A followed by U+030A COMBINING RING ABOVE),
even though Unicode considers them canonically equivalent.
Like char::to_casefold_unnormalized() this method does not handle language-specific
casing, like Turkish and Azeri I/ı/İ/i. See that method’s documentation
for more information.
§Examples
Basic usage:
#![feature(casefold)]
let s0 = "HELLO";
let s1 = "Hello";
assert_eq!(s0.to_casefold_unnormalized(), s1.to_casefold_unnormalized());
assert_eq!(s0.to_casefold_unnormalized(), "hello")Scripts without case are not changed:
#![feature(casefold)]
let new_year = "农历新年";
assert_eq!(new_year, new_year.to_casefold_unnormalized());One character can become multiple:
#![feature(casefold)]
let s0 = "TSCHÜẞ";
let s1 = "TSCHÜSS";
let s2 = "tschüß";
assert_eq!(s0.to_casefold_unnormalized(), s1.to_casefold_unnormalized());
assert_eq!(s0.to_casefold_unnormalized(), s2.to_casefold_unnormalized());
assert_eq!(s0.to_casefold_unnormalized(), "tschüss");No NFC normalization is performed:
#![feature(casefold)]
// These two strings are visually and semantically identical...
let comp = "Å";
let decomp = "Å";
// ... but not codepoint-for-codepoint equal.
assert_eq!(comp, "\u{C5}");
assert_eq!(decomp, "A\u{030A}");
// Their case-foldings are likewise unequal:
assert_eq!(comp.to_casefold_unnormalized(), "\u{E5}");
assert_eq!(decomp.to_casefold_unnormalized(), "a\u{030A}");1.16.0 · Sourcepub fn repeat(&self, n: usize) -> String
Available on non-no_global_oom_handling only.
pub fn repeat(&self, n: usize) -> String
no_global_oom_handling only.Creates a new String by repeating a string n times.
§Panics
This function will panic if the capacity would overflow.
§Examples
Basic usage:
assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));A panic upon overflow:
// this will panic at runtime
let huge = "0123456789abcdef".repeat(usize::MAX);Examples found in repository?
64fn setup(mut commands: Commands, args: Res<Args>) {
65 warn!(include_str!("warning_string.txt"));
66
67 commands.spawn(Camera2d);
68 let text_string = "0123456789".repeat(10_000);
69 let text_font = TextFont {
70 font_size: FontSize::Px(4.),
71 ..Default::default()
72 };
73 let text_block = TextLayout {
74 justify: Justify::Left,
75 linebreak: LineBreak::AnyCharacter,
76 };
77
78 if !args.no_ui {
79 commands
80 .spawn(Node {
81 width: percent(100),
82 align_items: AlignItems::Center,
83 justify_content: JustifyContent::Center,
84 ..default()
85 })
86 .with_children(|commands| {
87 commands
88 .spawn(Node {
89 width: px(1000),
90 ..Default::default()
91 })
92 .with_child((Text(text_string.clone()), text_font.clone(), text_block));
93 });
94 }
95
96 if !args.no_text2d {
97 commands.spawn((
98 Text2d::new(text_string),
99 text_font.clone(),
100 TextColor(RED.into()),
101 bevy::sprite::Anchor::CENTER,
102 TextBounds::new_horizontal(1000.),
103 text_block,
104 ));
105 }
106}More examples
34fn spawn(mut commands: Commands, asset_server: Res<AssetServer>) {
35 warn!(include_str!("warning_string.txt"));
36
37 commands.spawn(Camera2d);
38
39 let make_spans = |i| {
40 [
41 (
42 TextSpan("text".repeat(i)),
43 TextFont {
44 font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
45 font_size: FontSize::Px((4 + i % 10) as f32),
46 ..Default::default()
47 },
48 TextColor(BLUE.into()),
49 ),
50 (
51 TextSpan("pipeline".repeat(i)),
52 TextFont {
53 font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
54 font_size: FontSize::Px((4 + i % 11) as f32),
55 ..default()
56 },
57 TextColor(YELLOW.into()),
58 ),
59 ]
60 };
61
62 let spans = (1..50).flat_map(|i| make_spans(i).into_iter());
63
64 commands
65 .spawn((
66 Text2d::default(),
67 TextLayout {
68 justify: Justify::Center,
69 linebreak: LineBreak::AnyCharacter,
70 },
71 TextBounds::default(),
72 ))
73 .with_children(|p| {
74 for span in spans {
75 p.spawn(span);
76 }
77 });
78}1.23.0 · Sourcepub fn to_ascii_uppercase(&self) -> String
Available on non-no_global_oom_handling only.
pub fn to_ascii_uppercase(&self) -> String
no_global_oom_handling only.Returns a copy of this string where each character is mapped to its ASCII upper case equivalent.
ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged.
To uppercase the value in-place, use make_ascii_uppercase.
To uppercase ASCII characters in addition to non-ASCII characters, use
to_uppercase.
§Examples
let s = "Grüße, Jürgen ❤";
assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());1.23.0 · Sourcepub fn to_ascii_lowercase(&self) -> String
Available on non-no_global_oom_handling only.
pub fn to_ascii_lowercase(&self) -> String
no_global_oom_handling only.Returns a copy of this string where each character is mapped to its ASCII lower case equivalent.
ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but non-ASCII letters are unchanged.
To lowercase the value in-place, use make_ascii_lowercase.
To lowercase ASCII characters in addition to non-ASCII characters, use
to_lowercase.
§Examples
let s = "Grüße, Jürgen ❤";
assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());Trait Implementations§
Source§impl Component for Text
Required Components: Node, TextLayout, TextFont, TextColor, LineHeight, LetterSpacing, TextNodeFlags, ContentSize, FontHinting.
impl Component for Text
Required Components: Node, TextLayout, TextFont, TextColor, LineHeight, LetterSpacing, TextNodeFlags, ContentSize, FontHinting.
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
const STORAGE_TYPE: StorageType = bevy_ecs::component::StorageType::Table
Source§type Mutability = Mutable
type Mutability = Mutable
Component<Mutability = Mutable>,
while immutable components will instead have Component<Mutability = Immutable>. Read moreSource§fn register_required_components(
_requiree: ComponentId,
required_components: &mut RequiredComponentsRegistrator<'_, '_>,
)
fn register_required_components( _requiree: ComponentId, required_components: &mut RequiredComponentsRegistrator<'_, '_>, )
Source§fn clone_behavior() -> ComponentCloneBehavior
fn clone_behavior() -> ComponentCloneBehavior
Source§fn relationship_accessor() -> Option<ComponentRelationshipAccessor<Text>>
fn relationship_accessor() -> Option<ComponentRelationshipAccessor<Text>>
ComponentRelationshipAccessor required for working with relationships in dynamic contexts. Read moreSource§fn on_add() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_add() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn on_insert() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_insert() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn on_discard() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_discard() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn on_remove() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_remove() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn on_despawn() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
fn on_despawn() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>
Source§fn map_entities<E>(_this: &mut Self, _mapper: &mut E)where
E: EntityMapper,
fn map_entities<E>(_this: &mut Self, _mapper: &mut E)where
E: EntityMapper,
EntityMapper. This is used to remap entities in contexts like scenes and entity cloning.
When deriving Component, this is populated by annotating fields containing entities with #[entities] Read moreSource§impl FromReflect for Text
impl FromReflect for Text
Source§fn from_reflect(reflect: &(dyn PartialReflect + 'static)) -> Option<Text>
fn from_reflect(reflect: &(dyn PartialReflect + 'static)) -> Option<Text>
Self from a reflected value.Source§fn take_from_reflect(
reflect: Box<dyn PartialReflect>,
) -> Result<Self, Box<dyn PartialReflect>>
fn take_from_reflect( reflect: Box<dyn PartialReflect>, ) -> Result<Self, Box<dyn PartialReflect>>
Self using,
constructing the value using from_reflect if that fails. Read moreSource§impl GetTypeRegistration for Text
impl GetTypeRegistration for Text
Source§fn get_type_registration() -> TypeRegistration
fn get_type_registration() -> TypeRegistration
TypeRegistration for this type.Source§fn register_type_dependencies(registry: &mut TypeRegistry)
fn register_type_dependencies(registry: &mut TypeRegistry)
Source§impl IntoReturn for Text
impl IntoReturn for Text
Source§impl PartialReflect for Text
impl PartialReflect for Text
Source§fn get_represented_type_info(&self) -> Option<&'static TypeInfo>
fn get_represented_type_info(&self) -> Option<&'static TypeInfo>
Source§fn try_apply(
&mut self,
value: &(dyn PartialReflect + 'static),
) -> Result<(), ApplyError>
fn try_apply( &mut self, value: &(dyn PartialReflect + 'static), ) -> Result<(), ApplyError>
Source§fn reflect_kind(&self) -> ReflectKind
fn reflect_kind(&self) -> ReflectKind
Source§fn reflect_ref(&self) -> ReflectRef<'_>
fn reflect_ref(&self) -> ReflectRef<'_>
Source§fn reflect_mut(&mut self) -> ReflectMut<'_>
fn reflect_mut(&mut self) -> ReflectMut<'_>
Source§fn reflect_owned(self: Box<Text>) -> ReflectOwned
fn reflect_owned(self: Box<Text>) -> ReflectOwned
Source§fn try_into_reflect(
self: Box<Text>,
) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>>
fn try_into_reflect( self: Box<Text>, ) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>>
Source§fn try_as_reflect(&self) -> Option<&(dyn Reflect + 'static)>
fn try_as_reflect(&self) -> Option<&(dyn Reflect + 'static)>
Source§fn try_as_reflect_mut(&mut self) -> Option<&mut (dyn Reflect + 'static)>
fn try_as_reflect_mut(&mut self) -> Option<&mut (dyn Reflect + 'static)>
Source§fn into_partial_reflect(self: Box<Text>) -> Box<dyn PartialReflect>
fn into_partial_reflect(self: Box<Text>) -> Box<dyn PartialReflect>
Source§fn as_partial_reflect(&self) -> &(dyn PartialReflect + 'static)
fn as_partial_reflect(&self) -> &(dyn PartialReflect + 'static)
Source§fn as_partial_reflect_mut(&mut self) -> &mut (dyn PartialReflect + 'static)
fn as_partial_reflect_mut(&mut self) -> &mut (dyn PartialReflect + 'static)
Source§fn reflect_partial_eq(
&self,
value: &(dyn PartialReflect + 'static),
) -> Option<bool>
fn reflect_partial_eq( &self, value: &(dyn PartialReflect + 'static), ) -> Option<bool>
Source§fn reflect_partial_cmp(
&self,
value: &(dyn PartialReflect + 'static),
) -> Option<Ordering>
fn reflect_partial_cmp( &self, value: &(dyn PartialReflect + 'static), ) -> Option<Ordering>
Source§fn debug(&self, f: &mut Formatter<'_>) -> Result<(), Error>
fn debug(&self, f: &mut Formatter<'_>) -> Result<(), Error>
Source§fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError>
fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError>
Self using reflection. Read moreSource§fn apply(&mut self, value: &(dyn PartialReflect + 'static))
fn apply(&mut self, value: &(dyn PartialReflect + 'static))
Source§fn to_dynamic(&self) -> Box<dyn PartialReflect>
fn to_dynamic(&self) -> Box<dyn PartialReflect>
Source§fn reflect_clone_and_take<T>(&self) -> Result<T, ReflectCloneError>
fn reflect_clone_and_take<T>(&self) -> Result<T, ReflectCloneError>
PartialReflect, combines reflect_clone and
take in a useful fashion, automatically constructing an appropriate
ReflectCloneError if the downcast fails.Source§fn reflect_hash(&self) -> Option<u64>
fn reflect_hash(&self) -> Option<u64>
Source§fn is_dynamic(&self) -> bool
fn is_dynamic(&self) -> bool
Source§impl Reflect for Text
impl Reflect for Text
Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut dyn Any. Read moreSource§fn into_reflect(self: Box<Text>) -> Box<dyn Reflect>
fn into_reflect(self: Box<Text>) -> Box<dyn Reflect>
Source§fn as_reflect(&self) -> &(dyn Reflect + 'static)
fn as_reflect(&self) -> &(dyn Reflect + 'static)
Source§fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)
fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)
impl StructuralPartialEq for Text
Source§impl TextSection for Text
impl TextSection for Text
Source§impl TupleStruct for Text
impl TupleStruct for Text
Source§fn field(&self, index: usize) -> Option<&(dyn PartialReflect + 'static)>
fn field(&self, index: usize) -> Option<&(dyn PartialReflect + 'static)>
index as a
&dyn Reflect.Source§fn field_mut(
&mut self,
index: usize,
) -> Option<&mut (dyn PartialReflect + 'static)>
fn field_mut( &mut self, index: usize, ) -> Option<&mut (dyn PartialReflect + 'static)>
index
as a &mut dyn Reflect.Source§fn iter_fields(&self) -> TupleStructFieldIter<'_> ⓘ
fn iter_fields(&self) -> TupleStructFieldIter<'_> ⓘ
Source§fn to_dynamic_tuple_struct(&self) -> DynamicTupleStruct
fn to_dynamic_tuple_struct(&self) -> DynamicTupleStruct
DynamicTupleStruct from this tuple struct.Source§fn get_represented_tuple_struct_info(&self) -> Option<&'static TupleStructInfo>
fn get_represented_tuple_struct_info(&self) -> Option<&'static TupleStructInfo>
None if TypeInfo is not available.Source§impl TypePath for Text
impl TypePath for Text
Source§fn type_path() -> &'static str
fn type_path() -> &'static str
Source§fn short_type_path() -> &'static str
fn short_type_path() -> &'static str
Source§fn type_ident() -> Option<&'static str>
fn type_ident() -> Option<&'static str>
Source§fn crate_name() -> Option<&'static str>
fn crate_name() -> Option<&'static str>
Auto Trait Implementations§
impl Freeze for Text
impl RefUnwindSafe for Text
impl Send for Text
impl Sync for Text
impl Unpin for Text
impl UnsafeUnpin for Text
impl UnwindSafe for Text
Blanket Implementations§
Source§impl<T, U> AsBindGroupShaderType<U> for T
impl<T, U> AsBindGroupShaderType<U> for T
Source§fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U
T ShaderType for self. When used in AsBindGroup
derives, it is safe to assume that all images in self exist.Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<T> Brush for T
Source§impl<C> Bundle for Cwhere
C: Component,
impl<C> Bundle for Cwhere
C: Component,
fn component_ids( components: &mut ComponentsRegistrator<'_>, ) -> impl Iterator<Item = ComponentId> + use<C>
Source§fn get_component_ids(
components: &Components,
) -> impl Iterator<Item = Option<ComponentId>>
fn get_component_ids( components: &Components, ) -> impl Iterator<Item = Option<ComponentId>>
Source§impl<C> BundleFromComponents for Cwhere
C: Component,
impl<C> BundleFromComponents for Cwhere
C: Component,
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> ConditionalSend for Twhere
T: Send,
Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be
downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.Source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further
downcast into Rc<ConcreteType> where ConcreteType implements Trait.Source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &Any’s vtable from &Trait’s.Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &mut Any’s vtable from &mut Trait’s.Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can
then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.Source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be
further downcast into Rc<ConcreteType> where ConcreteType implements Trait.Source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &Any’s vtable from &Trait’s.Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &mut Any’s vtable from &mut Trait’s.Source§impl<T> DowncastSend for T
impl<T> DowncastSend for T
Source§impl<T> DowncastSync for T
impl<T> DowncastSync for T
impl<S, T> Duplex<S> for Twhere
T: FromSample<S> + ToSample<S>,
Source§impl<C> DynamicBundle for Cwhere
C: Component,
impl<C> DynamicBundle for Cwhere
C: Component,
Source§unsafe fn get_components(
ptr: MovingPtr<'_, C>,
func: &mut impl FnMut(StorageType, OwningPtr<'_>),
) -> <C as DynamicBundle>::Effect
unsafe fn get_components( ptr: MovingPtr<'_, C>, func: &mut impl FnMut(StorageType, OwningPtr<'_>), ) -> <C as DynamicBundle>::Effect
Source§unsafe fn apply_effect(
_ptr: MovingPtr<'_, MaybeUninit<C>>,
_entity: &mut EntityWorldMut<'_>,
)
unsafe fn apply_effect( _ptr: MovingPtr<'_, MaybeUninit<C>>, _entity: &mut EntityWorldMut<'_>, )
Source§impl<T> DynamicTypePath for Twhere
T: TypePath,
impl<T> DynamicTypePath for Twhere
T: TypePath,
Source§fn reflect_type_path(&self) -> &str
fn reflect_type_path(&self) -> &str
TypePath::type_path.Source§fn reflect_short_type_path(&self) -> &str
fn reflect_short_type_path(&self) -> &str
Source§fn reflect_type_ident(&self) -> Option<&str>
fn reflect_type_ident(&self) -> Option<&str>
TypePath::type_ident.Source§fn reflect_crate_name(&self) -> Option<&str>
fn reflect_crate_name(&self) -> Option<&str>
TypePath::crate_name.Source§fn reflect_module_path(&self) -> Option<&str>
fn reflect_module_path(&self) -> Option<&str>
Source§impl<T> DynamicTyped for Twhere
T: Typed,
impl<T> DynamicTyped for Twhere
T: Typed,
Source§fn reflect_type_info(&self) -> &'static TypeInfo
fn reflect_type_info(&self) -> &'static TypeInfo
Typed::type_info.Source§impl<T> ErasedBundleTemplate for T
impl<T> ErasedBundleTemplate for T
Source§unsafe fn apply(
&self,
context: &mut TemplateContext<'_, '_>,
) -> Result<(), BevyError>
unsafe fn apply( &self, context: &mut TemplateContext<'_, '_>, ) -> Result<(), BevyError>
entity. Read moreSource§fn clone_template(&self) -> Box<dyn ErasedBundleTemplate>
fn clone_template(&self) -> Box<dyn ErasedBundleTemplate>
Clone.Source§impl<T> ErasedComponentTemplate for T
impl<T> ErasedComponentTemplate for T
Source§unsafe fn apply(
&self,
context: &mut TemplateContext<'_, '_>,
bundle_writer: &mut BundleWriter<'_>,
) -> Result<(), BevyError>
unsafe fn apply( &self, context: &mut TemplateContext<'_, '_>, bundle_writer: &mut BundleWriter<'_>, ) -> Result<(), BevyError>
entity. Read moreSource§fn clone_template(&self) -> Box<dyn ErasedComponentTemplate>
fn clone_template(&self) -> Box<dyn ErasedComponentTemplate>
Clone.impl<T> ErasedDestructor for Twhere
T: 'static,
Source§impl<T> FmtForward for T
impl<T> FmtForward for T
Source§fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
self to use its Binary implementation when Debug-formatted.Source§fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
self to use its Display implementation when
Debug-formatted.Source§fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
self to use its LowerExp implementation when
Debug-formatted.Source§fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
self to use its LowerHex implementation when
Debug-formatted.Source§fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
self to use its Octal implementation when Debug-formatted.Source§fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
self to use its Pointer implementation when
Debug-formatted.Source§fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
self to use its UpperExp implementation when
Debug-formatted.Source§fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
self to use its UpperHex implementation when
Debug-formatted.Source§impl<S> FromSample<S> for S
impl<S> FromSample<S> for S
fn from_sample_(s: S) -> S
Source§impl<T> FromTemplate for T
impl<T> FromTemplate for T
Source§impl<T> FromWorld for Twhere
T: Default,
impl<T> FromWorld for Twhere
T: Default,
Source§fn from_world(_world: &mut World) -> T
fn from_world(_world: &mut World) -> T
Creates Self using default().
Source§impl<T> GetPath for T
impl<T> GetPath for T
Source§fn reflect_path<'p>(
&self,
path: impl ReflectPath<'p>,
) -> Result<&(dyn PartialReflect + 'static), ReflectPathError<'p>>
fn reflect_path<'p>( &self, path: impl ReflectPath<'p>, ) -> Result<&(dyn PartialReflect + 'static), ReflectPathError<'p>>
path. Read moreSource§fn reflect_path_mut<'p>(
&mut self,
path: impl ReflectPath<'p>,
) -> Result<&mut (dyn PartialReflect + 'static), ReflectPathError<'p>>
fn reflect_path_mut<'p>( &mut self, path: impl ReflectPath<'p>, ) -> Result<&mut (dyn PartialReflect + 'static), ReflectPathError<'p>>
path. Read moreSource§fn path<'p, T>(
&self,
path: impl ReflectPath<'p>,
) -> Result<&T, ReflectPathError<'p>>where
T: Reflect,
fn path<'p, T>(
&self,
path: impl ReflectPath<'p>,
) -> Result<&T, ReflectPathError<'p>>where
T: Reflect,
path. Read moreSource§fn path_mut<'p, T>(
&mut self,
path: impl ReflectPath<'p>,
) -> Result<&mut T, ReflectPathError<'p>>where
T: Reflect,
fn path_mut<'p, T>(
&mut self,
path: impl ReflectPath<'p>,
) -> Result<&mut T, ReflectPathError<'p>>where
T: Reflect,
path. Read moreSource§impl<S> GetTupleStructField for Swhere
S: TupleStruct,
impl<S> GetTupleStructField for Swhere
S: TupleStruct,
Source§impl<T, W> HasTypeWitness<W> for Twhere
W: MakeTypeWitness<Arg = T>,
T: ?Sized,
impl<T, W> HasTypeWitness<W> for Twhere
W: MakeTypeWitness<Arg = T>,
T: ?Sized,
impl<T> HitDataExtra for T
Source§impl<T> Identity for Twhere
T: ?Sized,
impl<T> Identity for Twhere
T: ?Sized,
Source§impl<T> InitializeFromFunction<T> for T
impl<T> InitializeFromFunction<T> for T
Source§fn initialize_from_function(f: fn() -> T) -> T
fn initialize_from_function(f: fn() -> T) -> T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§impl<T> IntoResult<T> for T
impl<T> IntoResult<T> for T
Source§fn into_result(self) -> Result<T, RunSystemError>
fn into_result(self) -> Result<T, RunSystemError>
Source§impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
fn into_sample(self) -> T
Source§impl<G> PatchFromTemplate for Gwhere
G: FromTemplate,
impl<G> PatchFromTemplate for Gwhere
G: FromTemplate,
Source§fn patch<F>(func: F) -> TemplatePatch<F, <G as PatchFromTemplate>::Template>
fn patch<F>(func: F) -> TemplatePatch<F, <G as PatchFromTemplate>::Template>
func, and turns it into a TemplatePatch.Source§impl<T> PatchTemplate for Twhere
T: Template,
impl<T> PatchTemplate for Twhere
T: Template,
Source§fn patch_template<F>(func: F) -> TemplatePatch<F, T>
fn patch_template<F>(func: F) -> TemplatePatch<F, T>
Source§impl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
Source§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
Source§fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
self and passes that borrow into the pipe function. Read moreSource§fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
self and passes that borrow into the pipe function. Read moreSource§fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
Source§fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R,
) -> R
fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
Source§fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
self, then passes self.as_ref() into the pipe function.Source§fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
self, then passes self.as_mut() into the pipe
function.Source§fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
self, then passes self.deref() into the pipe function.impl<T> Read<Exclusive, BecauseExclusive> for Twhere
T: ?Sized,
Source§impl<R, P> ReadPrimitive<R> for P
impl<R, P> ReadPrimitive<R> for P
Source§fn read_from_little_endian(read: &mut R) -> Result<Self, Error>
fn read_from_little_endian(read: &mut R) -> Result<Self, Error>
ReadEndian::read_from_little_endian().impl<T> Reflectable for T
impl<T> Settings for T
Source§impl<T> Source for T
impl<T> Source for T
Source§type Slice<'a> = <<T as Deref>::Target as Source>::Slice<'a>
where
T: 'a
type Slice<'a> = <<T as Deref>::Target as Source>::Slice<'a> where T: 'a
Source can be sliced into.Source§fn read<'a, Chunk>(&'a self, offset: usize) -> Option<Chunk>where
Chunk: Chunk<'a>,
fn read<'a, Chunk>(&'a self, offset: usize) -> Option<Chunk>where
Chunk: Chunk<'a>,
None when reading
out of bounds would occur. Read moreSource§fn slice(&self, range: Range<usize>) -> Option<<T as Source>::Slice<'_>>
fn slice(&self, range: Range<usize>) -> Option<<T as Source>::Slice<'_>>
slice::get(range). Read moreSource§unsafe fn slice_unchecked(
&self,
range: Range<usize>,
) -> <T as Source>::Slice<'_>
unsafe fn slice_unchecked( &self, range: Range<usize>, ) -> <T as Source>::Slice<'_>
forbid_unsafe only.slice::get_unchecked(range). Read moreSource§fn is_boundary(&self, index: usize) -> bool
fn is_boundary(&self, index: usize) -> bool
Source§impl<Ret> SpawnIfAsync<(), Ret> for Ret
impl<Ret> SpawnIfAsync<(), Ret> for Ret
Source§impl<T, O> SuperFrom<T> for Owhere
O: From<T>,
impl<T, O> SuperFrom<T> for Owhere
O: From<T>,
Source§fn super_from(input: T) -> O
fn super_from(input: T) -> O
Source§impl<T, O, M> SuperInto<O, M> for Twhere
O: SuperFrom<T, M>,
impl<T, O, M> SuperInto<O, M> for Twhere
O: SuperFrom<T, M>,
Source§fn super_into(self) -> O
fn super_into(self) -> O
Source§impl<T> Tap for T
impl<T> Tap for T
Source§fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
Borrow<B> of a value. Read moreSource§fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
BorrowMut<B> of a value. Read moreSource§fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
AsRef<R> view of a value. Read moreSource§fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
AsMut<R> view of a value. Read moreSource§fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
Deref::Target of a value. Read moreSource§fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
Deref::Target of a value. Read moreSource§fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
.tap() only in debug builds, and is erased in release builds.Source§fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
.tap_mut() only in debug builds, and is erased in release
builds.Source§fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
.tap_borrow() only in debug builds, and is erased in release
builds.Source§fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
.tap_borrow_mut() only in debug builds, and is erased in release
builds.Source§fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
.tap_ref() only in debug builds, and is erased in release
builds.Source§fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
.tap_ref_mut() only in debug builds, and is erased in release
builds.Source§fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
.tap_deref() only in debug builds, and is erased in release
builds.Source§impl<T> Template for T
impl<T> Template for T
Source§fn build_template(
&self,
_context: &mut TemplateContext<'_, '_>,
) -> Result<<T as Template>::Output, BevyError>
fn build_template( &self, _context: &mut TemplateContext<'_, '_>, ) -> Result<<T as Template>::Output, BevyError>
entity context to produce a Template::Output.Source§fn clone_template(&self) -> T
fn clone_template(&self) -> T
Clone.