Skip to content

Commit

Permalink
handle nuls differently after PR gyscos#786
Browse files Browse the repository at this point in the history
  • Loading branch information
correabuscar committed Jun 5, 2024
1 parent fa96654 commit 94c23e6
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 29 deletions.
12 changes: 8 additions & 4 deletions cursive-core/src/buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ impl CellWidth {
match width {
1 => CellWidth::Single,
2 => CellWidth::Double,
_ => panic!("expected width of 1 or 2 only."),
n => panic!("expected width of 1 or 2 only. Got {n}."),
}
}

Expand Down Expand Up @@ -182,9 +182,13 @@ impl PrintBuffer {
// Fill our active buffer
// TODO: Use some WithWidth(&str, usize) to not re-compute width a thousand times
for g in text.graphemes(true) {
let width = g.width();
self.set_cell(pos, g, width, style);
pos.x += width;
// Delete nuls because they have width 0 which would cause an exit(101)
// which is a panic but to see it you've to redir stderr to a file (with ncurses)
if "\0" != g {
let width = g.width();
self.set_cell(pos, g, width, style);
pos.x += width;
}
}
}

Expand Down
28 changes: 3 additions & 25 deletions cursive/src/backends/curses/n.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,35 +402,13 @@ impl backend::Backend for Backend {
}

fn print(&self, text: &str) {
// Remove '\0' from &str or else nothing would get printed
// As for why delete instead of replace with eg. space, see:
// https://github.com/gyscos/cursive/pull/778#discussion_r1613859129
let text = delete_nuls(text);
let len = text.len() as i32;
// &str is assured it doesn't contain \0 aka nuls here due to PR 786
// thus we can ignore the return value here
// Ignore the value to avoid warning: unused `Result` that must be used
let _ = ncurses::addnstr(&text, len);
let _ = ncurses::addstr(&text);
}
}

fn delete_nuls<'a>(text: &'a str) -> Cow<'a, str> {
if text.contains('\0') {
Cow::Owned(text.replace('\0', ""))
} else {
Cow::Borrowed(text)
}
}

#[test]
fn test_print_at_rep_nul_char_in_string() {
let text = "Some\0thing with \0nul\0s\0 in \0it";
let expected = "Something with nuls in it";
assert_eq!(expected, delete_nuls(text));

let backend = Backend::init().unwrap();
// This doesn't panic, it replaces the \0-es with nothing
backend.print("abc\0de\0f");
}

/// Returns the Key enum corresponding to the given ncurses event.
fn get_mouse_button(bare_event: i32) -> MouseButton {
match bare_event {
Expand Down

0 comments on commit 94c23e6

Please sign in to comment.