From e875305b29058bcf7243cddf814d3b4dd3508564 Mon Sep 17 00:00:00 2001 From: Joonas Javanainen Date: Wed, 26 Aug 2015 12:43:08 +0100 Subject: [PATCH] Overhaul ImStr constructors --- src/lib.rs | 24 +++++++++++++++--------- src/sliders.rs | 4 ++-- src/window.rs | 2 +- 3 files changed, 18 insertions(+), 12 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index c4fbc77..ac6d802 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -11,6 +11,7 @@ extern crate sdl2; use libc::{c_char, c_float, c_int, c_uchar}; use std::borrow::Cow; +use std::convert::From; use std::ffi::CStr; use std::fmt; use std::mem; @@ -52,10 +53,10 @@ pub struct ImGui; macro_rules! im_str { ($e:tt) => ({ let value = concat!($e, "\0"); - unsafe { ::imgui::ImStr::from_bytes(value.as_bytes()) } + unsafe { ::imgui::ImStr::from_bytes_unchecked(value.as_bytes()) } }); ($e:tt, $($arg:tt)*) => ({ - ::imgui::ImStr::from_fmt(format_args!($e, $($arg)*)) + ::imgui::ImStr::from(format!($e, $($arg)*)) }) } @@ -65,26 +66,31 @@ pub struct ImStr<'a> { } impl<'a> ImStr<'a> { - pub unsafe fn from_bytes(bytes: &'a [u8]) -> ImStr<'a> { + pub unsafe fn from_bytes_unchecked(bytes: &'a [u8]) -> ImStr<'a> { ImStr { bytes: Cow::Borrowed(bytes) } } - pub fn from_str(value: &str) -> ImStr<'a> { + fn as_ptr(&self) -> *const c_char { self.bytes.as_ptr() as *const c_char } +} + +impl<'a> From<&'a str> for ImStr<'a> { + fn from(value: &'a str) -> ImStr<'a> { let mut bytes: Vec = value.bytes().collect(); bytes.push(0); ImStr { bytes: Cow::Owned(bytes) } } - pub fn from_fmt(args: fmt::Arguments) -> ImStr<'a> { - let mut bytes = fmt::format(args).into_bytes(); - bytes.push(0); +} + +impl From for ImStr<'static> { + fn from(mut value: String) -> ImStr<'static> { + value.push('\0'); ImStr { - bytes: Cow::Owned(bytes) + bytes: Cow::Owned(value.into_bytes()) } } - fn as_ptr(&self) -> *const c_char { self.bytes.as_ptr() as *const c_char } } pub struct TextureHandle<'a> { diff --git a/src/sliders.rs b/src/sliders.rs index f1d89ef..ea80399 100644 --- a/src/sliders.rs +++ b/src/sliders.rs @@ -22,7 +22,7 @@ impl<'ui, 'p> SliderInt<'ui, 'p> { value: value, min: min, max: max, - display_format: unsafe { ImStr::from_bytes(b"%.0f\0") }, + display_format: unsafe { ImStr::from_bytes_unchecked(b"%.0f\0") }, _phantom: PhantomData } } @@ -60,7 +60,7 @@ impl<'ui, 'p> SliderFloat<'ui, 'p> { value: value, min: min, max: max, - display_format: unsafe { ImStr::from_bytes(b"%.3f\0") }, + display_format: unsafe { ImStr::from_bytes_unchecked(b"%.3f\0") }, power: 1.0, _phantom: PhantomData } diff --git a/src/window.rs b/src/window.rs index 2f5a8a2..0811a82 100644 --- a/src/window.rs +++ b/src/window.rs @@ -33,7 +33,7 @@ impl<'ui, 'p> Window<'ui, 'p> { pos_cond: ImGuiSetCond::empty(), size: (0.0, 0.0), size_cond: ImGuiSetCond::empty(), - name: unsafe { ImStr::from_bytes(b"Debug\0") }, + name: unsafe { ImStr::from_bytes_unchecked(b"Debug\0") }, opened: None, bg_alpha: -1.0, flags: ImGuiWindowFlags::empty(),