mobile_code/lib.rs
1//! # mobile_code
2//!
3//! `mobile_code` is used for generating a code container to get, match
4//! and verify the code of a specific phone number
5//!
6
7/// # Example
8///
9/// Create a container
10/// let mut mobile_code = MobileCode::new(8);
11/// Add a phone number
12/// let number:u64 = 4162215930;
13/// mobile_code.add(number); // Add a phone number
14/// Add a phone list
15/// let mut vlist: Vec<u64> = Vec::new();
16/// vlist.push(4166471234);
17/// vlist.push(9086079876);
18/// mobile_code.add_list(&vlist);
19///
20/// Display the current codes
21/// mobile_code.list();
22///
23/// Get the code of a phone
24/// let code = mobile_code.get(&number);
25/// println!("Code is {:?}", code);
26/// Verify the code
27/// println!("Checking verify: {}", mobile_code.verify(&number, code));
28/// Test is_empty()
29/// println!("Checking empty: {}", mobile_code.is_empty());
30/// Remove a phone
31/// mobile_code.remove(&number);
32/// println!("Checking empty: {}", mobile_code.is_empty());
33/// Check has()
34/// println!("Checking has: {}", mobile_code.has(&number));
35use std::collections::HashMap;
36use rand::Rng;
37use num_traits::Pow;
38
39pub struct MobileCode {
40 mobile_codes: HashMap<u64, u64>,
41 length: u8,
42}
43
44impl MobileCode {
45 pub fn new(len: u8) -> Self { // Create an empty container
46 MobileCode {
47 mobile_codes: HashMap::new(),
48 length: len,
49 }
50 }
51
52 // Generate a random code
53 fn code_generator(&self) -> u64 {
54 //number = number || 6;
55 let low = Pow::pow(10u64, self.length - 1);
56 let high = Pow::pow(10u64, self.length) + 1;
57 rand::thread_rng().gen_range(low, high)
58 }
59
60 // List all the codes within the container
61 pub fn list(&self) {
62 for (key, value) in &self.mobile_codes {
63 println!("{} -> {}", key, value);
64 }
65 }
66
67 // Add a phone into the container
68 pub fn add(&mut self, mobile: u64) {
69 self.mobile_codes.insert(mobile, self.code_generator());
70 }
71
72 // Add a phone list into the container
73 pub fn add_list(&mut self, list: &Vec<u64>) {
74 for mobile in list {
75 self.add(*mobile);
76 }
77 }
78
79 // Get the code for this phone
80 pub fn get(&self, mobile: &u64) -> Option<&u64> {
81 self.mobile_codes.get(mobile)
82 }
83
84 // Has the container included the phone?
85 pub fn has(&self, mobile: &u64) -> bool {
86 self.mobile_codes.contains_key(mobile)
87 }
88
89 // Verify the code against the phone stored in the container
90 pub fn verify(&self, mobile: &u64, code: Option<&u64>) -> bool {
91 if self.mobile_codes.contains_key(mobile) {
92 //let v = self.mobile_codes.get(mobile).unwrap();
93 self.mobile_codes.get(mobile) == code
94 }
95 else {
96 false
97 }
98 }
99
100 // Remove the phone from the container
101 pub fn remove(&mut self, mobile: &u64) {
102 self.mobile_codes.remove(mobile);
103 }
104
105 pub fn clear(&mut self) {
106 self.mobile_codes.clear();
107 }
108
109 pub fn is_empty(&self) -> bool {
110 self.mobile_codes.is_empty()
111 }
112}
113