pub struct String { /* private fields */ }Expand description
A UTF-8–encoded, growable string.
String is the most common string type. It has ownership over the contents
of the string, stored in a heap-allocated buffer (see Representation).
It is closely related to its borrowed counterpart, the primitive str.
§Examples
You can create a String from a literal string with String::from:
let hello = String::from("Hello, world!");You can append a char to a String with the push method, and
append a &str with the push_str method:
let mut hello = String::from("Hello, ");
hello.push('w');
hello.push_str("orld!");If you have a vector of UTF-8 bytes, you can create a String from it with
the from_utf8 method:
// some bytes, in a vector
let sparkle_heart = vec![240, 159, 146, 150];
// We know these bytes are valid, so we'll use `unwrap()`.
let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
assert_eq!("💖", sparkle_heart);§UTF-8
Strings are always valid UTF-8. If you need a non-UTF-8 string, consider
OsString. It is similar, but without the UTF-8 constraint. Because UTF-8
is a variable width encoding, Strings are typically smaller than an array of
the same chars:
// `s` is ASCII which represents each `char` as one byte
let s = "hello";
assert_eq!(s.len(), 5);
// A `char` array with the same contents would be longer because
// every `char` is four bytes
let s = ['h', 'e', 'l', 'l', 'o'];
let size: usize = s.into_iter().map(|c| size_of_val(&c)).sum();
assert_eq!(size, 20);
// However, for non-ASCII strings, the difference will be smaller
// and sometimes they are the same
let s = "💖💖💖💖💖";
assert_eq!(s.len(), 20);
let s = ['💖', '💖', '💖', '💖', '💖'];
let size: usize = s.into_iter().map(|c| size_of_val(&c)).sum();
assert_eq!(size, 20);This raises interesting questions as to how s[i] should work.
What should i be here? Several options include byte indices and
char indices but, because of UTF-8 encoding, only byte indices
would provide constant time indexing. Getting the ith char, for
example, is available using chars:
let s = "hello";
let third_character = s.chars().nth(2);
assert_eq!(third_character, Some('l'));
let s = "💖💖💖💖💖";
let third_character = s.chars().nth(2);
assert_eq!(third_character, Some('💖'));Next, what should s[i] return? Because indexing returns a reference
to underlying data it could be &u8, &[u8], or something similar.
Since we’re only providing one index, &u8 makes the most sense but that
might not be what the user expects and can be explicitly achieved with
as_bytes():
// The first byte is 104 - the byte value of `'h'`
let s = "hello";
assert_eq!(s.as_bytes()[0], 104);
// or
assert_eq!(s.as_bytes()[0], b'h');
// The first byte is 240 which isn't obviously useful
let s = "💖💖💖💖💖";
assert_eq!(s.as_bytes()[0], 240);Due to these ambiguities/restrictions, indexing with a usize is simply
forbidden:
let s = "hello";
// The following will not compile!
println!("The first letter of s is {}", s[0]);It is more clear, however, how &s[i..j] should work (that is,
indexing with a range). It should accept byte indices (to be constant-time)
and return a &str which is UTF-8 encoded. This is also called “string slicing”.
Note this will panic if the byte indices provided are not character
boundaries - see is_char_boundary for more details. See the implementations
for SliceIndex<str> for more details on string slicing. For a non-panicking
version of string slicing, see get.
The bytes and chars methods return iterators over the bytes and
codepoints of the string, respectively. To iterate over codepoints along
with byte indices, use char_indices.
§Deref
String implements Deref<Target = str>, and so inherits all of str’s
methods. In addition, this means that you can pass a String to a
function which takes a &str by using an ampersand (&):
fn takes_str(s: &str) { }
let s = String::from("Hello");
takes_str(&s);This will create a &str from the String and pass it in. This
conversion is very inexpensive, and so generally, functions will accept
&strs as arguments unless they need a String for some specific
reason.
In certain cases Rust doesn’t have enough information to make this
conversion, known as Deref coercion. In the following example a string
slice &'a str implements the trait TraitExample, and the function
example_func takes anything that implements the trait. In this case Rust
would need to make two implicit conversions, which Rust doesn’t have the
means to do. For that reason, the following example will not compile.
trait TraitExample {}
impl<'a> TraitExample for &'a str {}
fn example_func<A: TraitExample>(example_arg: A) {}
let example_string = String::from("example_string");
example_func(&example_string);There are two options that would work instead. The first would be to
change the line example_func(&example_string); to
example_func(example_string.as_str());, using the method as_str()
to explicitly extract the string slice containing the string. The second
way changes example_func(&example_string); to
example_func(&*example_string);. In this case we are dereferencing a
String to a str, then referencing the str back to
&str. The second way is more idiomatic, however both work to do the
conversion explicitly rather than relying on the implicit conversion.
§Representation
A String is made up of three components: a pointer to some bytes, a
length, and a capacity. The pointer points to the internal buffer which String
uses to store its data. The length is the number of bytes currently stored
in the buffer, and the capacity is the size of the buffer in bytes. As such,
the length will always be less than or equal to the capacity.
This buffer is always stored on the heap.
You can look at these with the as_ptr, len, and capacity
methods:
let story = String::from("Once upon a time...");
// Deconstruct the String into parts.
let (ptr, len, capacity) = story.into_raw_parts();
// story has nineteen bytes
assert_eq!(19, len);
// We can re-build a String out of ptr, len, and capacity. This is all
// unsafe because we are responsible for making sure the components are
// valid:
let s = unsafe { String::from_raw_parts(ptr, len, capacity) } ;
assert_eq!(String::from("Once upon a time..."), s);If a String has enough capacity, adding elements to it will not
re-allocate. For example, consider this program:
let mut s = String::new();
println!("{}", s.capacity());
for _ in 0..5 {
s.push_str("hello");
println!("{}", s.capacity());
}This will output the following:
0
8
16
16
32
32At first, we have no memory allocated at all, but as we append to the
string, it increases its capacity appropriately. If we instead use the
with_capacity method to allocate the correct capacity initially:
let mut s = String::with_capacity(25);
println!("{}", s.capacity());
for _ in 0..5 {
s.push_str("hello");
println!("{}", s.capacity());
}We end up with a different output:
25
25
25
25
25
25Here, there’s no need to allocate more memory inside the loop.
Implementations§
Source§impl String
impl String
1.0.0 (const: 1.39.0) · Sourcepub const fn new() -> String
pub const fn new() -> String
Creates a new empty String.
Given that the String is empty, this will not allocate any initial
buffer. While that means that this initial operation is very
inexpensive, it may cause excessive allocation later when you add
data. If you have an idea of how much data the String will hold,
consider the with_capacity method to prevent excessive
re-allocation.
§Examples
let s = String::new();Examples found in repository?
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}78 fn debug_relationships(
79 // Not all of our entities are targeted by something, so we use `Option` in our query to handle this case.
80 relations_query: Query<(&Name, &Targeting, Option<&TargetedBy>)>,
81 name_query: Query<&Name>,
82 ) {
83 let mut relationships = String::new();
84
85 for (name, targeting, maybe_targeted_by) in relations_query.iter() {
86 let targeting_name = name_query.get(targeting.0).unwrap();
87 let targeted_by_string = if let Some(targeted_by) = maybe_targeted_by {
88 let mut vec_of_names = Vec::<&Name>::new();
89
90 for entity in targeted_by.iter() {
91 let name = name_query.get(entity).unwrap();
92 vec_of_names.push(name);
93 }
94
95 // Convert this to a nice string for printing.
96 let vec_of_str: Vec<&str> = vec_of_names.iter().map(|name| name.as_str()).collect();
97 vec_of_str.join(", ")
98 } else {
99 "nobody".to_string()
100 };
101
102 relationships.push_str(&format!(
103 "{name} is targeting {targeting_name}, and is targeted by {targeted_by_string}\n",
104 ));
105 }
106
107 println!("{relationships}");
108 }488fn update_status_text(
489 saved_indirect_parameters: Res<SavedIndirectParameters>,
490 mut texts: Query<&mut Text>,
491 meshes: Query<Entity, With<Mesh3d>>,
492 app_status: Res<AppStatus>,
493) {
494 // How many meshes are in the scene?
495 let total_mesh_count = meshes.iter().count();
496
497 // Sample the rendered object count. Note that we don't synchronize beyond
498 // locking the data and therefore this will value will generally at least
499 // one frame behind. This is fine; this app is just a demonstration after
500 // all.
501 let (
502 rendered_object_count,
503 occlusion_culling_supported,
504 occlusion_culling_introspection_supported,
505 ): (u32, bool, bool) = {
506 let saved_indirect_parameters = saved_indirect_parameters.lock().unwrap();
507 let Some(saved_indirect_parameters) = saved_indirect_parameters.as_ref() else {
508 // Bail out early if the resource isn't initialized yet.
509 return;
510 };
511 (
512 saved_indirect_parameters
513 .data
514 .iter()
515 .take(saved_indirect_parameters.count as usize)
516 .map(|indirect_parameters| indirect_parameters.instance_count)
517 .sum(),
518 saved_indirect_parameters.occlusion_culling_supported,
519 saved_indirect_parameters.occlusion_culling_introspection_supported,
520 )
521 };
522
523 // Change the text.
524 for mut text in &mut texts {
525 text.0 = String::new();
526 if !occlusion_culling_supported {
527 text.0
528 .push_str("Occlusion culling not supported on this platform");
529 continue;
530 }
531
532 let _ = writeln!(
533 &mut text.0,
534 "Occlusion culling {} (Press Space to toggle)",
535 if app_status.occlusion_culling {
536 "ON"
537 } else {
538 "OFF"
539 },
540 );
541
542 if !occlusion_culling_introspection_supported {
543 continue;
544 }
545
546 let _ = write!(
547 &mut text.0,
548 "{rendered_object_count}/{total_mesh_count} meshes rendered"
549 );
550 }
551}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 with_capacity(capacity: usize) -> String
Available on non-no_global_oom_handling only.
pub fn with_capacity(capacity: usize) -> String
no_global_oom_handling only.Creates a new empty String with at least the specified capacity.
Strings have an internal buffer to hold their data. The capacity is
the length of that buffer, and can be queried with the capacity
method. This method creates an empty String, but one with an initial
buffer that can hold at least capacity bytes. This is useful when you
may be appending a bunch of data to the String, reducing the number of
reallocations it needs to do.
If the given capacity is 0, no allocation will occur, and this method
is identical to the new method.
§Panics
Panics if the capacity exceeds isize::MAX bytes.
§Examples
let mut s = String::with_capacity(10);
// The String contains no chars, even though it has capacity for more
assert_eq!(s.len(), 0);
// These are all done without reallocating...
let cap = s.capacity();
for _ in 0..10 {
s.push('a');
}
assert_eq!(s.capacity(), cap);
// ...but this may make the string reallocate
s.push('a');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}Sourcepub fn try_with_capacity(capacity: usize) -> Result<String, TryReserveError>
🔬This is a nightly-only experimental API. (try_with_capacity)
pub fn try_with_capacity(capacity: usize) -> Result<String, TryReserveError>
try_with_capacity)1.0.0 · Sourcepub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error>
pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error>
Converts a vector of bytes to a String.
A string (String) is made of bytes (u8), and a vector of bytes
(Vec<u8>) is made of bytes, so this function converts between the
two. Not all byte slices are valid Strings, however: String
requires that it is valid UTF-8. from_utf8() checks to ensure that
the bytes are valid UTF-8, and then does the conversion.
If you are sure that the byte slice is valid UTF-8, and you don’t want
to incur the overhead of the validity check, there is an unsafe version
of this function, from_utf8_unchecked, which has the same behavior
but skips the check.
This method will take care to not copy the vector, for efficiency’s sake.
If you need a &str instead of a String, consider
str::from_utf8.
The inverse of this method is into_bytes.
§Errors
Returns Err if the slice is not UTF-8 with a description as to why the
provided bytes are not UTF-8. The vector you moved in is also included.
§Examples
Basic usage:
// some bytes, in a vector
let sparkle_heart = vec![240, 159, 146, 150];
// We know these bytes are valid, so we'll use `unwrap()`.
let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();
assert_eq!("💖", sparkle_heart);Incorrect bytes:
// some invalid bytes, in a vector
let sparkle_heart = vec![0, 159, 146, 150];
assert!(String::from_utf8(sparkle_heart).is_err());See the docs for FromUtf8Error for more details on what you can do
with this error.
Examples found in repository?
84 async fn load(
85 &self,
86 reader: &mut dyn Reader,
87 settings: &TextSettings,
88 _load_context: &mut LoadContext<'_>,
89 ) -> Result<Text, Self::Error> {
90 let mut bytes = Vec::new();
91 reader.read_to_end(&mut bytes).await?;
92 let value = if let Some(ref text) = settings.text_override {
93 text.clone()
94 } else {
95 String::from_utf8(bytes).unwrap()
96 };
97 Ok(Text(value))
98 }1.0.0 · Sourcepub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str>
Available on non-no_global_oom_handling only.
pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str>
no_global_oom_handling only.Converts a slice of bytes to a string, including invalid characters.
Strings are made of bytes (u8), and a slice of bytes
(&[u8]) is made of bytes, so this function converts
between the two. Not all byte slices are valid strings, however: strings
are required to be valid UTF-8. During this conversion,
from_utf8_lossy() will replace any invalid UTF-8 sequences with
U+FFFD REPLACEMENT CHARACTER, which looks like this: �
If you are sure that the byte slice is valid UTF-8, and you don’t want
to incur the overhead of the conversion, there is an unsafe version
of this function, from_utf8_unchecked, which has the same behavior
but skips the checks.
This function returns a Cow<'a, str>. If our byte slice is invalid
UTF-8, then we need to insert the replacement characters, which will
change the size of the string, and hence, require a String. But if
it’s already valid UTF-8, we don’t need a new allocation. This return
type allows us to handle both cases.
§Examples
Basic usage:
// some bytes, in a vector
let sparkle_heart = vec![240, 159, 146, 150];
let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);
assert_eq!("💖", sparkle_heart);Incorrect bytes:
// some invalid bytes
let input = b"Hello \xF0\x90\x80World";
let output = String::from_utf8_lossy(input);
assert_eq!("Hello �World", output);1.99.0 · Sourcepub fn from_utf8_lossy_owned(v: Vec<u8>) -> String
Available on non-no_global_oom_handling only.
pub fn from_utf8_lossy_owned(v: Vec<u8>) -> String
no_global_oom_handling only.Converts a Vec<u8> to a String, substituting invalid UTF-8
sequences with replacement characters.
See from_utf8_lossy for more details.
Note that this function does not guarantee reuse of the original Vec
allocation.
§Examples
Basic usage:
// some bytes, in a vector
let sparkle_heart = vec![240, 159, 146, 150];
let sparkle_heart = String::from_utf8_lossy_owned(sparkle_heart);
assert_eq!(String::from("💖"), sparkle_heart);Incorrect bytes:
// some invalid bytes
let input: Vec<u8> = b"Hello \xF0\x90\x80World".into();
let output = String::from_utf8_lossy_owned(input);
assert_eq!(String::from("Hello �World"), output);1.0.0 · Sourcepub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error>
Available on non-no_global_oom_handling only.
pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error>
no_global_oom_handling only.Decode a native endian UTF-16–encoded vector v into a String,
returning Err if v contains any invalid data.
§Examples
// 𝄞music
let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
0x0073, 0x0069, 0x0063];
assert_eq!(String::from("𝄞music"),
String::from_utf16(v).unwrap());
// 𝄞mu<invalid>ic
let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
0xD800, 0x0069, 0x0063];
assert!(String::from_utf16(v).is_err());1.0.0 · Sourcepub fn from_utf16_lossy(v: &[u16]) -> String
Available on non-no_global_oom_handling only.
pub fn from_utf16_lossy(v: &[u16]) -> String
no_global_oom_handling only.Decode a native endian UTF-16–encoded slice v into a String,
replacing invalid data with the replacement character (U+FFFD).
Unlike from_utf8_lossy which returns a Cow<'a, str>,
from_utf16_lossy returns a String since the UTF-16 to UTF-8
conversion requires a memory allocation.
§Examples
// 𝄞mus<invalid>ic<invalid>
let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
0x0073, 0xDD1E, 0x0069, 0x0063,
0xD834];
assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
String::from_utf16_lossy(v));1.98.0 · Sourcepub fn from_utf16le(v: &[u8]) -> Result<String, FromUtf16Error>
Available on non-no_global_oom_handling only.
pub fn from_utf16le(v: &[u8]) -> Result<String, FromUtf16Error>
no_global_oom_handling only.Decode a UTF-16LE–encoded vector v into a String,
returning Err if v contains any invalid data.
§Examples
Basic usage:
// 𝄞music
let v = &[0x34, 0xD8, 0x1E, 0xDD, 0x6d, 0x00, 0x75, 0x00,
0x73, 0x00, 0x69, 0x00, 0x63, 0x00];
assert_eq!(String::from("𝄞music"),
String::from_utf16le(v).unwrap());
// 𝄞mu<invalid>ic
let v = &[0x34, 0xD8, 0x1E, 0xDD, 0x6d, 0x00, 0x75, 0x00,
0x00, 0xD8, 0x69, 0x00, 0x63, 0x00];
assert!(String::from_utf16le(v).is_err());1.98.0 · Sourcepub fn from_utf16le_lossy(v: &[u8]) -> String
Available on non-no_global_oom_handling only.
pub fn from_utf16le_lossy(v: &[u8]) -> String
no_global_oom_handling only.Decode a UTF-16LE–encoded slice v into a String, replacing
invalid data with the replacement character (U+FFFD).
Unlike from_utf8_lossy which returns a Cow<'a, str>,
from_utf16le_lossy returns a String since the UTF-16 to UTF-8
conversion requires a memory allocation.
§Examples
Basic usage:
// 𝄞mus<invalid>ic<invalid>
let v = &[0x34, 0xD8, 0x1E, 0xDD, 0x6d, 0x00, 0x75, 0x00,
0x73, 0x00, 0x1E, 0xDD, 0x69, 0x00, 0x63, 0x00,
0x34, 0xD8];
assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
String::from_utf16le_lossy(v));1.98.0 · Sourcepub fn from_utf16be(v: &[u8]) -> Result<String, FromUtf16Error>
Available on non-no_global_oom_handling only.
pub fn from_utf16be(v: &[u8]) -> Result<String, FromUtf16Error>
no_global_oom_handling only.Decode a UTF-16BE–encoded vector v into a String,
returning Err if v contains any invalid data.
§Examples
Basic usage:
// 𝄞music
let v = &[0xD8, 0x34, 0xDD, 0x1E, 0x00, 0x6d, 0x00, 0x75,
0x00, 0x73, 0x00, 0x69, 0x00, 0x63];
assert_eq!(String::from("𝄞music"),
String::from_utf16be(v).unwrap());
// 𝄞mu<invalid>ic
let v = &[0xD8, 0x34, 0xDD, 0x1E, 0x00, 0x6d, 0x00, 0x75,
0xD8, 0x00, 0x00, 0x69, 0x00, 0x63];
assert!(String::from_utf16be(v).is_err());1.98.0 · Sourcepub fn from_utf16be_lossy(v: &[u8]) -> String
Available on non-no_global_oom_handling only.
pub fn from_utf16be_lossy(v: &[u8]) -> String
no_global_oom_handling only.Decode a UTF-16BE–encoded slice v into a String, replacing
invalid data with the replacement character (U+FFFD).
Unlike from_utf8_lossy which returns a Cow<'a, str>,
from_utf16le_lossy returns a String since the UTF-16 to UTF-8
conversion requires a memory allocation.
§Examples
Basic usage:
// 𝄞mus<invalid>ic<invalid>
let v = &[0xD8, 0x34, 0xDD, 0x1E, 0x00, 0x6d, 0x00, 0x75,
0x00, 0x73, 0xDD, 0x1E, 0x00, 0x69, 0x00, 0x63,
0xD8, 0x34];
assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
String::from_utf16be_lossy(v));1.93.0 · Sourcepub fn into_raw_parts(self) -> (*mut u8, usize, usize)
pub fn into_raw_parts(self) -> (*mut u8, usize, usize)
Decomposes a String into its raw components: (pointer, length, capacity).
Returns the raw pointer to the underlying data, the length of
the string (in bytes), and the allocated capacity of the data
(in bytes). These are the same arguments in the same order as
the arguments to from_raw_parts.
After calling this function, the caller is responsible for the
memory previously managed by the String. The only way to do
this is to convert the raw pointer, length, and capacity back
into a String with the from_raw_parts function, allowing
the destructor to perform the cleanup.
§Examples
let s = String::from("hello");
let (ptr, len, cap) = s.into_raw_parts();
let rebuilt = unsafe { String::from_raw_parts(ptr, len, cap) };
assert_eq!(rebuilt, "hello");1.0.0 · Sourcepub unsafe fn from_raw_parts(
buf: *mut u8,
length: usize,
capacity: usize,
) -> String
pub unsafe fn from_raw_parts( buf: *mut u8, length: usize, capacity: usize, ) -> String
Creates a new String from a pointer, a length and a capacity.
§Safety
This is highly unsafe, due to the number of invariants that aren’t checked:
- all safety requirements for
Vec::<u8>::from_raw_parts. - all safety requirements for
String::from_utf8_unchecked.
Violating these may cause problems like corrupting the allocator’s
internal data structures. For example, it is normally not safe to
build a String from a pointer to a C char array containing UTF-8
unless you are certain that array was originally allocated by the
Rust standard library’s allocator.
The ownership of buf is effectively transferred to the
String which may then deallocate, reallocate or change the
contents of memory pointed to by the pointer at will. Ensure
that nothing else uses the pointer after calling this
function.
§Examples
unsafe {
let s = String::from("hello");
// Deconstruct the String into parts.
let (ptr, len, capacity) = s.into_raw_parts();
let s = String::from_raw_parts(ptr, len, capacity);
assert_eq!(String::from("hello"), s);
}1.0.0 · Sourcepub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String
pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String
Converts a vector of bytes to a String without checking that the
string contains valid UTF-8.
See the safe version, from_utf8, for more details.
§Safety
This function is unsafe because it does not check that the bytes passed
to it are valid UTF-8. If this constraint is violated, it may cause
memory unsafety issues with future users of the String, as the rest of
the standard library assumes that Strings are valid UTF-8.
§Examples
// some bytes, in a vector
let sparkle_heart = vec![240, 159, 146, 150];
let sparkle_heart = unsafe {
String::from_utf8_unchecked(sparkle_heart)
};
assert_eq!("💖", sparkle_heart);1.0.0 (const: 1.87.0) · Sourcepub const fn into_bytes(self) -> Vec<u8> ⓘ
pub const fn into_bytes(self) -> Vec<u8> ⓘ
Converts a String into a byte vector.
This consumes the String, so we do not need to copy its contents.
§Examples
let s = String::from("hello");
let bytes = s.into_bytes();
assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);1.7.0 (const: 1.87.0) · Sourcepub const fn as_str(&self) -> &str
pub const 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 (const: 1.87.0) · Sourcepub const fn as_mut_str(&mut self) -> &mut str
pub const 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 (const: 1.87.0) · Sourcepub const fn capacity(&self) -> usize
pub const 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 (const: 1.87.0) · Sourcepub const fn as_bytes(&self) -> &[u8] ⓘ
pub const 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 (const: 1.87.0) · Sourcepub const unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> ⓘ
pub const 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 (const: 1.87.0) · Sourcepub const fn len(&self) -> usize
pub const 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 (const: 1.87.0) · Sourcepub const fn is_empty(&self) -> bool
pub const 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, "");Sourcepub fn into_chars(self) -> IntoChars ⓘ
🔬This is a nightly-only experimental API. (string_into_chars)
pub fn into_chars(self) -> IntoChars ⓘ
string_into_chars)Converts a String into an iterator over the chars of the string.
As a string consists of valid UTF-8, we can iterate through a string
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. That functionality
is not provided by Rust’s standard library, check crates.io instead.
§Examples
Basic usage:
#![feature(string_into_chars)]
let word = String::from("goodbye");
let mut chars = word.into_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:
#![feature(string_into_chars)]
let y = String::from("y̆");
let mut chars = y.into_chars();
assert_eq!(Some('y'), chars.next()); // not 'y̆'
assert_eq!(Some('\u{0306}'), chars.next());
assert_eq!(None, chars.next());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: ❌❌✅");1.4.0 · Sourcepub fn into_boxed_str(self) -> Box<str>
Available on non-no_global_oom_handling only.
pub fn into_boxed_str(self) -> Box<str>
no_global_oom_handling only.Converts this String into a Box<str>.
Before doing the conversion, this method discards excess capacity like shrink_to_fit.
Note that this call may reallocate and copy the bytes of the string.
§Examples
let s = String::from("hello");
let b = s.into_boxed_str();1.72.0 · Sourcepub fn leak<'a>(self) -> &'a mut str
pub fn leak<'a>(self) -> &'a mut str
Consumes and leaks the String, returning a mutable reference to the contents,
&'a mut str.
The caller has free choice over the returned lifetime, including 'static. Indeed,
this function is ideally used for data that lives for the remainder of the program’s life,
as dropping the returned reference will cause a memory leak.
It does not reallocate or shrink the String, so the leaked allocation may include unused
capacity that is not part of the returned slice. If you want to discard excess capacity,
call into_boxed_str, and then Box::leak instead. However, keep in mind that
trimming the capacity may result in a reallocation and copy.
§Examples
let x = String::from("bucket");
let static_ref: &'static mut str = x.leak();
assert_eq!(static_ref, "bucket");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<'i> Accumulate<&'i str> for String
Available on crate feature alloc only.
impl<'i> Accumulate<&'i str> for String
alloc only.Source§impl Accumulate<String> for String
Available on crate feature alloc only.
impl Accumulate<String> for String
alloc only.Source§impl Accumulate<char> for String
Available on crate feature alloc only.
impl Accumulate<char> for String
alloc only.1.0.0 · Source§impl Add<&str> for String
Available on non-no_global_oom_handling only.Implements the + operator for concatenating two strings.
impl Add<&str> for String
no_global_oom_handling only.Implements the + operator for concatenating two strings.
This consumes the String on the left-hand side and re-uses its buffer (growing it if
necessary). This is done to avoid allocating a new String and copying the entire contents on
every operation, which would lead to O(n^2) running time when building an n-byte string by
repeated concatenation.
The string on the right-hand side is only borrowed; its contents are copied into the returned
String.
§Examples
Concatenating two Strings takes the first by value and borrows the second:
let a = String::from("hello");
let b = String::from(" world");
let c = a + &b;
// `a` is moved and can no longer be used here.If you want to keep using the first String, you can clone it and append to the clone instead:
let a = String::from("hello");
let b = String::from(" world");
let c = a.clone() + &b;
// `a` is still valid here.Concatenating &str slices can be done by converting the first to a String:
let a = "hello";
let b = " world";
let c = a.to_string() + b;1.12.0 · Source§impl AddAssign<&str> for String
Available on non-no_global_oom_handling only.Implements the += operator for appending to a String.
impl AddAssign<&str> for String
no_global_oom_handling only.Implements the += operator for appending to a String.
This has the same behavior as the push_str method.
Source§fn add_assign(&mut self, other: &str)
fn add_assign(&mut self, other: &str)
+= operation. Read moreSource§impl Arg for &String
Available on crate feature alloc only.
impl Arg for &String
alloc only.Source§fn to_string_lossy(&self) -> Cow<'_, str>
fn to_string_lossy(&self) -> Cow<'_, str>
Cow<'_, str>.Source§fn as_cow_c_str(&self) -> Result<Cow<'_, CStr>, Errno>
fn as_cow_c_str(&self) -> Result<Cow<'_, CStr>, Errno>
CStr.Source§impl Arg for String
Available on crate feature alloc only.
impl Arg for String
alloc only.Source§fn to_string_lossy(&self) -> Cow<'_, str>
fn to_string_lossy(&self) -> Cow<'_, str>
Cow<'_, str>.Source§fn as_cow_c_str(&self) -> Result<Cow<'_, CStr>, Errno>
fn as_cow_c_str(&self) -> Result<Cow<'_, CStr>, Errno>
CStr.Source§impl Arg for &String
Available on crate feature alloc only.
impl Arg for &String
alloc only.Source§fn to_string_lossy(&self) -> Cow<'_, str>
fn to_string_lossy(&self) -> Cow<'_, str>
Cow<'_, str>.Source§fn as_cow_c_str(&self) -> Result<Cow<'_, CStr>, Errno>
fn as_cow_c_str(&self) -> Result<Cow<'_, CStr>, Errno>
CStr.Source§impl Arg for String
Available on crate feature alloc only.
impl Arg for String
alloc only.Source§fn to_string_lossy(&self) -> Cow<'_, str>
fn to_string_lossy(&self) -> Cow<'_, str>
Cow<'_, str>.Source§fn as_cow_c_str(&self) -> Result<Cow<'_, CStr>, Errno>
fn as_cow_c_str(&self) -> Result<Cow<'_, CStr>, Errno>
CStr.impl AsHeaderName for String
impl AsHeaderName for &String
impl AsSendBody for String
impl AsSendBody for &String
Source§impl Body for String
impl Body for String
Source§type Error = Infallible
type Error = Infallible
Body might generate.Source§fn poll_frame(
self: Pin<&mut String>,
_cx: &mut Context<'_>,
) -> Poll<Option<Result<Frame<<String as Body>::Data>, <String as Body>::Error>>>
fn poll_frame( self: Pin<&mut String>, _cx: &mut Context<'_>, ) -> Poll<Option<Result<Frame<<String as Body>::Data>, <String as Body>::Error>>>
Source§fn is_end_stream(&self) -> bool
fn is_end_stream(&self) -> bool
true when the end of stream has been reached. Read more1.36.0 · Source§impl BorrowMut<str> for String
impl BorrowMut<str> for String
Source§fn borrow_mut(&mut self) -> &mut str
fn borrow_mut(&mut self) -> &mut str
impl DerefPure for String
Source§impl<'de> Deserialize<'de> for String
Available on crate features alloc or std only.
impl<'de> Deserialize<'de> for String
alloc or std only.Source§fn deserialize<D>(
deserializer: D,
) -> Result<String, <D as Deserializer<'de>>::Error>where
D: Deserializer<'de>,
fn deserialize<D>(
deserializer: D,
) -> Result<String, <D as Deserializer<'de>>::Error>where
D: Deserializer<'de>,
Source§impl EncodeAsVarULE<str> for String
Available on crate feature alloc only.
impl EncodeAsVarULE<str> for String
alloc only.Source§fn encode_var_ule_as_slices<R>(&self, cb: impl FnOnce(&[&[u8]]) -> R) -> R
fn encode_var_ule_as_slices<R>(&self, cb: impl FnOnce(&[&[u8]]) -> R) -> R
cb with a piecewise list of byte slices that when concatenated
produce the memory pattern of the corresponding instance of T. Read moreSource§fn encode_var_ule_len(&self) -> usize
fn encode_var_ule_len(&self) -> usize
VarULE typeSource§fn encode_var_ule_write(&self, dst: &mut [u8])
fn encode_var_ule_write(&self, dst: &mut [u8])
VarULE type to the dst buffer. dst should
be the size of Self::encode_var_ule_len()Source§impl EncodeAsVarULE<str> for &String
Available on crate feature alloc only.
impl EncodeAsVarULE<str> for &String
alloc only.Source§fn encode_var_ule_as_slices<R>(&self, cb: impl FnOnce(&[&[u8]]) -> R) -> R
fn encode_var_ule_as_slices<R>(&self, cb: impl FnOnce(&[&[u8]]) -> R) -> R
cb with a piecewise list of byte slices that when concatenated
produce the memory pattern of the corresponding instance of T. Read moreSource§fn encode_var_ule_len(&self) -> usize
fn encode_var_ule_len(&self) -> usize
VarULE typeSource§fn encode_var_ule_write(&self, dst: &mut [u8])
fn encode_var_ule_write(&self, dst: &mut [u8])
VarULE type to the dst buffer. dst should
be the size of Self::encode_var_ule_len()impl Eq for String
Source§impl<'a> Extend<&'a AsciiChar> for String
Available on non-no_global_oom_handling only.
impl<'a> Extend<&'a AsciiChar> for String
no_global_oom_handling only.Source§fn extend<I>(&mut self, iter: I)where
I: IntoIterator<Item = &'a AsciiChar>,
fn extend<I>(&mut self, iter: I)where
I: IntoIterator<Item = &'a AsciiChar>,
Source§fn extend_one(&mut self, c: &'a AsciiChar)
fn extend_one(&mut self, c: &'a AsciiChar)
extend_one)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one)1.2.0 · Source§impl<'a> Extend<&'a char> for String
Available on non-no_global_oom_handling only.
impl<'a> Extend<&'a char> for String
no_global_oom_handling only.Source§fn extend<I>(&mut self, iter: I)where
I: IntoIterator<Item = &'a char>,
fn extend<I>(&mut self, iter: I)where
I: IntoIterator<Item = &'a char>,
Source§fn extend_one(&mut self, _: &'a char)
fn extend_one(&mut self, _: &'a char)
extend_one)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one)1.0.0 · Source§impl<'a> Extend<&'a str> for String
Available on non-no_global_oom_handling only.
impl<'a> Extend<&'a str> for String
no_global_oom_handling only.Source§fn extend<I>(&mut self, iter: I)where
I: IntoIterator<Item = &'a str>,
fn extend<I>(&mut self, iter: I)where
I: IntoIterator<Item = &'a str>,
Source§fn extend_one(&mut self, s: &'a str)
fn extend_one(&mut self, s: &'a str)
extend_one)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one)Source§impl Extend<AsciiChar> for String
Available on non-no_global_oom_handling only.
impl Extend<AsciiChar> for String
no_global_oom_handling only.Source§fn extend<I>(&mut self, iter: I)where
I: IntoIterator<Item = AsciiChar>,
fn extend<I>(&mut self, iter: I)where
I: IntoIterator<Item = AsciiChar>,
Source§fn extend_one(&mut self, c: AsciiChar)
fn extend_one(&mut self, c: AsciiChar)
extend_one)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one)1.45.0 · Source§impl<A> Extend<Box<str, A>> for Stringwhere
A: Allocator,
Available on non-no_global_oom_handling only.
impl<A> Extend<Box<str, A>> for Stringwhere
A: Allocator,
no_global_oom_handling only.Source§fn extend<I>(&mut self, iter: I)
fn extend<I>(&mut self, iter: I)
Source§fn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one)Source§impl<A> Extend<Box<str, A>> for Stringwhere
A: Allocator,
Available on crate feature alloc only.
impl<A> Extend<Box<str, A>> for Stringwhere
A: Allocator,
alloc only.Source§fn extend<I>(&mut self, iter: I)
fn extend<I>(&mut self, iter: I)
Source§fn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one)1.19.0 · Source§impl<'a> Extend<Cow<'a, str>> for String
Available on non-no_global_oom_handling only.
impl<'a> Extend<Cow<'a, str>> for String
no_global_oom_handling only.Source§fn extend<I>(&mut self, iter: I)
fn extend<I>(&mut self, iter: I)
Source§fn extend_one(&mut self, s: Cow<'a, str>)
fn extend_one(&mut self, s: Cow<'a, str>)
extend_one)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one)1.4.0 · Source§impl Extend<String> for String
Available on non-no_global_oom_handling only.
impl Extend<String> for String
no_global_oom_handling only.Source§fn extend<I>(&mut self, iter: I)where
I: IntoIterator<Item = String>,
fn extend<I>(&mut self, iter: I)where
I: IntoIterator<Item = String>,
Source§fn extend_one(&mut self, s: String)
fn extend_one(&mut self, s: String)
extend_one)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one)1.0.0 · Source§impl Extend<char> for String
Available on non-no_global_oom_handling only.
impl Extend<char> for String
no_global_oom_handling only.Source§fn extend<I>(&mut self, iter: I)where
I: IntoIterator<Item = char>,
fn extend<I>(&mut self, iter: I)where
I: IntoIterator<Item = char>,
Source§fn extend_one(&mut self, c: char)
fn extend_one(&mut self, c: char)
extend_one)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one)1.28.0 · Source§impl<'a> From<&'a String> for Cow<'a, str>
Available on non-no_global_oom_handling only.
impl<'a> From<&'a String> for Cow<'a, str>
no_global_oom_handling only.1.14.0 · Source§impl<'a> From<Cow<'a, str>> for String
Available on non-no_global_oom_handling only.
impl<'a> From<Cow<'a, str>> for String
no_global_oom_handling only.Source§fn from(s: Cow<'a, str>) -> String
fn from(s: Cow<'a, str>) -> String
Converts a clone-on-write string to an owned
instance of String.
This extracts the owned string, clones the string if it is not already owned.
§Example
// If the string is not owned...
let cow: Cow<'_, str> = Cow::Borrowed("eggplant");
// It will allocate on the heap and copy the string.
let owned: String = String::from(cow);
assert_eq!(&owned[..], "eggplant");Source§impl From<DiagnosticPath> for String
impl From<DiagnosticPath> for String
Source§fn from(path: DiagnosticPath) -> String
fn from(path: DiagnosticPath) -> String
Source§impl From<ScriptLangTag<'_>> for String
Available on crate feature std only.
impl From<ScriptLangTag<'_>> for String
std only.Source§fn from(value: ScriptLangTag<'_>) -> String
fn from(value: ScriptLangTag<'_>) -> String
1.0.0 · Source§impl<'a> From<String> for Box<dyn Error + Sync + Send + 'a>
Available on non-no_global_oom_handling only.
impl<'a> From<String> for Box<dyn Error + Sync + Send + 'a>
no_global_oom_handling only.1.6.0 · Source§impl<'a> From<String> for Box<dyn Error + 'a>
Available on non-no_global_oom_handling only.
impl<'a> From<String> for Box<dyn Error + 'a>
no_global_oom_handling only.Source§impl From<String> for AssetSourceId<'static>
impl From<String> for AssetSourceId<'static>
Source§fn from(value: String) -> AssetSourceId<'static>
fn from(value: String) -> AssetSourceId<'static>
Source§impl From<String> for ShaderDefVal
impl From<String> for ShaderDefVal
Source§fn from(key: String) -> ShaderDefVal
fn from(key: String) -> ShaderDefVal
Source§impl<'a> FromIterator<&'a AsciiChar> for String
Available on non-no_global_oom_handling only.
impl<'a> FromIterator<&'a AsciiChar> for String
no_global_oom_handling only.1.17.0 · Source§impl<'a> FromIterator<&'a char> for String
Available on non-no_global_oom_handling only.
impl<'a> FromIterator<&'a char> for String
no_global_oom_handling only.1.0.0 · Source§impl<'a> FromIterator<&'a str> for String
Available on non-no_global_oom_handling only.
impl<'a> FromIterator<&'a str> for String
no_global_oom_handling only.Source§impl FromIterator<AsciiChar> for String
Available on non-no_global_oom_handling only.
impl FromIterator<AsciiChar> for String
no_global_oom_handling only.1.45.0 · Source§impl<A> FromIterator<Box<str, A>> for Stringwhere
A: Allocator,
Available on non-no_global_oom_handling only.
impl<A> FromIterator<Box<str, A>> for Stringwhere
A: Allocator,
no_global_oom_handling only.1.19.0 · Source§impl<'a> FromIterator<Cow<'a, str>> for String
Available on non-no_global_oom_handling only.
impl<'a> FromIterator<Cow<'a, str>> for String
no_global_oom_handling only.1.4.0 · Source§impl FromIterator<String> for String
Available on non-no_global_oom_handling only.
impl FromIterator<String> for String
no_global_oom_handling only.1.12.0 · Source§impl<'a> FromIterator<String> for Cow<'a, str>
Available on non-no_global_oom_handling only.
impl<'a> FromIterator<String> for Cow<'a, str>
no_global_oom_handling only.1.0.0 · Source§impl FromIterator<char> for String
Available on non-no_global_oom_handling only.
impl FromIterator<char> for String
no_global_oom_handling only.Source§impl FromReflect for String
impl FromReflect for String
Source§fn from_reflect(reflect: &(dyn PartialReflect + 'static)) -> Option<String>
fn from_reflect(reflect: &(dyn PartialReflect + 'static)) -> Option<String>
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 String
impl GetTypeRegistration for String
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 IdentFragment for String
impl IdentFragment for String
impl Index for String
impl Index for String
Source§impl IntoAttributeValue for String
impl IntoAttributeValue for String
Source§fn into_value(self) -> AttributeValue
fn into_value(self) -> AttributeValue
Source§impl IntoClientRequest for &String
impl IntoClientRequest for &String
Source§impl IntoClientRequest for String
impl IntoClientRequest for String
Source§impl<'de, E> IntoDeserializer<'de, E> for Stringwhere
E: Error,
Available on crate features alloc or std only.
impl<'de, E> IntoDeserializer<'de, E> for Stringwhere
E: Error,
alloc or std only.Source§type Deserializer = StringDeserializer<E>
type Deserializer = StringDeserializer<E>
Source§fn into_deserializer(self) -> StringDeserializer<E>
fn into_deserializer(self) -> StringDeserializer<E>
Source§impl IntoDynNode for String
impl IntoDynNode for String
Source§fn into_dyn_node(self) -> DynamicNode
fn into_dyn_node(self) -> DynamicNode
Source§impl IntoReturn for String
impl IntoReturn for String
1.0.0 · Source§impl Ord for String
impl Ord for String
1.21.0 (const: unstable) · Source§fn max(self, other: Self) -> Selfwhere
Self: Sized,
fn max(self, other: Self) -> Selfwhere
Self: Sized,
Source§impl PartialEq<ByteString> for String
impl PartialEq<ByteString> for String
Source§impl PartialEq<HeaderValue> for String
impl PartialEq<HeaderValue> for String
Source§impl PartialEq<PathAndQuery> for String
impl PartialEq<PathAndQuery> for String
Source§impl<const N: usize> PartialEq<TinyAsciiStr<N>> for String
Available on crate feature alloc only.
impl<const N: usize> PartialEq<TinyAsciiStr<N>> for String
alloc only.1.0.0 · Source§impl PartialOrd for String
impl PartialOrd for String
Source§impl PartialOrd<Authority> for String
impl PartialOrd<Authority> for String
Source§impl PartialOrd<Bytes> for String
impl PartialOrd<Bytes> for String
Source§impl PartialOrd<BytesMut> for String
impl PartialOrd<BytesMut> for String
Source§impl PartialOrd<HeaderValue> for String
impl PartialOrd<HeaderValue> for String
Source§impl PartialOrd<PathAndQuery> for String
impl PartialOrd<PathAndQuery> for String
Source§impl PartialReflect for String
impl PartialReflect for String
Source§fn get_represented_type_info(&self) -> Option<&'static TypeInfo>
fn get_represented_type_info(&self) -> Option<&'static TypeInfo>
Source§fn to_dynamic(&self) -> Box<dyn PartialReflect>
fn to_dynamic(&self) -> Box<dyn PartialReflect>
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<String>) -> ReflectOwned
fn reflect_owned(self: Box<String>) -> ReflectOwned
Source§fn try_into_reflect(
self: Box<String>,
) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>>
fn try_into_reflect( self: Box<String>, ) -> 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<String>) -> Box<dyn PartialReflect>
fn into_partial_reflect(self: Box<String>) -> 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_hash(&self) -> Option<u64>
fn reflect_hash(&self) -> Option<u64>
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 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 is_dynamic(&self) -> bool
fn is_dynamic(&self) -> bool
Source§impl<'b> Pattern for &'b String
A convenience impl that delegates to the impl for &str.
impl<'b> Pattern for &'b String
A convenience impl that delegates to the impl for &str.
§Examples
assert_eq!(String::from("Hello world").find("world"), Some(6));Source§type Searcher<'a> = <&'b str as Pattern>::Searcher<'a>
type Searcher<'a> = <&'b str as Pattern>::Searcher<'a>
pattern)Source§fn into_searcher(self, haystack: &str) -> <&'b str as Pattern>::Searcher<'_>
fn into_searcher(self, haystack: &str) -> <&'b str as Pattern>::Searcher<'_>
pattern)self and the haystack to search in.Source§fn is_contained_in(self, haystack: &str) -> bool
fn is_contained_in(self, haystack: &str) -> bool
pattern)Source§fn is_prefix_of(self, haystack: &str) -> bool
fn is_prefix_of(self, haystack: &str) -> bool
pattern)Source§fn strip_prefix_of(self, haystack: &str) -> Option<&str>
fn strip_prefix_of(self, haystack: &str) -> Option<&str>
pattern)Source§fn is_suffix_of<'a>(self, haystack: &'a str) -> bool
fn is_suffix_of<'a>(self, haystack: &'a str) -> bool
pattern)Source§fn strip_suffix_of<'a>(self, haystack: &'a str) -> Option<&'a str>
fn strip_suffix_of<'a>(self, haystack: &'a str) -> Option<&'a str>
pattern)Source§fn as_utf8_pattern(&self) -> Option<Utf8Pattern<'_>>
fn as_utf8_pattern(&self) -> Option<Utf8Pattern<'_>>
pattern)Source§impl Reflect for String
impl Reflect for String
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<String>) -> Box<dyn Reflect>
fn into_reflect(self: Box<String>) -> Box<dyn Reflect>
Source§fn as_reflect(&self) -> &(dyn Reflect + 'static)
fn as_reflect(&self) -> &(dyn Reflect + 'static)
Source§fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)
fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)
Source§impl<'a> Replacer for &'a String
impl<'a> Replacer for &'a String
Source§fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut String)
fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut String)
dst to replace the current match. Read moreSource§fn no_expansion(&mut self) -> Option<Cow<'_, str>>
fn no_expansion(&mut self) -> Option<Cow<'_, str>>
Source§fn by_ref<'r>(&'r mut self) -> ReplacerRef<'r, Self>
fn by_ref<'r>(&'r mut self) -> ReplacerRef<'r, Self>
Source§impl Replacer for String
impl Replacer for String
Source§fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut String)
fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut String)
dst to replace the current match. Read moreSource§fn no_expansion(&mut self) -> Option<Cow<'_, str>>
fn no_expansion(&mut self) -> Option<Cow<'_, str>>
Source§fn by_ref<'r>(&'r mut self) -> ReplacerRef<'r, Self>
fn by_ref<'r>(&'r mut self) -> ReplacerRef<'r, Self>
Source§impl Serialize for String
Available on crate features alloc or std only.
impl Serialize for String
alloc or std only.Source§fn serialize<S>(
&self,
serializer: S,
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where
S: Serializer,
fn serialize<S>(
&self,
serializer: S,
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where
S: Serializer,
impl StableDeref for String
alloc only.Source§impl StrConsumer for String
Pushes the str onto the end of the String
impl StrConsumer for String
Pushes the str onto the end of the String
Source§impl<'s> StringBuilder<'s> for String
Available on crate feature alloc only.
impl<'s> StringBuilder<'s> for String
alloc only.impl StructuralPartialEq for String
1.16.0 · Source§impl ToSocketAddrs for String
impl ToSocketAddrs for String
Source§type Iter = IntoIter<SocketAddr>
type Iter = IntoIter<SocketAddr>
Source§fn to_socket_addrs(&self) -> Result<IntoIter<SocketAddr>, Error>
fn to_socket_addrs(&self) -> Result<IntoIter<SocketAddr>, Error>
SocketAddrs. Read moreSource§impl ToTokens for String
impl ToTokens for String
Source§fn to_tokens(&self, tokens: &mut TokenStream)
fn to_tokens(&self, tokens: &mut TokenStream)
proc_macro_totokens)Source§fn to_token_stream(&self) -> TokenStream
fn to_token_stream(&self) -> TokenStream
proc_macro_totokens)Source§fn into_token_stream(self) -> TokenStreamwhere
Self: Sized,
fn into_token_stream(self) -> TokenStreamwhere
Self: Sized,
proc_macro_totokens)Source§impl ToTokens for String
impl ToTokens for String
Source§fn to_tokens(&self, tokens: &mut TokenStream)
fn to_tokens(&self, tokens: &mut TokenStream)
Source§fn to_token_stream(&self) -> TokenStream
fn to_token_stream(&self) -> TokenStream
Source§fn into_token_stream(self) -> TokenStreamwhere
Self: Sized,
fn into_token_stream(self) -> TokenStreamwhere
Self: Sized,
Source§impl TryFrom<ByteString> for String
impl TryFrom<ByteString> for String
Source§type Error = FromUtf8Error
type Error = FromUtf8Error
Source§fn try_from(
s: ByteString,
) -> Result<String, <String as TryFrom<ByteString>>::Error>
fn try_from( s: ByteString, ) -> Result<String, <String as TryFrom<ByteString>>::Error>
Source§impl TryFrom<OwnedValue> for String
impl TryFrom<OwnedValue> for String
1.87.0 · Source§impl TryFrom<Vec<u8>> for String
impl TryFrom<Vec<u8>> for String
Source§impl TypePath for String
impl TypePath for String
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>
1.0.0 · Source§impl Write for String
Available on non-no_global_oom_handling only.
impl Write for String
no_global_oom_handling only.Source§impl WriteTomlKey for String
Available on crate feature alloc only.
impl WriteTomlKey for String
alloc only.Source§impl WriteTomlValue for String
Available on crate feature alloc only.
impl WriteTomlValue for String
alloc only.Source§impl Writeable for String
Available on crate feature alloc only.
impl Writeable for String
alloc only.Source§fn write_to<W>(&self, sink: &mut W) -> Result<(), Error>
fn write_to<W>(&self, sink: &mut W) -> Result<(), Error>
write_to_parts, and discards any
Part annotations.Source§fn writeable_length_hint(&self) -> LengthHint
fn writeable_length_hint(&self) -> LengthHint
Source§fn writeable_borrow(&self) -> Option<&str>
fn writeable_borrow(&self) -> Option<&str>
Source§fn write_to_parts<S>(&self, sink: &mut S) -> Result<(), Error>where
S: PartsWrite + ?Sized,
fn write_to_parts<S>(&self, sink: &mut S) -> Result<(), Error>where
S: PartsWrite + ?Sized,
Part annotations to the given sink. Errors from the
sink are bubbled up. The default implementation delegates to write_to,
and doesn’t produce any Part annotations.Auto Trait Implementations§
impl Freeze for String
impl RefUnwindSafe for String
impl Send for String
impl Sync for String
impl Unpin for String
impl UnsafeUnpin for String
impl UnwindSafe for String
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<A, T> AsBits<T> for A
impl<A, T> AsBits<T> for A
Source§impl<T> BodyExt for T
impl<T> BodyExt for T
Source§fn frame(&mut self) -> Frame<'_, Self> ⓘwhere
Self: Unpin,
fn frame(&mut self) -> Frame<'_, Self> ⓘwhere
Self: Unpin,
Frame, if any.Source§fn map_frame<F, B>(self, f: F) -> MapFrame<Self, F>
fn map_frame<F, B>(self, f: F) -> MapFrame<Self, F>
Source§fn inspect_frame<F>(self, f: F) -> InspectFrame<Self, F>
fn inspect_frame<F>(self, f: F) -> InspectFrame<Self, F>
Source§fn map_err<F, E>(self, f: F) -> MapErr<Self, F>
fn map_err<F, E>(self, f: F) -> MapErr<Self, F>
Source§fn inspect_err<F>(self, f: F) -> InspectErr<Self, F>
fn inspect_err<F>(self, f: F) -> InspectErr<Self, F>
Source§fn boxed_unsync(self) -> UnsyncBoxBody<Self::Data, Self::Error>
fn boxed_unsync(self) -> UnsyncBoxBody<Self::Data, Self::Error>
Source§fn collect(self) -> Collect<Self> ⓘwhere
Self: Sized,
fn collect(self) -> Collect<Self> ⓘwhere
Self: Sized,
Collected body which will collect all the DATA frames
and trailers.Source§fn with_trailers<F>(self, trailers: F) -> WithTrailers<Self, F>
fn with_trailers<F>(self, trailers: F) -> WithTrailers<Self, F>
Source§fn into_stream(self) -> BodyStream<Self>where
Self: Sized,
fn into_stream(self) -> BodyStream<Self>where
Self: Sized,
BodyStream.Source§fn into_data_stream(self) -> BodyDataStream<Self>where
Self: Sized,
fn into_data_stream(self) -> BodyDataStream<Self>where
Self: Sized,
BodyDataStream.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
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
impl<T> CheapCloneStr for T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<Q, K> Comparable<K> for Q
impl<Q, K> Comparable<K> for Q
impl<T> ConditionalSend for Twhere
T: Send,
impl<T> DeserializeOwned for Twhere
T: for<'de> Deserialize<'de>,
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<'de, T> DynamicDeserialize<'de> for Twhere
T: Type + Deserialize<'de>,
impl<'de, T> DynamicDeserialize<'de> for Twhere
T: Type + Deserialize<'de>,
Source§type Deserializer = PhantomData<T>
type Deserializer = PhantomData<T>
Source§fn deserializer_for_signature(
signature: &Signature,
) -> Result<<T as DynamicDeserialize<'de>>::Deserializer, Error>
fn deserializer_for_signature( signature: &Signature, ) -> Result<<T as DynamicDeserialize<'de>>::Deserializer, Error>
Source§impl<T> DynamicType for T
impl<T> DynamicType for T
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<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key and return true if they are equal.Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
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<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<S, T> ParallelSlice<T> for S
impl<S, T> ParallelSlice<T> for S
Source§fn par_chunk_map<F, R>(
&self,
task_pool: &TaskPool,
chunk_size: usize,
f: F,
) -> Vec<R>
fn par_chunk_map<F, R>( &self, task_pool: &TaskPool, chunk_size: usize, f: F, ) -> Vec<R>
chunks_size or less and maps the chunks
in parallel across the provided task_pool. One task is spawned in the task pool
for every chunk. Read moreSource§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
Source§impl<T> Serialize for T
impl<T> Serialize for T
fn erased_serialize(&self, serializer: &mut dyn Serializer) -> Result<(), Error>
fn do_erased_serialize( &self, serializer: &mut dyn Serializer, ) -> Result<(), ErrorImpl>
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<T> Spanned for Twhere
T: Spanned + ?Sized,
impl<T> Spanned for Twhere
T: Spanned + ?Sized,
Source§fn span(&self) -> Span
fn span(&self) -> Span
Span covering the complete contents of this syntax tree
node, or Span::call_site() if this node is empty.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.Source§impl<T> ToHex for T
impl<T> ToHex for T
Source§fn encode_hex<U>(&self) -> Uwhere
U: FromIterator<char>,
fn encode_hex<U>(&self) -> Uwhere
U: FromIterator<char>,
self into the result. Lower case
letters are used (e.g. f9b4ca)Source§fn encode_hex_upper<U>(&self) -> Uwhere
U: FromIterator<char>,
fn encode_hex_upper<U>(&self) -> Uwhere
U: FromIterator<char>,
self into the result. Upper case
letters are used (e.g. F9B4CA)