[librsvg: 3/14] Factor out an util::utf8_cstr() to borrow a &str from a C char *



commit ff0c578ff30f13019f9e2ba9e63f46e9f91806d9
Author: Federico Mena Quintero <federico gnome org>
Date:   Wed Jan 24 10:58:56 2018 -0600

    Factor out an util::utf8_cstr() to borrow a &str from a C char *

 rust/src/opacity.rs      |  5 ++---
 rust/src/property_bag.rs |  5 ++---
 rust/src/util.rs         | 16 ++++++++++++++++
 3 files changed, 20 insertions(+), 6 deletions(-)
---
diff --git a/rust/src/opacity.rs b/rust/src/opacity.rs
index f8d1806..dd813f4 100644
--- a/rust/src/opacity.rs
+++ b/rust/src/opacity.rs
@@ -4,11 +4,11 @@
 use ::cssparser::{Parser, ParserInput, Token};
 use ::libc;
 
-use std::ffi::CStr;
 use std::str::FromStr;
 
 use parsers::ParseError;
 use error::*;
+use util::utf8_cstr;
 
 // Keep this in sync with rsvg-css.h:RsvgOpacityKind
 #[repr(C)]
@@ -120,8 +120,7 @@ impl Opacity {
 
 #[no_mangle]
 pub extern fn rsvg_css_parse_opacity (string: *const libc::c_char) -> OpacitySpec {
-    // we can unwrap because libxml2 already validated this for UTF-8
-    let s = unsafe { CStr::from_ptr(string).to_str().unwrap() };
+    let s = unsafe { utf8_cstr(string) };
 
     OpacitySpec::from(Opacity::from_str(s))
 }
diff --git a/rust/src/property_bag.rs b/rust/src/property_bag.rs
index b05e84d..8671dec 100644
--- a/rust/src/property_bag.rs
+++ b/rust/src/property_bag.rs
@@ -1,9 +1,9 @@
 use glib::translate::*;
 use libc;
-use std::ffi::CStr;
 
 use error::*;
 use parsers::Parse;
+use util::utf8_cstr;
 
 pub type FfiRsvgPropertyBag = *mut libc::c_void;
 
@@ -44,8 +44,7 @@ impl PropertyBag {
             if c_value.is_null() {
                 None
             } else {
-                // we can unwrap because libxml2 already validated this for UTF-8
-                Some(CStr::from_ptr(c_value).to_str().unwrap())
+                Some(utf8_cstr(c_value))
             }
         }
     }
diff --git a/rust/src/util.rs b/rust/src/util.rs
index 4cd80b2..9f33f67 100644
--- a/rust/src/util.rs
+++ b/rust/src/util.rs
@@ -1,3 +1,7 @@
+use libc;
+
+use std::ffi::CStr;
+
 // In paint servers (patterns, gradients, etc.), we have an
 // Option<String> for fallback names.  This is a utility function to
 // clone one of those.
@@ -14,3 +18,15 @@ pub const DBL_EPSILON: f64 = 1e-10;
 pub fn double_equals (a: f64, b: f64) -> bool {
     (a - b).abs () < DBL_EPSILON
 }
+
+/// Converts a `char *` which is known to be valid UTF-8 into a `&str`
+///
+/// The usual `from_glib_none(s)` allocates an owned String.  The
+/// purpose of `utf8_cstr()` is to get a temporary string slice into a
+/// C string which is already known to be valid UTF-8; for example,
+/// as for strings which come from `libxml2`.
+pub unsafe fn utf8_cstr<'a>(s: *const libc::c_char) -> &'a str {
+    assert!(!s.is_null());
+
+    CStr::from_ptr(s).to_str().unwrap()
+}


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]