Skip to content

Commit 2776ce8

Browse files
committed
Merge remote-tracking branch 'benma/cstr2'
2 parents f0f6a73 + 7619d6b commit 2776ce8

File tree

5 files changed

+38
-93
lines changed

5 files changed

+38
-93
lines changed

src/rust/bitbox02/src/lib.rs

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -51,13 +51,14 @@ pub use bitbox02_sys::buffer_t;
5151
#[macro_use]
5252
pub mod util;
5353

54-
// ug_put_string displays a debug message on the screen for 3 sec.
5554
pub fn ug_put_string(x: i16, y: i16, input: &str, inverted: bool) {
56-
match str_to_cstr!(input, 128) {
57-
Ok(buf) => unsafe {
58-
bitbox02_sys::UG_PutString(x, y, buf.as_ptr() as *const _, inverted);
59-
},
60-
Err(msg) => screen_print_debug(msg, 3000),
55+
unsafe {
56+
bitbox02_sys::UG_PutString(
57+
x,
58+
y,
59+
crate::util::str_to_cstr_vec(input).unwrap().as_ptr(),
60+
inverted,
61+
);
6162
}
6263
}
6364

@@ -99,16 +100,11 @@ pub fn delay(duration: Duration) {
99100
}
100101

101102
pub fn screen_print_debug(msg: &str, duration: i32) {
102-
match str_to_cstr!(msg, 200) {
103-
Ok(cstr) => unsafe {
104-
bitbox02_sys::screen_print_debug(cstr.as_ptr() as *const _, duration)
105-
},
106-
Err(errmsg) => unsafe {
107-
bitbox02_sys::screen_print_debug(
108-
str_to_cstr_force!(errmsg, 200).as_ptr() as *const _,
109-
duration,
110-
)
111-
},
103+
unsafe {
104+
bitbox02_sys::screen_print_debug(
105+
crate::util::str_to_cstr_vec(msg).unwrap().as_ptr(),
106+
duration,
107+
)
112108
}
113109
}
114110

src/rust/bitbox02/src/memory.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,12 +35,10 @@ pub fn get_device_name() -> String {
3535
.into()
3636
}
3737

38-
/// `name.as_bytes()` must be smaller or equal to
39-
/// `DEVICE_NAME_MAX_LEN`, otherwise this function panics.
4038
pub fn set_device_name(name: &str) -> Result<(), Error> {
4139
match unsafe {
4240
bitbox02_sys::memory_set_device_name(
43-
crate::str_to_cstr_force!(name, DEVICE_NAME_MAX_LEN).as_ptr(),
41+
crate::util::str_to_cstr_vec(name).or(Err(Error))?.as_ptr(),
4442
)
4543
} {
4644
true => Ok(()),

src/rust/bitbox02/src/ui/types.rs

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
extern crate alloc;
1616
use alloc::boxed::Box;
17+
use alloc::vec::Vec;
1718

1819
use util::Survive;
1920

@@ -69,20 +70,18 @@ impl<'a> ConfirmParams<'a> {
6970
/// alive for as long as the C params live.
7071
pub(crate) fn to_c_params(
7172
&self,
72-
title_scatch: &'a mut [u8; MAX_LABEL_SIZE + 2],
73-
body_scratch: &'a mut [u8; MAX_LABEL_SIZE + 2],
73+
title_scatch: &'a mut Vec<u8>,
74+
body_scratch: &'a mut Vec<u8>,
7475
) -> Survive<'a, bitbox02_sys::confirm_params_t> {
7576
// We truncate at a bit higher than MAX_LABEL_SIZE, so the label component will correctly
7677
// truncate and append '...'.
7778
const TRUNCATE_SIZE: usize = MAX_LABEL_SIZE + 1;
78-
*title_scatch = crate::str_to_cstr_force!(
79-
crate::util::truncate_str(self.title, TRUNCATE_SIZE),
80-
TRUNCATE_SIZE
81-
);
82-
*body_scratch = crate::str_to_cstr_force!(
83-
crate::util::truncate_str(self.body, TRUNCATE_SIZE),
84-
TRUNCATE_SIZE
85-
);
79+
*title_scatch =
80+
crate::util::str_to_cstr_vec(crate::util::truncate_str(self.title, TRUNCATE_SIZE))
81+
.unwrap();
82+
*body_scratch =
83+
crate::util::str_to_cstr_vec(crate::util::truncate_str(self.body, TRUNCATE_SIZE))
84+
.unwrap();
8685
Survive::new(bitbox02_sys::confirm_params_t {
8786
title: title_scatch.as_ptr(),
8887
title_autowrap: self.title_autowrap,
@@ -113,16 +112,15 @@ impl<'a> TrinaryInputStringParams<'a> {
113112
#[cfg_attr(feature = "testing", allow(dead_code))]
114113
pub(crate) fn to_c_params(
115114
&self,
116-
title_scratch: &'a mut [u8; MAX_LABEL_SIZE + 2],
115+
title_scratch: &'a mut Vec<u8>,
117116
) -> Survive<'a, bitbox02_sys::trinary_input_string_params_t> {
118117
// We truncate at a bit higher than MAX_LABEL_SIZE, so the label component will correctly
119118
// truncate and append '...'.
120119
const TRUNCATE_SIZE: usize = MAX_LABEL_SIZE + 1;
121120

122-
*title_scratch = crate::str_to_cstr_force!(
123-
crate::util::truncate_str(self.title, TRUNCATE_SIZE),
124-
TRUNCATE_SIZE
125-
);
121+
*title_scratch =
122+
crate::util::str_to_cstr_vec(crate::util::truncate_str(self.title, TRUNCATE_SIZE))
123+
.unwrap();
126124

127125
Survive::new(bitbox02_sys::trinary_input_string_params_t {
128126
title: title_scratch.as_ptr(),

src/rust/bitbox02/src/ui/ui.rs

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
// See the License for the specific language governing permissions and
1414
// limitations under the License.
1515

16-
use super::types::MAX_LABEL_SIZE;
1716
pub use super::types::{
1817
AcceptRejectCb, ConfirmParams, ContinueCancelCb, Font, MenuParams, SelectWordCb, TrinaryChoice,
1918
TrinaryChoiceCb, TrinaryInputStringParams,
@@ -101,7 +100,7 @@ where
101100
Box::into_raw(Box::new(cb)) as *mut c_void,
102101
),
103102
};
104-
let mut title_scratch = [0; MAX_LABEL_SIZE + 2];
103+
let mut title_scratch = Vec::new();
105104
let component = unsafe {
106105
bitbox02_sys::trinary_input_string_create(
107106
&params.to_c_params(&mut title_scratch).data, // title copied in C
@@ -141,8 +140,8 @@ where
141140
let mut callback = Box::from_raw(param as *mut F2);
142141
callback(result);
143142
}
144-
let mut title_scratch = [0; MAX_LABEL_SIZE + 2];
145-
let mut body_scratch = [0; MAX_LABEL_SIZE + 2];
143+
let mut title_scratch = Vec::new();
144+
let mut body_scratch = Vec::new();
146145
let component = unsafe {
147146
bitbox02_sys::confirm_create(
148147
&params
@@ -184,7 +183,7 @@ where
184183

185184
let component = unsafe {
186185
bitbox02_sys::status_create(
187-
crate::str_to_cstr_force!(text, MAX_LABEL_SIZE).as_ptr(), // copied in C
186+
crate::util::str_to_cstr_vec(text).unwrap().as_ptr(), // copied in C
188187
status_success,
189188
Some(c_callback::<F>),
190189
Box::into_raw(Box::new(callback)) as *mut _, // passed to c_callback as `param`.
@@ -244,10 +243,10 @@ pub fn menu_create(params: MenuParams<'_>) -> Component<'_> {
244243
//
245244
// Step 1: create the C strings. This var has to be alive until after menu_create() finishes,
246245
// otherwise the pointers we send to menu_create() will be invalid.
247-
let words: Vec<[u8; 101]> = params
246+
let words: Vec<Vec<u8>> = params
248247
.words
249248
.iter()
250-
.map(|word| crate::str_to_cstr_force!(word, 100))
249+
.map(|word| crate::util::str_to_cstr_vec(word).unwrap())
251250
.collect();
252251
// Step two: collect pointers. This var also has to be valid until menu_create() finishes, or
253252
// the pointer will be invalid.
@@ -333,10 +332,10 @@ pub fn trinary_choice_create<'a>(
333332
let chosen_cb_param = Box::into_raw(Box::new(chosen_callback)) as *mut c_void;
334333
let component = unsafe {
335334
bitbox02_sys::trinary_choice_create(
336-
crate::str_to_cstr_force!(message, MAX_LABEL_SIZE).as_ptr(), // copied in C
337-
crate::str_to_cstr_force!(label_left, MAX_LABEL_SIZE).as_ptr(), // copied in C
338-
crate::str_to_cstr_force!(label_middle, MAX_LABEL_SIZE).as_ptr(), // copied in C
339-
crate::str_to_cstr_force!(label_right, MAX_LABEL_SIZE).as_ptr(), // copied in C
335+
crate::util::str_to_cstr_vec(message).unwrap().as_ptr(), // copied in C
336+
crate::util::str_to_cstr_vec(label_left).unwrap().as_ptr(), // copied in C
337+
crate::util::str_to_cstr_vec(label_middle).unwrap().as_ptr(), // copied in C
338+
crate::util::str_to_cstr_vec(label_right).unwrap().as_ptr(), // copied in C
340339
Some(c_chosen_cb as _),
341340
chosen_cb_param,
342341
core::ptr::null_mut(), // parent component, there is no parent.
@@ -419,7 +418,7 @@ pub fn trinary_input_string_set_input(component: &mut Component, word: &str) {
419418
unsafe {
420419
bitbox02_sys::trinary_input_string_set_input(
421420
component.component,
422-
crate::str_to_cstr_force!(word, bitbox02_sys::INPUT_STRING_MAX_SIZE as usize).as_ptr(),
421+
crate::util::str_to_cstr_vec(word).unwrap().as_ptr(),
423422
)
424423
}
425424
}
@@ -439,7 +438,7 @@ pub fn screen_stack_pop_all() {
439438
pub fn progress_create<'a>(title: &str) -> Component<'a> {
440439
let component = unsafe {
441440
bitbox02_sys::progress_create(
442-
crate::str_to_cstr_force!(title, MAX_LABEL_SIZE).as_ptr(), // copied in C
441+
crate::util::str_to_cstr_vec(title).unwrap().as_ptr(), // copied in C
443442
)
444443
};
445444

src/rust/bitbox02/src/util.rs

Lines changed: 0 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -31,52 +31,6 @@ pub unsafe fn str_from_null_terminated_ptr<'a>(ptr: *const u8) -> Result<&'a str
3131
core::ffi::CStr::from_ptr(ptr.cast()).to_str().or(Err(()))
3232
}
3333

34-
/// Macro for creating a stack allocated buffer with the content of a string and a null-terminator
35-
///
36-
/// Example usage:
37-
///
38-
/// ```
39-
/// # #[macro_use] extern crate bitbox02;
40-
/// let name = "sample_string";
41-
/// let buf = match str_to_cstr!(name, 50) {
42-
/// Ok(buf) => buf,
43-
/// Err(msg) => panic!("{}", msg),
44-
/// };
45-
/// ```
46-
#[macro_export]
47-
macro_rules! str_to_cstr {
48-
($input:expr, $len:expr) => {{
49-
let mut buf = [0u8; $len + 1];
50-
if !$input.is_ascii() {
51-
Err("non-ascii input")
52-
} else {
53-
let len = core::cmp::min($len, $input.len());
54-
{
55-
// Take a slice of buf of the correct length
56-
let buf = &mut buf[..len];
57-
// Take a slice of input of the correct length
58-
let input = &$input.as_bytes()[..len];
59-
buf.copy_from_slice(input);
60-
}
61-
if $input.len() > len {
62-
Err("str is too long")
63-
} else {
64-
Ok(buf)
65-
}
66-
}
67-
}};
68-
}
69-
70-
#[macro_export]
71-
macro_rules! str_to_cstr_force {
72-
($input:expr, $len:expr) => {
73-
match $crate::str_to_cstr!($input, $len) {
74-
Ok(buf) => buf,
75-
Err(msg) => panic!("{}", msg),
76-
}
77-
};
78-
}
79-
8034
/// truncate_str truncates string `s` to `len` chars. If `s` is
8135
/// shorter than `len`, the string is returned unchanged (no panics).
8236
pub fn truncate_str(s: &str, len: usize) -> &str {

0 commit comments

Comments
 (0)