@@ -6,50 +6,78 @@ use crate::len_type::LenType;
6
6
use crate :: { CapacityError , String , StringView } ;
7
7
use core:: borrow:: Borrow ;
8
8
9
+ /// A clone-on-write (COW) string type for heapless.
10
+ ///
11
+ /// `Cow` can either **borrow** a `StringView` or **own** a `String`.
12
+ /// This allows efficient handling of strings that may be either temporary
13
+ /// references or fully owned data.
14
+ ///
15
+ /// # Type Parameters
16
+ ///
17
+ /// - `N`: The inline buffer size for owned strings.
18
+ /// - `LenT`: The integer type used for length tracking (must implement [`LenType`]).
19
+
9
20
/// A clone-on-write string type for heapless
10
21
#[ derive( Debug ) ]
11
22
pub enum Cow < ' a , const N : usize , LenT : LenType = usize > {
23
+ /// A borrowed view of a string.
12
24
Borrowed ( & ' a StringView < LenT > ) ,
25
+
26
+ /// An owned string with inline storage of size `N`.
13
27
Owned ( String < N , LenT > ) ,
14
28
}
15
29
16
30
impl < ' a , const N : usize , LenT : LenType > Cow < ' a , N , LenT > {
31
+ /// Converts the `Cow` into an owned [`String`].
32
+ ///
33
+ /// If the `Cow` is borrowed, this clones the underlying string data.
34
+ /// If the `Cow` is already owned, this returns a clone of it.
17
35
pub fn to_owned ( & self ) -> String < N , LenT > {
18
36
match self {
19
37
Cow :: Borrowed ( sv) => String :: from ( sv) ,
20
38
Cow :: Owned ( s) => s. clone ( ) ,
21
39
}
22
40
}
23
41
42
+ /// Returns the string as a `&str`.
43
+ ///
44
+ /// Works for both borrowed and owned variants.
24
45
pub fn as_str ( & self ) -> & str {
25
46
match self {
26
47
Cow :: Borrowed ( sv) => sv. as_str ( ) ,
27
48
Cow :: Owned ( s) => s. as_str ( ) ,
28
49
}
29
50
}
30
51
52
+ /// Returns `true` if this `Cow` is a borrowed string.
31
53
pub fn is_borrowed ( & self ) -> bool {
32
54
matches ! ( self , Cow :: Borrowed ( _) )
33
55
}
34
56
57
+ /// Returns `true` if this `Cow` is an owned string.
35
58
pub fn is_owned ( & self ) -> bool {
36
59
matches ! ( self , Cow :: Owned ( _) )
37
60
}
38
61
}
39
62
40
63
impl < ' a , const N : usize , LenT : LenType > From < & ' a StringView < LenT > > for Cow < ' a , N , LenT > {
64
+ /// Creates a borrowed `Cow` from a `StringView`.
41
65
fn from ( sv : & ' a StringView < LenT > ) -> Self {
42
66
Cow :: Borrowed ( sv)
43
67
}
44
68
}
45
69
46
70
impl < const N : usize , LenT : LenType > From < String < N , LenT > > for Cow < ' _ , N , LenT > {
71
+ /// Creates an owned `Cow` from a `String`.
47
72
fn from ( s : String < N , LenT > ) -> Self {
48
73
Cow :: Owned ( s)
49
74
}
50
75
}
51
76
52
77
impl < ' a , const N : usize , LenT : LenType > Borrow < str > for Cow < ' a , N , LenT > {
78
+ /// Borrows the string as a `&str`.
79
+ ///
80
+ /// This allows `Cow` to be used anywhere a `&str` is expected.
53
81
fn borrow ( & self ) -> & str {
54
82
self . as_str ( )
55
83
}
0 commit comments