utils: Add a function to format codes

If the number of digits is even, inserts an empty space in the middle.

HINT: Most codes are 6 digits long, except steam of course.
This commit is contained in:
Maximiliano Sandoval R 2021-01-22 15:13:24 +01:00
parent e9499bd428
commit b199cdaa91
Failed to generate hash of commit
2 changed files with 18 additions and 6 deletions

View file

@ -288,11 +288,8 @@ impl Account {
provider.algorithm().into(),
provider.digits() as u32,
) {
self.set_property(
"otp",
&format!("{:0width$}", otp, width = provider.digits() as usize),
)
.unwrap();
self.set_property("otp", &otp::format(otp, provider.digits() as usize))
.unwrap();
};
}

View file

@ -49,9 +49,18 @@ pub(crate) fn generate_hotp(
)
}
pub(crate) fn format(code: u32, digits: usize) -> String {
let mut formated_code = format!("{:0width$}", code, width = digits);
if digits % 2 == 0 {
let middle = digits / 2;
formated_code.insert(middle, ' ');
}
formated_code
}
#[cfg(test)]
mod tests {
use super::make_hotp;
use super::{format, make_hotp};
#[test]
fn hotp() {
@ -70,4 +79,10 @@ mod tests {
316439
);
}
#[test]
fn hotp() {
assert_eq!(format(012345, 6).unwrap(), "012 345");
assert_eq!(format(01234, 5).unwrap(), "01234");
}
}