Skip to content
Snippets Groups Projects
Commit eb56157f authored by Michael Hauspie's avatar Michael Hauspie
Browse files

Initial commit with usize decimal format

parents
Branches
No related tags found
No related merge requests found
/target
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "mini-format"
version = "0.1.0"
[package]
name = "mini-format"
version = "0.1.0"
edition = "2021"
authors = ["Michaël Hauspie <michael.hauspie@univ-lille.fr>"]
[dependencies]
mini-format is a minimalist formating crate.
Its main purpose is to be used in very small embedded systems in which
you want to avoid use the [`core::fmt::Write`] trait for whatever
reason.
#![doc = include_str!("../README.md")]
#![cfg_attr(not(test), no_std)]
/// A trait that tells that a type can be formatted.
///
/// This is used to provide the [`format`] function
/// that can be called on any type that implement the
/// trait
pub trait Format<F> where
F: FnMut(char)
{
/// format to a decimal representation by using the provided
/// `putchar` closure to *output* subsequent char, whatever it may
/// mean
fn format_dec(&self, putchar: F);
}
/// format a value to a decimal representation by using the provided
/// `putchar` closure to *output* subsequent char, whatever it may
/// mean
pub fn format_dec<T,F>(value: T, putchar: F) where
T: Format<F>,
F: FnMut(char)
{
value.format_dec(putchar);
}
impl<F:FnMut(char)> Format<F> for usize {
fn format_dec(&self, mut putchar: F) {
let mut max_pow = 1;
let mut val = *self;
while val / max_pow >= 10 {
max_pow *= 10;
}
while max_pow >= 1 {
let char_val: char = char::from_u32((val / max_pow) as u32 + '0' as u32).unwrap_or(' ');
putchar(char_val);
val = val % max_pow;
max_pow /= 10
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn format_dec_ok() {
let x = 124567891354654;
let mut s = String::new();
format_dec(x, |c| {
s.push(c)
});
assert_eq!(s, format!("{x}"));
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment