Use String::from_utf8_lossy for error/trace.

Try to use the original message even if there are invalid
characters.
This commit is contained in:
gwenn 2016-05-07 12:08:57 +02:00
parent 254a0b4cd8
commit b20168fe9c
2 changed files with 10 additions and 14 deletions

View File

@ -101,8 +101,7 @@ pub type Result<T> = result::Result<T, Error>;
unsafe fn errmsg_to_string(errmsg: *const c_char) -> String { unsafe fn errmsg_to_string(errmsg: *const c_char) -> String {
let c_slice = CStr::from_ptr(errmsg).to_bytes(); let c_slice = CStr::from_ptr(errmsg).to_bytes();
let utf8_str = str::from_utf8(c_slice); String::from_utf8_lossy(c_slice).into_owned()
utf8_str.unwrap_or("Invalid string encoding").to_owned()
} }
fn str_to_cstring(s: &str) -> Result<CString> { fn str_to_cstring(s: &str) -> Result<CString> {

View File

@ -27,9 +27,8 @@ pub unsafe fn config_log(callback: Option<fn(c_int, &str)>) -> Result<()> {
let c_slice = unsafe { CStr::from_ptr(msg).to_bytes() }; let c_slice = unsafe { CStr::from_ptr(msg).to_bytes() };
let callback: fn(c_int, &str) = unsafe { mem::transmute(p_arg) }; let callback: fn(c_int, &str) = unsafe { mem::transmute(p_arg) };
if let Ok(s) = str::from_utf8(c_slice) { let s = String::from_utf8_lossy(c_slice);
callback(err, s); callback(err, &s);
}
} }
let rc = match callback { let rc = match callback {
@ -70,9 +69,8 @@ impl Connection {
unsafe extern "C" fn trace_callback(p_arg: *mut c_void, z_sql: *const c_char) { unsafe extern "C" fn trace_callback(p_arg: *mut c_void, z_sql: *const c_char) {
let trace_fn: fn(&str) = mem::transmute(p_arg); let trace_fn: fn(&str) = mem::transmute(p_arg);
let c_slice = CStr::from_ptr(z_sql).to_bytes(); let c_slice = CStr::from_ptr(z_sql).to_bytes();
if let Ok(s) = str::from_utf8(c_slice) { let s = String::from_utf8_lossy(c_slice);
trace_fn(s); trace_fn(&s);
}
} }
let c = self.db.borrow_mut(); let c = self.db.borrow_mut();
@ -96,13 +94,12 @@ impl Connection {
nanoseconds: u64) { nanoseconds: u64) {
let profile_fn: fn(&str, Duration) = mem::transmute(p_arg); let profile_fn: fn(&str, Duration) = mem::transmute(p_arg);
let c_slice = CStr::from_ptr(z_sql).to_bytes(); let c_slice = CStr::from_ptr(z_sql).to_bytes();
if let Ok(s) = str::from_utf8(c_slice) { let s = String::from_utf8_lossy(c_slice);
const NANOS_PER_SEC: u64 = 1_000_000_000; const NANOS_PER_SEC: u64 = 1_000_000_000;
let duration = Duration::new(nanoseconds / NANOS_PER_SEC, let duration = Duration::new(nanoseconds / NANOS_PER_SEC,
(nanoseconds % NANOS_PER_SEC) as u32); (nanoseconds % NANOS_PER_SEC) as u32);
profile_fn(s, duration); profile_fn(&s, duration);
}
} }
let c = self.db.borrow_mut(); let c = self.db.borrow_mut();