1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#![cfg(feature = "semver-exempt")]
use core::fmt;
use nb::block;
use crate::serial::{NbWriter, ScifExt};
pub fn set_stdout<T: ScifExt>(_writer: NbWriter<T>) {
use core::fmt::Write;
interrupt_free(|| unsafe {
STDOUT = Some((
|s| {
let _ = Stdout(&mut T::global().into_nb_writer()).write_str(s);
},
|args| {
let _ = Stdout(&mut T::global().into_nb_writer()).write_fmt(args);
},
));
})
}
static mut STDOUT: Option<(fn(&str), fn(fmt::Arguments<'_>))> = None;
struct Stdout<'p, T>(&'p mut T);
impl<'p, T> core::fmt::Write for Stdout<'p, T>
where
T: embedded_hal::serial::Write<u8>,
{
fn write_str(&mut self, s: &str) -> core::fmt::Result {
for byte in s.as_bytes() {
if *byte == b'\n' {
let res = block!(self.0.write(b'\r'));
if res.is_err() {
return Err(core::fmt::Error);
}
}
let res = block!(self.0.write(*byte));
if res.is_err() {
return Err(core::fmt::Error);
}
}
Ok(())
}
}
#[inline]
#[cfg(target_arch = "arm")]
fn interrupt_free<T>(x: impl FnOnce() -> T) -> T {
use core::arch::asm;
let cpsr: u32;
unsafe { asm!("mrs {}, cpsr", out(reg)cpsr) };
let unmask = (cpsr & (1 << 7)) == 0;
unsafe { asm!("cpsid i") };
let ret = x();
if unmask {
unsafe { asm!("cpsie i") };
}
ret
}
#[cfg(not(target_arch = "arm"))]
fn interrupt_free<T>(_: impl FnOnce() -> T) -> T {
panic!("this crate is not supported on this platform")
}
#[doc(hidden)]
pub fn write_str(s: &str) {
interrupt_free(|| unsafe {
if let Some(stdout) = STDOUT.as_ref() {
(stdout.0)(s);
}
})
}
#[doc(hidden)]
pub fn write_fmt(args: fmt::Arguments<'_>) {
interrupt_free(|| unsafe {
if let Some(stdout) = STDOUT.as_ref() {
(stdout.1)(args);
}
})
}
#[macro_export]
macro_rules! sprint {
($($tt:tt)*) => {
match ::core::format_args!($($tt)*) {
args => if let ::core::option::Option::Some(s) = args.as_str() {
$crate::stdout::write_str(s)
} else {
$crate::stdout::write_fmt(args)
},
}
};
}
#[macro_export]
macro_rules! sprintln {
($($tt:tt)*) => {{
$crate::sprint!($($tt)*);
$crate::stdout::write_str("\n");
}};
}