1use crate::alloc::AllocError;
4use std::borrow::Cow;
5
6pub trait TryToString {
8 fn try_to_string(&self) -> Result<String, AllocError>;
10}
11
12impl TryToString for str {
13 #[inline]
14 fn try_to_string(&self) -> Result<String, AllocError> {
15 let mut s = String::new();
16 s.try_reserve_exact(self.len())?;
17 s.push_str(self);
18 Ok(s)
19 }
20}
21
22impl TryToString for Cow<'_, str> {
23 #[inline]
24 fn try_to_string(&self) -> Result<String, AllocError> {
25 self.as_ref().try_to_string()
26 }
27}
28
29impl TryToString for String {
30 #[inline]
31 fn try_to_string(&self) -> Result<String, AllocError> {
32 self.as_str().try_to_string()
33 }
34}
35
36#[cfg(test)]
37mod tests {
38 use super::*;
39
40 #[test]
41 fn test_try_to_string() {
42 assert_eq!("abc".try_to_string().unwrap(), "abc");
43 }
44}