Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added logging methods for u16 and u16 array #57

Merged
merged 3 commits into from
Sep 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions libs/logging/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,36 @@ impl<'a> Logger<'a> {
.unwrap();
}
}

pub fn log_u16(&mut self, val: &u16) {
for digit_index in (1..6).rev() {

// We have to temporarily the u16 to u32, otherwise doing 10^5 would cause an
// overflow in a u16 (100,000 > 65,535)
let digit = (*val as u32 % 10u32.pow(digit_index as u32)) / 10u32.pow(digit_index as u32 - 1);
let digit_character: u8 = digit as u8 + 48; // 48 is the offset of the numbers in the ASCII table

block!(match self.uart.bwrite_all(&[digit_character]) {
Ok(_) => Ok(()),
Err(_) => Err(nb::Error::Other(())),
})
.unwrap();
}
}

pub fn log_u16_array(&mut self, array: &[u16]) {
self.log("[");

array.iter().enumerate().for_each(|(index, &value)| {
self.log_u16(&value);

if index != array.len() - 1 {
self.log(", ");
}
});

self.log("]");
}
}

#[cfg(test)]
Expand Down Expand Up @@ -78,4 +108,20 @@ mod tests {
logger.log("Hello");
assert_eq!(mock_writer.get_string(), "Hello");
}

#[test]
fn test_log_u16() {
let mut mock_writer = MockWriter::new();
let mut logger = Logger::new(&mut mock_writer);
logger.log_u16(&3456u16);
assert_eq!(mock_writer.get_string(), "03456");
}

#[test]
fn test_log_u16_array() {
let mut mock_writer = MockWriter::new();
let mut logger = Logger::new(&mut mock_writer);
logger.log_u16_array(&[100u16, 250u16, 500u16]);
assert_eq!(mock_writer.get_string(), "[00100, 00250, 00500]");
}
}
Loading