Skip to content

Commit 69a37a6

Browse files
committed
Add documentation for string->Cow conversions
Mostly, it's just to reassure everyone that these functions don't allocate. Part of #51430
1 parent 8fd946c commit 69a37a6

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

library/alloc/src/string.rs

+33
Original file line numberDiff line numberDiff line change
@@ -2352,6 +2352,16 @@ impl<'a> From<Cow<'a, str>> for String {
23522352

23532353
#[stable(feature = "rust1", since = "1.0.0")]
23542354
impl<'a> From<&'a str> for Cow<'a, str> {
2355+
/// Converts a string slice into a Borrowed variant.
2356+
/// No heap allocation is performed, and the string
2357+
/// is not copied.
2358+
///
2359+
/// # Example
2360+
///
2361+
/// ```
2362+
/// # use std::borrow::Cow;
2363+
/// assert_eq!(Cow::from("eggplant"), Cow::Borrowed("eggplant"));
2364+
/// ```
23552365
#[inline]
23562366
fn from(s: &'a str) -> Cow<'a, str> {
23572367
Cow::Borrowed(s)
@@ -2360,6 +2370,18 @@ impl<'a> From<&'a str> for Cow<'a, str> {
23602370

23612371
#[stable(feature = "rust1", since = "1.0.0")]
23622372
impl<'a> From<String> for Cow<'a, str> {
2373+
/// Converts a String into an Owned variant.
2374+
/// No heap allocation is performed, and the string
2375+
/// is not copied.
2376+
///
2377+
/// # Example
2378+
///
2379+
/// ```
2380+
/// # use std::borrow::Cow;
2381+
/// let s = "eggplant".to_string();
2382+
/// let s2 = "eggplant".to_string();
2383+
/// assert_eq!(Cow::from(s), Cow::<'static, str>::Owned(s2));
2384+
/// ```
23632385
#[inline]
23642386
fn from(s: String) -> Cow<'a, str> {
23652387
Cow::Owned(s)
@@ -2368,6 +2390,17 @@ impl<'a> From<String> for Cow<'a, str> {
23682390

23692391
#[stable(feature = "cow_from_string_ref", since = "1.28.0")]
23702392
impl<'a> From<&'a String> for Cow<'a, str> {
2393+
/// Converts a String reference into a Borrowed variant.
2394+
/// No heap allocation is performed, and the string
2395+
/// is not copied.
2396+
///
2397+
/// # Example
2398+
///
2399+
/// ```
2400+
/// # use std::borrow::Cow;
2401+
/// let s = "eggplant".to_string();
2402+
/// assert_eq!(Cow::from(&s), Cow::Borrowed("eggplant"));
2403+
/// ```
23712404
#[inline]
23722405
fn from(s: &'a String) -> Cow<'a, str> {
23732406
Cow::Borrowed(s.as_str())

0 commit comments

Comments
 (0)