Skip to content

Commit

Permalink
fix cstring macro usage; fixes #19
Browse files Browse the repository at this point in the history
- remove `cstring_mut` function
- update examples
  • Loading branch information
joseluis committed Mar 27, 2022
1 parent 5ba1b42 commit 2071d9f
Show file tree
Hide file tree
Showing 17 changed files with 101 additions and 85 deletions.
8 changes: 4 additions & 4 deletions examples/direct/examples/cursor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,16 @@ fn main() -> NcResult<()> {
for _n in 0..40 {
ncd.flush()?;
sleep![0, 30];
channels.set_fg_rgb8(
channels.set_fg_rgb([
rng.gen_range(0x66..=0xEE),
rng.gen_range(0x66..=0xEE),
rng.gen_range(0x66..=0xEE),
);
channels.set_bg_rgb8(
]);
channels.set_bg_rgb([
rng.gen_range(0..=0x9),
rng.gen_range(0..=0x9),
rng.gen_range(0..=0x9),
);
]);
ncd.putstr(channels, ".")?;
}

Expand Down
2 changes: 1 addition & 1 deletion examples/direct/examples/image-c.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ fn render_image(ncd: &mut NcDirect, blit: NcBlitter) {
unsafe {
if ncdirect_render_image(
ncd,
cstring![image_path],
cstring![image_path].as_ptr(),
NCALIGN_CENTER,
blit.into(),
NCSCALE_NONE,
Expand Down
10 changes: 5 additions & 5 deletions examples/poc/examples/kittyzapper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@ use libnotcurses_sys::*;
fn main() -> NcResult<()> {
let ncd = unsafe { NcDirect::new()? };

ncd.set_fg_rgb8(100, 100, 100)?;
ncd.set_bg_rgb8(0xff, 0xff, 0xff)?;
ncd.set_fg_rgb([100, 100, 100])?;
ncd.set_bg_rgb([0xff, 0xff, 0xff])?;
printf!("a");
ncd.set_bg_rgb8(0, 0, 0)?;
ncd.set_bg_rgb([0, 0, 0])?;
printf!("b");
printf!(" ");
printf!(" ");
ncd.set_bg_rgb8(0, 0, 1)?;
ncd.set_bg_rgb([0, 0, 1])?;
printf!("c");
printf!(" ");
printf!(" ");
ncd.set_bg_rgb8(0xff, 0xff, 0xff)?;
ncd.set_bg_rgb([0xff, 0xff, 0xff])?;
printf!("d");
printf!("\n");

Expand Down
8 changes: 4 additions & 4 deletions examples/poc/examples/menu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@ fn main() -> NcResult<()> {

let mut mopts = NcMenuOptions::new(&mut sections);
// FIXME: better API
c_api::ncchannels_set_fg_rgb(&mut mopts.headerchannels, 0x00ff00);
c_api::ncchannels_set_bg_rgb(&mut mopts.headerchannels, 0x440000);
c_api::ncchannels_set_fg_rgb(&mut mopts.sectionchannels, 0xb0d700);
c_api::ncchannels_set_bg_rgb(&mut mopts.sectionchannels, 0x002200);
c_api::ncchannels_set_fg_rgb(&mut mopts.headerchannels, 0x00ff00_u32);
c_api::ncchannels_set_bg_rgb(&mut mopts.headerchannels, 0x440000_u32);
c_api::ncchannels_set_fg_rgb(&mut mopts.sectionchannels, 0xb0d700_u32);
c_api::ncchannels_set_bg_rgb(&mut mopts.sectionchannels, 0x002200_u32);

let stdplane = unsafe { nc.stdplane() };
let (dim_y, _dim_x) = stdplane.dim_yx();
Expand Down
9 changes: 6 additions & 3 deletions src/cell/methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ impl NcCell {
#[inline]
pub fn from_char(plane: &mut NcPlane, ch: char) -> NcResult<Self> {
let mut cell = Self::new();
let res = unsafe { nccell_load(plane, &mut cell, cstring![ch.to_string()]) };
let cs = cstring![ch.to_string()];
let res = unsafe { nccell_load(plane, &mut cell, cs.as_ptr()) };
if res == NCRESULT_ERR {
return Err(NcError::new());
}
Expand All @@ -43,7 +44,8 @@ impl NcCell {
#[inline]
pub fn from_str(plane: &mut NcPlane, string: &str) -> NcResult<Self> {
let mut cell = Self::new();
let res = unsafe { nccell_load(plane, &mut cell, cstring![string]) };
let cs = cstring![string];
let res = unsafe { nccell_load(plane, &mut cell, cs.as_ptr()) };
if res == NCRESULT_ERR {
return Err(NcError::new());
}
Expand All @@ -62,7 +64,8 @@ impl NcCell {
/// The styling of the cell is left untouched, but any resources are released.
/// *C style function: [nccell_load()][c_api::nccell_load].*
pub fn load(plane: &mut NcPlane, cell: &mut NcCell, egc: &str) -> NcResult<u32> {
let bytes = unsafe { c_api::nccell_load(plane, cell, cstring![egc]) };
let cs = cstring![egc];
let bytes = unsafe { c_api::nccell_load(plane, cell, cs.as_ptr()) };
error![
bytes,
&format!["NcCell.load(NcPlane, NcCell, {:?})", egc],
Expand Down
9 changes: 6 additions & 3 deletions src/cell/reimplemented.rs
Original file line number Diff line number Diff line change
Expand Up @@ -458,7 +458,8 @@ pub fn nccell_prime(
) -> NcResult_i32 {
cell.stylemask = style.into();
cell.channels = channels.into();
unsafe { c_api::nccell_load(plane, cell, cstring![gcluster]) }
let cs = cstring![gcluster];
unsafe { c_api::nccell_load(plane, cell, cs.as_ptr()) }
}

/// Loads up six cells with the `EGC`s necessary to draw a box.
Expand All @@ -485,8 +486,10 @@ pub fn nccells_load_box(
) -> NcResult_i32 {
assert![gcluster.len() >= 6]; // DEBUG

// TODO: CHECK: mutable copy for pointer arithmetics:
let mut gclu = cstring![gcluster];
// CHECK: mutable copy for pointer arithmetics

let cs = cstring![gcluster];
let mut gclu = cs.as_ptr();

let mut ulen: NcResult_i32 = nccell_prime(plane, ul, gcluster, style.into(), channels.into());

Expand Down
14 changes: 9 additions & 5 deletions src/direct/methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,11 @@ impl NcDirect {
max_y: u32,
max_x: u32,
) -> NcResult<&'a mut NcPlane> {
let cs = cstring![filename];
let res = unsafe {
c_api::ncdirect_render_frame(
self,
cstring![filename],
cs.as_ptr(),
blitter.into().into(),
scale.into().into(),
max_y as i32,
Expand Down Expand Up @@ -138,11 +139,12 @@ impl NcDirect {
blitter: impl Into<NcBlitter> + Copy,
scale: impl Into<NcScale> + Copy,
) -> NcResult<()> {
let cs = cstring![filename];
error![
unsafe {
c_api::ncdirect_render_image(
self,
cstring![filename],
cs.as_ptr(),
align.into().into(),
blitter.into().into(),
scale.into().into(),
Expand Down Expand Up @@ -624,8 +626,9 @@ impl NcDirect {
///
/// *C style function: [ncdirect_putstr()][c_api::ncdirect_putstr].*
pub fn putstr(&mut self, channels: impl Into<NcChannels> + Copy, string: &str) -> NcResult<()> {
let cs = cstring![string];
error![
unsafe { c_api::ncdirect_putstr(self, channels.into().into(), cstring![string]) },
unsafe { c_api::ncdirect_putstr(self, channels.into().into(), cs.as_ptr()) },
&format!("NcDirect.putstr({:0X}, {:?})", channels.into(), string)
]
}
Expand All @@ -641,9 +644,10 @@ impl NcDirect {
///
/// *C style function: [ncdirect_readline()][c_api::ncdirect_readline].*
//
// FIXME: memory leak still reported by valgrind
// CHECK if memory leak still reported by valgrind
pub fn readline(&mut self, prompt: &str) -> NcResult<String> {
let res = unsafe { c_api::ncdirect_readline(self, cstring![prompt]) };
let cs = cstring![prompt];
let res = unsafe { c_api::ncdirect_readline(self, cs.as_ptr()) };
if !res.is_null() {
return Ok(rstring_free![res]);
} else {
Expand Down
12 changes: 8 additions & 4 deletions src/direct/reimplemented.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,10 +136,12 @@ pub fn ncdirect_hline_interp(
h1: impl Into<NcChannels_u64>,
h2: impl Into<NcChannels_u64>,
) -> NcResult_i32 {
let cs = cstring![egc];

#[cfg(any(target_arch = "armv7l", target_arch = "i686"))]
let egc_ptr = cstring![egc] as *const i8;
let egc_ptr = cs.as_ptr() as *const i8;
#[cfg(not(any(target_arch = "armv7l", target_arch = "i686")))]
let egc_ptr = cstring![egc];
let egc_ptr = cs.as_ptr();

unsafe { crate::c_api::ffi::ncdirect_hline_interp(ncd, egc_ptr, len, h1.into(), h2.into()) }
}
Expand All @@ -163,10 +165,12 @@ pub fn ncdirect_vline_interp(
h1: impl Into<NcChannels_u64>,
h2: impl Into<NcChannels_u64>,
) -> NcResult_i32 {
let cs = cstring![egc];

#[cfg(any(target_arch = "armv7l", target_arch = "i686"))]
let egc_ptr = cstring![egc] as *const i8;
let egc_ptr = cs.as_ptr() as *const i8;
#[cfg(not(any(target_arch = "armv7l", target_arch = "i686")))]
let egc_ptr = cstring![egc];
let egc_ptr = cs.as_ptr();

unsafe { crate::c_api::ffi::ncdirect_vline_interp(ncd, egc_ptr, len, h1.into(), h2.into()) }
}
25 changes: 5 additions & 20 deletions src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,24 +100,7 @@ macro_rules! visual_render_sleep {
#[doc(hidden)]
macro_rules! cstring {
($s:expr) => {
// NOTE: The returned pointer will be valid for as long as self is
// CHECK does this live long enough in all circumstances?
std::ffi::CString::new($s).unwrap().as_ptr()
};
}

/// Converts an `&str` into `*mut c_char`.
///
/// See [`Cstring`].
#[macro_export]
#[doc(hidden)]
macro_rules! cstring_mut {
($s:expr) => {
// we can't use this without taking the responsibility of deallocating:
std::ffi::CString::new($s).unwrap().into_raw()

// another option:
// unsafe { crate::c_api::libc::strdup(crate::cstring![$s]) }
std::ffi::CString::new($s).unwrap()
};
}

Expand Down Expand Up @@ -150,10 +133,12 @@ macro_rules! rstring_free {
#[doc(hidden)]
macro_rules! printf {
($s:expr) => {
unsafe { crate::c_api::libc::printf(cstring![$s]) }
let cs = cstring![$s];
unsafe { crate::c_api::libc::printf(cs.as_ptr()) }
};
($s:expr $(, $opt:expr)*) => {
unsafe { crate::c_api::libc::printf(cstring![$s], $($opt),*) }
let cs = cstring![$s];
unsafe { crate::c_api::libc::printf(cs.as_ptr(), $($opt),*) }
};
}

Expand Down
11 changes: 6 additions & 5 deletions src/metric.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! `NcMetric`

pub(crate) mod reimplemented {
use crate::{c_api::ffi, cstring_mut, rstring, NcError, NcResult};
use crate::{c_api::ffi, cstring, rstring, NcError, NcResult};

// TODO: clarify, update and visibilize doc-comments

Expand Down Expand Up @@ -44,13 +44,14 @@ pub(crate) mod reimplemented {
mult: u64,
uprefix: i32,
) -> NcResult<&str> {
let buf = cstring_mut![buf];
let res = unsafe { ffi::ncnmetric(val, s, decimal, buf, omitdec, mult, uprefix) };
let cbuf = cstring![buf];
let res =
unsafe { ffi::ncnmetric(val, s, decimal, cbuf.into_raw(), omitdec, mult, uprefix) };

if res.is_null() {
Err(NcError::new_msg(&format![
"ncmetric({}, {}, {}, {:?}, {}, {}, {})",
val, s, decimal, buf, omitdec, mult, uprefix
"ncmetric({}, {}, {:?}, {}, {}, {})",
val, s, decimal, omitdec, mult, uprefix
]))
} else {
Ok(rstring![res])
Expand Down
9 changes: 6 additions & 3 deletions src/notcurses/methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -533,8 +533,9 @@ impl Nc {
/// *C style function: [notcurses_lex_blitter()][c_api::notcurses_lex_blitter].*
pub fn lex_blitter(blitter_str: &str) -> NcResult<NcBlitter> {
let mut blitter = 0;
let cs = cstring![blitter_str];
error![
unsafe { c_api::notcurses_lex_blitter(cstring![blitter_str], &mut blitter) },
unsafe { c_api::notcurses_lex_blitter(cs.as_ptr(), &mut blitter) },
"Invalid blitter name",
blitter.into()
]
Expand All @@ -547,16 +548,18 @@ impl Nc {
///
/// *C style function: [notcurses_lex_margins()][c_api::notcurses_lex_margins].*
pub fn lex_margins(margins_str: &str, options: &mut NcOptions) -> NcResult<()> {
error![unsafe { c_api::notcurses_lex_margins(cstring![margins_str], options) }]
let cs = cstring![margins_str];
error![unsafe { c_api::notcurses_lex_margins(cs.as_ptr(), options) }]
}

/// Returns an [`NcScale`] from a string representation.
///
/// *C style function: [notcurses_lex_scalemode()][c_api::notcurses_lex_scalemode].*
pub fn lex_scalemode(scale_str: &str) -> NcResult<NcScale> {
let mut scale = 0;
let cs = cstring![scale_str];
error![
unsafe { c_api::notcurses_lex_scalemode(cstring![scale_str], &mut scale) },
unsafe { c_api::notcurses_lex_scalemode(cs.as_ptr(), &mut scale) },
"",
scale.into()
]
Expand Down
15 changes: 6 additions & 9 deletions src/plane/methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -600,10 +600,11 @@ impl NcPlane {
stylemask: impl Into<NcStyle> + Copy,
channels: impl Into<NcChannels> + Copy,
) -> NcResult<u32> {
let cs = cstring![egc];
let res = unsafe {
c_api::ncplane_set_base(
self,
cstring![egc],
cs.as_ptr(),
stylemask.into().into(),
channels.into().0,
)
Expand Down Expand Up @@ -929,14 +930,9 @@ impl NcPlane {
///
/// *C style function: [ncplane_puttext()][c_api::ncplane_puttext].*
pub fn puttext(&mut self, y: u32, align: impl Into<NcAlign>, string: &str) -> NcResult<u32> {
let cs = cstring![string];
let res = unsafe {
c_api::ncplane_puttext(
self,
y as i32,
align.into().into(),
cstring![string],
null_mut(),
)
c_api::ncplane_puttext(self, y as i32, align.into().into(), cs.as_ptr(), null_mut())
};
error![res, &format!("NcPlane.puttext({:?})", string), res as u32]
}
Expand Down Expand Up @@ -1156,13 +1152,14 @@ impl NcPlane {
num_bytes: usize,
string: &str,
) -> NcResult<u32> {
let cs = cstring![string];
let res = unsafe {
c_api::ncplane_putnstr_aligned(
self,
y as i32,
align.into().into(),
num_bytes,
cstring![string],
cs.as_ptr(),
)
};
error![
Expand Down

0 comments on commit 2071d9f

Please sign in to comment.