1+ use std:: fmt;
2+ use std:: fmt:: Formatter ;
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`].
15+ #[ derive( Debug , Copy , Clone , Hash , PartialEq , Eq ) ]
16+ pub struct OTPResult {
17+ digits : u32 ,
18+ code : u32 ,
19+ }
20+
21+ /// Constructors for the [`OTPResult`] struct.
22+ impl OTPResult {
23+ /// Creates a new instance with the provided digit count and OTP code.
24+ pub fn new ( digits : u32 , code : u32 ) -> Self {
25+ OTPResult { digits, code }
26+ }
27+ }
28+
29+ /// Getters for the [`OTPResult`] struct.
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.
34+ pub fn get_digits ( & self ) -> u32 { self . digits }
35+ }
36+
37+ /// Convenience code getters for the [`OTPResult`] struct
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.
43+ pub fn as_string ( & self ) -> String {
44+ format ! ( "{:01$}" , self . code as usize , self . digits as usize )
45+ }
46+
47+
48+ /// Returns the OTP as it's original numerical representation
49+ ///
50+ /// This number may not be [`OTPResult::digits`] long.
51+ pub fn as_u32 ( & self ) -> u32 {
52+ self . code
53+ }
54+ }
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.
60+ impl fmt:: Display for OTPResult {
61+ fn fmt ( & self , f : & mut Formatter < ' _ > ) -> fmt:: Result {
62+ write ! ( f, "{}" , self . as_string( ) )
63+ }
64+ }
0 commit comments