Skip to content

Commit ea50907

Browse files
Add Cow<'a, N, LenT> type for heapless strings
- Introduced a clone-on-write (Cow) enum for heapless strings. - Supports borrowed (&StringView<LenT>) and owned (String<N, LenT>) variants. - Provides to_owned(), as_str(), is_borrowed(), and is_owned() helper methods. - Implements From for StringView and String. - Implements Borrow<str> for ergonomic use. - Fully bounded by LenT: LenType to match heapless string types.
1 parent bbe988d commit ea50907

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

src/cow.rs

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#![cfg(feature = "alloc")]
2+
3+
extern crate alloc;
4+
5+
use crate::len_type::LenType;
6+
use crate::{CapacityError, String, StringView};
7+
use core::borrow::Borrow;
8+
9+
/// A clone-on-write string type for heapless
10+
#[derive(Debug)]
11+
pub enum Cow<'a, const N: usize, LenT: LenType = usize> {
12+
Borrowed(&'a StringView<LenT>),
13+
Owned(String<N, LenT>),
14+
}
15+
16+
impl<'a, const N: usize, LenT: LenType> Cow<'a, N, LenT> {
17+
pub fn to_owned(&self) -> String<N, LenT> {
18+
match self {
19+
Cow::Borrowed(sv) => String::from(sv),
20+
Cow::Owned(s) => s.clone(),
21+
}
22+
}
23+
24+
pub fn as_str(&self) -> &str {
25+
match self {
26+
Cow::Borrowed(sv) => sv.as_str(),
27+
Cow::Owned(s) => s.as_str(),
28+
}
29+
}
30+
31+
pub fn is_borrowed(&self) -> bool {
32+
matches!(self, Cow::Borrowed(_))
33+
}
34+
35+
pub fn is_owned(&self) -> bool {
36+
matches!(self, Cow::Owned(_))
37+
}
38+
}
39+
40+
impl<'a, const N: usize, LenT: LenType> From<&'a StringView<LenT>> for Cow<'a, N, LenT> {
41+
fn from(sv: &'a StringView<LenT>) -> Self {
42+
Cow::Borrowed(sv)
43+
}
44+
}
45+
46+
impl<const N: usize, LenT: LenType> From<String<N, LenT>> for Cow<'_, N, LenT> {
47+
fn from(s: String<N, LenT>) -> Self {
48+
Cow::Owned(s)
49+
}
50+
}
51+
52+
impl<'a, const N: usize, LenT: LenType> Borrow<str> for Cow<'a, N, LenT> {
53+
fn borrow(&self) -> &str {
54+
self.as_str()
55+
}
56+
}

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,7 @@ pub use vec::{Vec, VecView};
166166
mod test_helpers;
167167

168168
pub mod c_string;
169+
pub mod cow;
169170
pub mod deque;
170171
pub mod history_buf;
171172
pub mod index_map;

0 commit comments

Comments
 (0)