Skip to content

Commit

Permalink
saul: Provide name_owned(), deprecate and clip the existing name func…
Browse files Browse the repository at this point in the history
…tions

An underlying API change[20529] made the functions impossible to
satisfy; as they are already fallible (and may have returned None if the
list were reduced), returning None is a compatible-by-the-letter way out.

[20529]: RIOT-OS/RIOT#20529

Co-Authored-By: Teufelchen1 <[email protected]>
Closes: #86
  • Loading branch information
chrysn and Teufelchen1 committed Apr 3, 2024
1 parent 409a5be commit 6568416
Showing 1 changed file with 31 additions and 8 deletions.
39 changes: 31 additions & 8 deletions src/saul.rs
Original file line number Diff line number Diff line change
Expand Up @@ -486,18 +486,41 @@ impl Unit {
}

/// String representation of a given unit (e.g. `V` or `m`)
#[doc(alias = "phydat_unit_to_str")]
#[deprecated(
note = "RIOT's mechanism changed; this returns None unconditionally, use .name_owned() instead"
)]
pub fn name(self) -> Option<&'static str> {
unsafe { riot_sys::phydat_unit_to_str(Self::to_c(Some(self))).to_lifetimed_cstr()? }
.to_str()
.ok()
None
}

/// Like [`.name()`](Unit::name), but with additional names like "none" or "time".
#[doc(alias = "phydat_unit_to_str_verbose")]
#[deprecated(
note = "RIOT's mechanism changed; this returns None unconditionally, use .name_owned() instead"
)]
pub fn name_verbose(self) -> Option<&'static str> {
unsafe { riot_sys::phydat_unit_to_str_verbose(Self::to_c(Some(self))).to_lifetimed_cstr()? }
.to_str()
.ok()
None
}

/// String representation of a given unit (e.g. `V`, `m`, `none` or `time`)
#[doc(alias = "phydat_unit_write")]
pub fn name_owned<const S: usize>(self) -> Option<heapless::String<S>> {
let mut result = heapless::String::new();
// SAFETY: The C API will only write UTF-8 bytes.
let mut bytes = unsafe { result.as_mut_vec() };
// SAFETY: C API promises to write only up to S bytes, will not write NULL byte.
let len = unsafe {
riot_sys::phydat_unit_write(
// Casting away signedness
bytes.as_mut_ptr() as *mut _,
// size_t is not always usize
S as _,
Self::to_c(Some(self)),
)
}
.negative_to_error()
.ok()?;
// SAFETY: We just wrote those bytes.
unsafe { bytes.set_len(len as _) };
Some(result)
}
}

0 comments on commit 6568416

Please sign in to comment.