Skip to main content

leodos_libcfs/
util.rs

1//! General utility functions.
2
3use crate::error::{CfsError, OsalError, Result};
4use core::ffi::CStr;
5use heapless::CString;
6use heapless::String;
7
8/// Converts a `&str` to a null-terminated `CString<N>`.
9pub fn cstring<const N: usize>(s: &str) -> Result<CString<N>> {
10    let mut c = CString::new();
11    c.extend_from_bytes(s.as_bytes())
12        .map_err(|_| CfsError::Osal(OsalError::NameTooLong))?;
13    Ok(c)
14}
15
16/// Converts a NUL-terminated C `char` array to a `heapless::String<N>`.
17pub fn string_from_c_buf<const N: usize>(buf: &[core::ffi::c_char]) -> Result<String<N>> {
18    let c_str = unsafe { CStr::from_ptr(buf.as_ptr()) };
19    let s = c_str.to_str().map_err(|_| CfsError::InvalidString)?;
20    String::try_from(s).map_err(|_| CfsError::Osal(OsalError::NameTooLong))
21}