Commit 0c992236 authored by Astro's avatar Astro
Browse files

l0dable: fmt_buffer additions

parent fb6969cc
//! Stolen from https://stackoverflow.com/questions/39488327/how-to-format-output-to-a-byte-array-with-no-std-and-no-allocator
use core::fmt;
use core::fmt::{self, Write};
use core::mem::uninitialized;
use core::str::from_utf8_unchecked;
pub struct FmtBuffer<'a> {
buf: &'a mut [u8],
......@@ -34,3 +36,21 @@ impl<'a> fmt::Write for FmtBuffer<'a> {
Ok(())
}
}
/// 256 bytes ought to be enough for any string
pub fn str_to_cstr(s: &str) -> [u8; 256] {
let mut buf: [u8; 256] = unsafe { uninitialized() };
let mut fmt = FmtBuffer::new(buf.as_mut());
write!(fmt, "{}\0", s).unwrap();
buf
}
impl AsRef<str> for FmtBuffer<'_> {
fn as_ref(&self) -> &str {
let len = self.buf.iter().position(|b| *b == 0)
.unwrap_or(0);
unsafe {
from_utf8_unchecked(&self.buf[0..len])
}
}
}
......@@ -81,15 +81,8 @@ pub mod trng;
mod utime;
pub use utime::time;
mod fmt_buffer;
pub use fmt_buffer::FmtBuffer;
pub use fmt_buffer::{FmtBuffer, str_to_cstr};
mod bme680;
pub use bme680::BME680;
mod bhi160;
pub use bhi160::{Sensor as BHI160, Accelerometer, Orientation, Gyroscope, SensorData as BHI160Data};
pub fn exit(ret: i32) -> ! {
unsafe {
epic_exit(ret);
}
unreachable!()
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment