use smallvec::{smallvec, SmallVec}; use std::ffi::{CStr, CString, NulError};
/// Similar to `std::ffi::CString`, but avoids heap allocating if the string is /// small enough. Also guarantees it's input is UTF-8 -- used for cases where we /// need to pass a NUL-terminated string to SQLite, and we have a `&str`. #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] pub(crate) struct SmallCString(SmallVec<[u8; 16]>);
#[inline] pubfn as_str(&self) -> &str { self.debug_checks(); // Constructor takes a &str so this is safe. unsafe { std::str::from_utf8_unchecked(self.as_bytes_without_nul()) }
}
/// Get the bytes not including the NUL terminator. E.g. the bytes which /// make up our `str`: /// - `SmallCString::new("foo").as_bytes_without_nul() == b"foo"` /// - `SmallCString::new("foo").as_bytes_with_nul() == b"foo\0"` #[inline] pubfn as_bytes_without_nul(&self) -> &[u8] { self.debug_checks();
&self.0[..self.len()]
}
/// Get the bytes behind this str *including* the NUL terminator. This /// should never return an empty slice. #[inline] pubfn as_bytes_with_nul(&self) -> &[u8] { self.debug_checks();
&self.0
}
#[test] fn test_small_cstring() { // We don't go through the normal machinery for default, so make sure // things work.
assert_eq!(SmallCString::default().0, SmallCString::new("").unwrap().0);
assert_eq!(SmallCString::new("foo").unwrap().len(), 3);
assert_eq!(
SmallCString::new("foo").unwrap().as_bytes_with_nul(),
b"foo\0"
);
assert_eq!(
SmallCString::new("foo").unwrap().as_bytes_without_nul(),
b"foo",
);
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.