discovery
discovery copied to clipboard
Different results in usart (buffer-overrun) when using String
My first stab at this code was as follows:
for c in "The quick brown fox jumps over the lazy dog.".chars() {
usart1.tdr.write(|w| w.tdr(u16::from(c as u8)));
}
Using a String rather than a byte string apparently introduces enough overhead in the debug build that the sentence comes across the serial connection just fine:
`for` loop took 30798 ticks (3849.75 us)
At the top of the page you say "If you wrote your program like this", it just might be worth pointing out that other common ways might not produce this result.
(Thanks for this project overall, this has been fun to work through!)
Thanks for you comment, @acfoltzer.
My first stab at this code was as follows:
Sorry to be pedantic but this is wrong in the general case because Rust strings are UTF-8 and char is 32 bits in size. For example:
Disclaimer: google translate
use std::str;
fn main() {
let mut buffer = vec![];
for c in "Der schnelle braune Fuchs springt über den faulen Hund".chars() {
buffer.push(c as u8);
}
println!("{}", unsafe { str::from_utf8_unchecked(&buffer) });
}
Produces:
Der schnelle braune Fuchs springt ber den faulen Hund
Note that ü is missing. And actually using str::from_utf8(&buffer).unwrap() would have resulted in a panic.
This would be the proper way to byte serialize Rust strings:
use std::str;
fn main() {
let mut buffer = vec![];
for b in "Der schnelle braune Fuchs springt über den faulen Hund".as_bytes() {
buffer.push(*b);
}
println!("{}", str::from_utf8(&buffer).unwrap());
}
This gives back:
Der schnelle braune Fuchs springt über den faulen Hund
it just might be worth pointing out that other common ways might not produce this result.
sounds reasonable