4 use smallvec::SmallVec;
6 const SIZE: usize = 36;
8 /// Like SmallVec but for C strings.
10 pub struct SmallCStr {
11 data: SmallVec<[u8; SIZE]>,
16 pub fn new(s: &str) -> SmallCStr {
19 let data = if len < SIZE {
20 let mut buf = [0; SIZE];
21 buf[..len].copy_from_slice(s.as_bytes());
22 SmallVec::from_buf_and_len(buf, len1)
24 let mut data = Vec::with_capacity(len1);
25 data.extend_from_slice(s.as_bytes());
27 SmallVec::from_vec(data)
29 if let Err(e) = ffi::CStr::from_bytes_with_nul(&data) {
30 panic!("The string \"{}\" cannot be converted into a CStr: {}", s, e);
36 pub fn new_with_nul(s: &str) -> SmallCStr {
38 if let Err(e) = ffi::CStr::from_bytes_with_nul(b) {
39 panic!("The string \"{}\" cannot be converted into a CStr: {}", s, e);
41 SmallCStr { data: SmallVec::from_slice(s.as_bytes()) }
46 pub fn as_c_str(&self) -> &ffi::CStr {
48 ffi::CStr::from_bytes_with_nul_unchecked(&self.data[..])
53 pub fn len_with_nul(&self) -> usize {
57 pub fn spilled(&self) -> bool {
62 impl Deref for SmallCStr {
63 type Target = ffi::CStr;
65 fn deref(&self) -> &ffi::CStr {
72 const TEXT: &str = "abcd";
73 let reference = ffi::CString::new(TEXT.to_string()).unwrap();
75 let scs = SmallCStr::new(TEXT);
77 assert_eq!(scs.len_with_nul(), TEXT.len() + 1);
78 assert_eq!(scs.as_c_str(), reference.as_c_str());
79 assert!(!scs.spilled());
84 const TEXT: &str = "";
85 let reference = ffi::CString::new(TEXT.to_string()).unwrap();
87 let scs = SmallCStr::new(TEXT);
89 assert_eq!(scs.len_with_nul(), TEXT.len() + 1);
90 assert_eq!(scs.as_c_str(), reference.as_c_str());
91 assert!(!scs.spilled());
96 const TEXT: &str = "01234567890123456789012345678901234567890123456789\
97 01234567890123456789012345678901234567890123456789\
98 01234567890123456789012345678901234567890123456789";
99 let reference = ffi::CString::new(TEXT.to_string()).unwrap();
101 let scs = SmallCStr::new(TEXT);
103 assert_eq!(scs.len_with_nul(), TEXT.len() + 1);
104 assert_eq!(scs.as_c_str(), reference.as_c_str());
105 assert!(scs.spilled());
111 let _ = SmallCStr::new("abcd\0def");