fix(detect): fix possible undefined behavior

This commit is contained in:
Federico Terzi 2021-08-09 22:19:29 +02:00
parent bb4e88c445
commit c68d59797e

View File

@ -24,10 +24,9 @@ pub struct Keymap {
impl Keymap { impl Keymap {
pub fn new(context: &Context, rmlvo: Option<KeyboardConfig>) -> Result<Keymap> { pub fn new(context: &Context, rmlvo: Option<KeyboardConfig>) -> Result<Keymap> {
let names = rmlvo.map(|rmlvo| Self::generate_names(rmlvo)); let names = rmlvo.map(Self::generate_names);
let names_ptr = names.map_or(std::ptr::null(), |names| &names);
let names_ptr = names.map_or(std::ptr::null(), |(names, _owned)| &names);
let raw_keymap = unsafe { let raw_keymap = unsafe {
xkb_keymap_new_from_names(context.get_handle(), names_ptr, XKB_KEYMAP_COMPILE_NO_FLAGS) xkb_keymap_new_from_names(context.get_handle(), names_ptr, XKB_KEYMAP_COMPILE_NO_FLAGS)
}; };
@ -48,7 +47,7 @@ impl Keymap {
self.keymap self.keymap
} }
fn generate_names(rmlvo: KeyboardConfig) -> xkb_rule_names { fn generate_names(rmlvo: KeyboardConfig) -> (xkb_rule_names, OwnedRawKeyboardConfig) {
let rules = rmlvo let rules = rmlvo
.rules .rules
.map(|s| CString::new(s).expect("unable to create CString for keymap")); .map(|s| CString::new(s).expect("unable to create CString for keymap"));
@ -65,13 +64,23 @@ impl Keymap {
.options .options
.map(|s| CString::new(s).expect("unable to create CString for keymap")); .map(|s| CString::new(s).expect("unable to create CString for keymap"));
xkb_rule_names { let owned_config = OwnedRawKeyboardConfig {
rules: rules.map_or(std::ptr::null(), |s| s.as_ptr()), rules,
model: model.map_or(std::ptr::null(), |s| s.as_ptr()), model,
layout: layout.map_or(std::ptr::null(), |s| s.as_ptr()), layout,
variant: variant.map_or(std::ptr::null(), |s| s.as_ptr()), variant,
options: options.map_or(std::ptr::null(), |s| s.as_ptr()), options,
} };
let xkb_config = xkb_rule_names {
rules: owned_config.rules.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
model: owned_config.model.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
layout: owned_config.layout.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
variant: owned_config.variant.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
options: owned_config.options.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
};
(xkb_config, owned_config)
} }
} }
@ -88,3 +97,11 @@ pub enum KeymapError {
#[error("could not create xkb keymap")] #[error("could not create xkb keymap")]
FailedCreation(), FailedCreation(),
} }
struct OwnedRawKeyboardConfig {
rules: Option<CString>,
model: Option<CString>,
layout: Option<CString>,
variant: Option<CString>,
options: Option<CString>,
}