browser_window_c/
lib.rs

1mod bindings;
2
3use std::{error::Error, ffi::CStr, fmt, ptr, slice, str};
4
5pub use crate::bindings::*;
6
7/**************************************************************
8 * Implementations for C structs that are also useful in Rust *
9 *************************************************** */
10
11impl cbw_CStrSlice {
12	pub fn empty() -> Self {
13		Self {
14			len: 0,
15			data: ptr::null(),
16		}
17	}
18}
19
20impl From<&str> for cbw_CStrSlice {
21	fn from(string: &str) -> Self {
22		Self {
23			data: string.as_bytes().as_ptr() as _,
24			len: string.len() as _,
25		}
26	}
27}
28
29impl<'a> Into<&'a str> for cbw_CStrSlice {
30	fn into(self) -> &'a str {
31		let raw: &[u8] = unsafe { slice::from_raw_parts(self.data as _, self.len as _) };
32
33		#[cfg(debug_assertions)]
34		return str::from_utf8(raw).expect("Invalid UTF-8");
35		#[cfg(not(debug_assertions))]
36		return unsafe { str::from_utf8_unchecked(raw) };
37	}
38}
39
40impl Into<String> for cbw_CStrSlice {
41	fn into(self) -> String {
42		let str: &str = self.into();
43
44		str.to_owned()
45	}
46}
47
48impl cbw_StrSlice {
49	pub fn empty() -> Self {
50		Self {
51			len: 0,
52			data: ptr::null_mut(),
53		}
54	}
55}
56
57impl<'a> Into<&'a str> for cbw_StrSlice {
58	fn into(self) -> &'a str {
59		let raw: &[u8] = unsafe { slice::from_raw_parts(self.data as _, self.len as _) };
60
61		#[cfg(debug_assertions)]
62		return str::from_utf8(raw).expect("Invalid UTF-8");
63		#[cfg(not(debug_assertions))]
64		return unsafe { str::from_utf8_unchecked(raw) };
65	}
66}
67
68impl Into<String> for cbw_StrSlice {
69	fn into(self) -> String {
70		let str: &str = self.into();
71
72		str.to_owned()
73	}
74}
75
76impl Error for cbw_Err {
77	fn source(&self) -> Option<&(dyn Error + 'static)> { None }
78}
79
80impl fmt::Display for cbw_Err {
81	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82		unsafe {
83			let msg_ptr = (self.alloc_message.unwrap())(self.code, self.data);
84			let cstr = CStr::from_ptr(msg_ptr);
85			write!(f, "{}", cstr.to_string_lossy().as_ref())
86		}
87	}
88}