|
1 | 1 | use std::fmt;
|
2 | 2 | use std::fmt::Formatter;
|
3 | 3 |
|
| 4 | +/// A convenience struct to hold the result of a [`HOTP`] or [`TOTP`] |
| 5 | +/// generation. |
| 6 | +/// |
| 7 | +/// Contains the amount of digits the OTP should be, and the actual OTP, |
| 8 | +/// which will be equal to or less than the digit count. Currently houses |
| 9 | +/// a convenience [`OTPResult::as_string`] which returns a zero-padded string |
| 10 | +/// that has a length of [`OTPResult::digits`]. Additionally, the numerical |
| 11 | +/// representation of the code can be got with [`OTPResult::as_u32`]. |
| 12 | +/// |
| 13 | +/// Returned as a result of either [`HOTP::get_otp`], [`TOTP::get_otp`] |
| 14 | +/// or [`TOTP::get_otp_with_custom_time_start`]. |
4 | 15 | #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
|
5 | 16 | pub struct OTPResult {
|
6 | 17 | digits: u32,
|
7 | 18 | code: u32,
|
8 | 19 | }
|
9 | 20 |
|
| 21 | +/// Constructors for the [`OTPResult`] struct. |
10 | 22 | impl OTPResult {
|
| 23 | + /// Creates a new instance with the provided digit count and OTP code. |
11 | 24 | pub fn new(digits: u32, code: u32 ) -> Self {
|
12 | 25 | OTPResult { digits, code }
|
13 | 26 | }
|
14 | 27 | }
|
15 | 28 |
|
| 29 | +/// Getters for the [`OTPResult`] struct. |
16 | 30 | impl OTPResult {
|
| 31 | + /// Gets the digit count given to the struct on creation. |
| 32 | + /// |
| 33 | + /// Also the count used to determine how long the formatted string will be. |
17 | 34 | pub fn get_digits(&self) -> u32 { self.digits }
|
18 | 35 | }
|
19 | 36 |
|
| 37 | +/// Conveneince code getters for the [`OTPResult`] struct |
20 | 38 | impl OTPResult {
|
| 39 | + /// Returns the OTP as a formatted string of length [`OTPResult.digits`]. |
| 40 | + /// |
| 41 | + /// If [`OTPResult::code`] is less than [`OTPResult::digits`] long, leading zeroes |
| 42 | + /// will be added to the string. |
21 | 43 | pub fn as_string(&self) -> String {
|
22 | 44 | format!("{:01$}", self.code as usize, self.digits as usize)
|
23 | 45 | }
|
24 | 46 |
|
| 47 | + |
| 48 | + /// Returns the OTP as it's original numerical representation |
| 49 | + /// |
| 50 | + /// This number may not be [`OTPResult::digits`] long. |
25 | 51 | pub fn as_u32(&self) -> u32 {
|
26 | 52 | self.code
|
27 | 53 | }
|
28 | 54 | }
|
29 | 55 |
|
| 56 | +/// A Display implementation for the [`OTPResult`] struct |
| 57 | +/// |
| 58 | +/// Returns the String-formatted code, which is zero-padded |
| 59 | +/// to be [`OTPResult::digits`] long. |
30 | 60 | impl fmt::Display for OTPResult {
|
31 | 61 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
32 | 62 | write!(f, "{}", self.as_string())
|
|
0 commit comments