@@ -51,17 +51,29 @@ impl<'a, 'b> PartialEq<&'b CStr> for &'a CStr {
5151 }
5252}
5353
54+ impl std:: borrow:: ToOwned for CStr {
55+ type Owned = CString ;
56+
57+ fn to_owned ( & self ) -> Self :: Owned {
58+ self . into ( )
59+ }
60+ }
61+
62+ #[ cfg( feature = "serde" ) ]
63+ impl serde:: Serialize for & CStr {
64+ fn serialize < S > ( & self , serializer : S ) -> std:: result:: Result < S :: Ok , S :: Error >
65+ where
66+ S : serde:: Serializer ,
67+ {
68+ self . as_str ( ) . serialize ( serializer)
69+ }
70+ }
71+
5472#[ diagnostic:: on_unimplemented( message = "the string literal contains a zero byte" ) ]
5573pub trait ValidCStr { }
5674pub struct IsValidCStr < const VALID : bool > ;
5775impl ValidCStr for IsValidCStr < true > { }
5876
59- #[ derive( Clone , Eq , PartialEq , Hash ) ]
60- #[ repr( transparent) ]
61- pub struct CString {
62- data : String ,
63- }
64-
6577pub const fn validate_cstr ( text : & str ) -> Option < & CStr > {
6678 let bytes = text. as_bytes ( ) ;
6779 let mut i = 0 ;
@@ -86,6 +98,12 @@ macro_rules! cstr {
8698}
8799pub use cstr;
88100
101+ #[ derive( Clone , Eq , PartialEq , Hash ) ]
102+ #[ repr( transparent) ]
103+ pub struct CString {
104+ data : String ,
105+ }
106+
89107impl TryFrom < String > for CString {
90108 type Error = Error ;
91109
@@ -95,7 +113,20 @@ impl TryFrom<String> for CString {
95113 }
96114}
97115
116+ impl TryFrom < & str > for CString {
117+ type Error = Error ;
118+
119+ fn try_from ( data : & str ) -> Result < Self > {
120+ let cs: & CStr = data. try_into ( ) ?;
121+ Ok ( cs. into ( ) )
122+ }
123+ }
124+
98125impl CString {
126+ pub ( crate ) fn from_unchecked ( data : String ) -> Self {
127+ Self { data }
128+ }
129+
99130 pub fn into_string ( self ) -> String {
100131 self . data
101132 }
@@ -130,3 +161,9 @@ impl std::fmt::Display for CString {
130161 self . data . fmt ( f)
131162 }
132163}
164+
165+ impl std:: borrow:: Borrow < CStr > for CString {
166+ fn borrow ( & self ) -> & CStr {
167+ self . as_ref ( )
168+ }
169+ }
0 commit comments