aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorC. Morgan Hamill <me@cmhamill.org>2015-03-19 22:18:10 +0100
committerC. Morgan Hamill <me@cmhamill.org>2015-03-20 13:58:46 +0100
commitfb76ee5ec2368c6f36d8a4f73234e614ee6ca0d0 (patch)
tree2953f772a504d0376a659522597e5e14fc48e91d
parent2c0a26ddf8385a4363cb8d4c54259abb33932ea8 (diff)
downloadmail-fb76ee5ec2368c6f36d8a4f73234e614ee6ca0d0.tar.gz
Add `ToStr` and `ToStaticStr` traits.
Allow easy mapping of borrowed C strings to borrowed strings with appropriate lifetimes. I have some doubts about this, as I'm not 100% on how lifetimes interact with the notmuch-provided strings yet.
-rw-r--r--src/lib.rs2
-rw-r--r--src/utils.rs31
2 files changed, 32 insertions, 1 deletions
diff --git a/src/lib.rs b/src/lib.rs
index 0f88f60..f490df7 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,4 +1,4 @@
-#![feature(libc)]
+#![feature(core, libc)]
extern crate libc;
#[macro_use]
diff --git a/src/utils.rs b/src/utils.rs
index 77e6e5e..ad8bcac 100644
--- a/src/utils.rs
+++ b/src/utils.rs
@@ -1,6 +1,37 @@
+use std::{
+ ffi,
+ str,
+};
+
+use libc;
+
pub trait NotmuchEnum {
type NotmuchT;
fn from_notmuch_t(notmuch_t: Self::NotmuchT) -> Self;
fn to_notmuch_t(self) -> Self::NotmuchT;
}
+
+pub trait ToStr {
+ fn to_str(&self) -> Result<&str, str::Utf8Error>;
+}
+
+impl ToStr for *const libc::c_char {
+ fn to_str(&self) -> Result<&str, str::Utf8Error> {
+ str::from_utf8(unsafe {
+ ffi::CStr::from_ptr(*self)
+ }.to_bytes())
+ }
+}
+
+pub trait ToStaticStr {
+ fn to_static_str(&self) -> Result<&'static str, str::Utf8Error>;
+}
+
+impl ToStaticStr for *const libc::c_char {
+ fn to_static_str(&self) -> Result<&'static str, str::Utf8Error> {
+ str::from_utf8(unsafe {
+ ffi::CStr::from_ptr(*self)
+ }.to_bytes())
+ }
+}