Skip to content

Commit

Permalink
Merge branch 'main' into parse-cfg-through-syn
Browse files Browse the repository at this point in the history
  • Loading branch information
chrysn committed Oct 20, 2023
2 parents 2af99de + a366d14 commit f95247b
Show file tree
Hide file tree
Showing 34 changed files with 495 additions and 210 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/buildtest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ jobs:
# update` is much faster the second time (so a parallel execution may
# still be faster but uses 3x the resources)
run: |
export BOARDS='native sltb001a samr21-xpro'
export BOARDS='native sltb001a samr21-xpro stk3700'
DIRS='examples/rust-hello-world examples/rust-gcoap tests/rust_minimal'
# It appears that there has to be output before :: commands really catch on
echo "Building ${DIRS} on ${BOARDS}"
Expand All @@ -56,7 +56,7 @@ jobs:
echo "::echo ::off"
- name: Build and run tests
run: |
export BOARDS='native sltb001a samr21-xpro'
export BOARDS='native sltb001a samr21-xpro stk3700'
DIRS=$(echo tests/*/)
export RIOTBASE=$(pwd)/RIOT
# It appears that there has to be output before :: commands really catch on
Expand Down
4 changes: 2 additions & 2 deletions src/auto_init.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Tools for declaring a function that is run during initialization
//!
//! The [auto_init!] macro is this module's main product.
//! The [`auto_init!`](super::auto_init!) macro is this module's main product.
/// Wrapper around [riot_sys::auto_init_module_t]
///
Expand All @@ -13,7 +13,7 @@ impl AutoInitModule {
/// Initializer for module auto-initialization
///
/// Do not call this directly: Its result must be placed in a static in a special section in
/// memory, which is handled by the [`auto_init!`] macro.
/// memory, which is handled by the [`auto_init!`](super::auto_init!) macro.
pub const fn new(
init_function: extern "C" fn(),
priority: u16,
Expand Down
2 changes: 1 addition & 1 deletion src/bluetil.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ pub enum Error {

impl From<crate::error::NumericError> for Error {
fn from(e: crate::error::NumericError) -> Error {
match e.number as _ {
match e.number() as _ {
riot_sys::BLUETIL_AD_NOTFOUND => Error::NotFound,
riot_sys::BLUETIL_AD_NOMEM => Error::NoMem,
_ => panic!("Invalid bluetil error"),
Expand Down
65 changes: 65 additions & 0 deletions src/dac.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
use riot_sys::dac_t;

#[derive(Debug)]
pub struct DACLine {
line: dac_t,
}

#[derive(Debug)]
#[non_exhaustive]
pub enum DACError {
/// The given dac_t line did not exist
NoLine,
/// An unknown error did occur
Unknown,
}

impl DACLine {
/// Creates and intializes a new [`DACLine`].
///
/// The `index` indicates which dac device from the current board should be used.
/// For information on how many such devices are available for this board please
/// refer to its RIOT documentation.
///
/// Returns an Error if the given line does not exist
/// on the board.
pub fn new(index: usize) -> Result<Self, DACError> {
let line = unsafe { riot_sys::macro_DAC_LINE(index as u32) };
let res = unsafe { riot_sys::dac_init(line) } as i32;

const DAC_OK: i32 = riot_sys::DAC_OK as i32;
const DAC_NOLINE: i32 = riot_sys::DAC_NOLINE as i32;

match res {
DAC_OK => Ok(DACLine { line }),
DAC_NOLINE => Err(DACError::NoLine),
_ => Err(DACError::Unknown),
}
}

/// Builds a [`DACLine`] from an already initialized [`dac_t`].
///
/// Providing a not initialized [`dac_t`] results in undefined behavior.
pub unsafe fn new_without_init(line: dac_t) -> Self {
DACLine { line }
}

/// Writes the given value to this [`DACLine`]
///
/// The `value` is internally scaled to the underlying
/// dac device so that the maximum voltage output
/// is always equivalent to [`u16::MAX`]
pub fn set(&mut self, value: u16) {
unsafe { riot_sys::dac_set(self.line, value) }
}

/// Turns the [`DACLine`] on after `DACLine::power_off`
pub fn power_on(&mut self) {
unsafe { riot_sys::dac_poweron(self.line) }
}

/// Turns the [`DACLine`] off
pub fn power_off(&mut self) {
unsafe { riot_sys::dac_poweroff(self.line) }
}
}
40 changes: 34 additions & 6 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
//! Common error handling components for the RIOT operating system
//!
//! ## Constants
//!
//! Several commonly used errors are provided as constants rather than requiring the use of
//! [NumericError::from_constant] for easier use. That list is not created comprehensively but
//! populated on demand. (Copying the full list would needlessly limit RIOT's ability to slim down
//! the list).
use core::convert::TryInto;

Expand All @@ -16,8 +23,9 @@ pub trait NegativeErrorExt {
/// represent `Result<positive_usize, NumericError>` as just the isize it originally was. For the
/// time being, this works well enough, and performance evaluation can later be done against a
/// manually implemented newtype around isize that'd be used to represent the Result.
#[derive(Debug)]
#[derive(Debug, PartialEq)]
pub struct NumericError {
#[deprecated(note = "Use the .number() method")]
pub number: isize,
}

Expand All @@ -43,29 +51,36 @@ impl NumericError {
/// ## Panics
///
/// In debug mode, this ensures that the given error is greater than zero.
pub fn from_constant(name: isize) -> Self {
pub const fn from_constant(name: isize) -> Self {
debug_assert!(
name > 0,
"Error names are expected to be positive for conversion into negative error numbers."
);
#[allow(deprecated)] // it's deprecated *pub*
NumericError { number: -name }
}

/// Numeric value of the error
pub const fn number(&self) -> isize {
#[allow(deprecated)] // it's deprecated *pub*
self.number
}

/// Convert the error into an [nb::Error] that is [nb::Error::WouldBlock] if the error is
/// `-EAGAIN`, and an actual error otherwise.
pub fn again_is_wouldblock(self) -> nb::Error<Self> {
match -self.number as u32 {
riot_sys::EAGAIN => nb::Error::WouldBlock,
_ => nb::Error::Other(self),
if self == Self::from_constant(riot_sys::EAGAIN as _) {
return nb::Error::WouldBlock;
}
nb::Error::Other(self)
}
}

// Would be nice, but there's no strerror
//
// impl core::fmt::Display for NumericError {
// fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
// write!(f, "Error {} ({})", self.number, ...)
// write!(f, "Error {} ({})", self.number(), ...)
// }
// }

Expand All @@ -79,9 +94,22 @@ where
if self >= Self::zero() {
Ok(self)
} else {
#[allow(deprecated)] // it's deprecated *pub*
Err(NumericError {
number: self.try_into().unwrap_or(-(riot_sys::EOVERFLOW as isize)),
})
}
}
}

macro_rules! E {
($e:ident) => {
#[doc = concat!("The predefined error ", stringify!($e))]
pub const $e: NumericError = NumericError::from_constant(riot_sys::$e as _);
};
}

// See module level comment
E!(EAGAIN);
E!(ENOMEM);
E!(EOVERFLOW);
10 changes: 2 additions & 8 deletions src/gcoap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ unsafe extern "C" fn link_encoder<H: WithLinkEncoder>(
let h: &H = unsafe { &*((*resource).context as *const _) };

let buf = buf as *mut u8; // cast away signedness of char
let mut buf = if buf.is_null() {
let buf = if buf.is_null() {
None
} else {
Some(core::slice::from_raw_parts_mut(buf, buf_len as _))
Expand Down Expand Up @@ -259,7 +259,7 @@ impl<'a, H> SingleHandlerListener<'a, H>
where
H: 'a + Handler + WithLinkEncoder,
{
/// Like [`new()`], but utilizing that the handler is also [WithLinkEncoder] and can thus influence
/// Like [`Self::new()`], but utilizing that the handler is also [WithLinkEncoder] and can thus influence
/// what is reported when the default .well-known/core handler is queried.
pub fn new_with_link_encoder(
path: &'a core::ffi::CStr,
Expand Down Expand Up @@ -344,7 +344,6 @@ pub trait WithLinkEncoder {
}

use riot_sys::{
coap_get_total_hdr_len,
coap_opt_add_opaque,
coap_opt_add_uint,
coap_opt_get_next,
Expand Down Expand Up @@ -376,11 +375,6 @@ impl PacketBuffer {
}) as u8 // odd return type in C
}

/// Wrapper for coap_get_total_hdr_len
fn get_total_hdr_len(&self) -> usize {
(unsafe { coap_get_total_hdr_len(crate::inline_cast(self.pkt)) }) as usize
}

/// Wrapper for gcoap_resp_init
///
/// As it is used and wrapped here, this makes GCOAP_RESP_OPTIONS_BUF bytes unusable, but
Expand Down
3 changes: 2 additions & 1 deletion src/gnrc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ pub mod ipv6;

pub mod netapi;
pub mod netreg;
pub mod pktbuf;
#[deprecated(note = "moved to gnrc_pktbuf toplevel module")]
pub use crate::gnrc_pktbuf as pktbuf;

use riot_sys::{gnrc_netif_iter, gnrc_netif_t};

Expand Down
4 changes: 2 additions & 2 deletions src/gnrc/ipv6.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ impl ::core::str::FromStr for Address {
// When no_std_net / embedded_nal is present, it may be a good idea to run through there.
impl ::core::fmt::Debug for Address {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let as_u8 = unsafe { &self.inner.u8_ };
let as_u8 = self.raw();
write!(
f,
"{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:{:02x}{:02x}:\
Expand Down Expand Up @@ -180,7 +180,7 @@ impl From<embedded_nal::Ipv6Addr> for Address {
#[cfg(feature = "with_embedded_nal")]
impl From<Address> for embedded_nal::Ipv6Addr {
fn from(addr: Address) -> Self {
Self::from(unsafe { addr.inner.u8_ })
Self::from(*addr.raw())
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/gnrc/netreg.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#[cfg(feature = "with_msg_v2")]
use core::mem::MaybeUninit;

use riot_sys::{gnrc_netreg_entry_t, gnrc_netreg_register, gnrc_netreg_unregister, gnrc_nettype_t};

#[cfg(feature = "with_msg_v2")]
use crate::error::NegativeErrorExt;

// Transmuting the pointer into a Pktsnip does the right thing by treating it as a smart
Expand Down
23 changes: 18 additions & 5 deletions src/gnrc/pktbuf.rs → src/gnrc_pktbuf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ use riot_sys::{
gnrc_pktbuf_realloc_data,
gnrc_pktbuf_release_error,
gnrc_pktsnip_t,
gnrc_udp_hdr_build,
GNRC_NETERR_SUCCESS,
};

Expand Down Expand Up @@ -138,6 +137,8 @@ impl<M: Mode> Pktsnip<M> {
src: core::num::NonZeroU16,
dst: core::num::NonZeroU16,
) -> Result<Pktsnip<Writable>, NotEnoughSpace> {
use riot_sys::gnrc_udp_hdr_build;

let snip = unsafe { gnrc_udp_hdr_build(self.ptr, src.into(), dst.into()) };
if snip == 0 as *mut _ {
// All other errors are caught by the signature
Expand Down Expand Up @@ -253,13 +254,19 @@ impl<'a> Pktsnip<Writable> {
size: usize,
nettype: gnrc_nettype_t,
) -> Result<Self, NotEnoughSpace> {
let next = next.map(|s| s.ptr).unwrap_or(0 as *mut _);
let snip =
unsafe { gnrc_pktbuf_add(next, data as *const _, size.try_into().unwrap(), nettype) };
let next_ptr = next.as_ref().map(|s| s.ptr).unwrap_or(0 as *mut _);
forget(next);
let snip = unsafe {
gnrc_pktbuf_add(
next_ptr,
data as *const _,
size.try_into().unwrap(),
nettype,
)
};
if snip == 0 as *mut _ {
return Err(NotEnoughSpace);
}
forget(next);
Ok(unsafe { Pktsnip::<Writable>::from_ptr(snip) })
}

Expand All @@ -284,7 +291,13 @@ impl<'a> Pktsnip<Writable> {

impl<M: Mode> ::core::fmt::Debug for Pktsnip<M> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let mode = core::any::type_name::<M>();
let mode = mode
.rsplit("::")
.next()
.expect("Type name contains :: because it is part of a module");
f.debug_struct("Pktsnip")
.field("M", &mode)
.field("length", &self.len())
.field("snips", &self.count())
.finish()
Expand Down
2 changes: 1 addition & 1 deletion src/interrupt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
//! * Utility functions can disable interrupts (creating critical sections), check whether
//! interrupts are enabled or to determine whether code is executed in a thread or an ISR.
//!
//! * Some functions (eg. [`ZTimer::set_ticks_during`](crate::ztimer::ZTimer::set_ticks_during))
//! * Some functions (eg. [`ZTimer::set_ticks_during`](crate::ztimer::Clock::set_during))
//! take callbacks that will be called in an interrupt context.
//!
//! These are typechecked to be Send, as they are moved from the thread to the interrupt context.
Expand Down
35 changes: 24 additions & 11 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,25 @@ mod helpers;
mod never;
use never::Never;

/// The identifier of the RIOT board the program is being built for (`RIOT_BOARD` in C).
#[doc(alias = "RIOT_BOARD")]
pub const BOARD: &'static str = {
let b = riot_sys::RIOT_BOARD;
let Ok(b) = core::ffi::CStr::from_bytes_with_nul(b) else {
// Could be `.expect()`, but that's not const yet
// Workaround-For: https://github.com/rust-lang/rust/issues/67441
panic!("Board names are null-terminated C strings");
};
let Ok(b) = b.to_str() else {
panic!("Board names should be ASCII")
};
b
};

/// Name of the RIOT board that is being used
///
/// Development:
///
/// Once this can be const, it'll be deprecated in favor of a pub const &'static str. That'll also
/// force the compiler to remove all the exceptions at build time (currently it does not, even with
/// aggressive optimization).
pub fn board() -> &'static str {
core::ffi::CStr::from_bytes_with_nul(riot_sys::RIOT_BOARD)
.expect("Board names are null-terminated C strings")
.to_str()
.expect("Board names should be ASCII")
#[deprecated(note = "Access BOARD instead")]
pub const fn board() -> &'static str {
BOARD
}

/// Cast pointers around before passing them in to functions; this is sometimes needed when a
Expand Down Expand Up @@ -105,6 +112,9 @@ pub mod thread;
pub mod gcoap;
#[cfg(riot_module_gnrc)]
pub mod gnrc;
// Note that this can also exist without gnrc
#[cfg(riot_module_gnrc_pktbuf)]
pub mod gnrc_pktbuf;
#[cfg(riot_module_gnrc)]
pub mod gnrc_util;
#[cfg(riot_module_periph_i2c)]
Expand All @@ -118,6 +128,9 @@ pub mod spi;
#[cfg(riot_module_periph_adc)]
pub mod adc;

#[cfg(riot_module_periph_dac)]
pub mod dac;

#[cfg(riot_module_ztimer)]
pub mod ztimer;

Expand Down
Loading

0 comments on commit f95247b

Please sign in to comment.