Created
May 26, 2023 16:18
-
-
Save judah4/6596908bcd6b29bb0ca90a316d10de09 to your computer and use it in GitHub Desktop.
Make a shorten and restore method to shorten a url and expand it, in Rust.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::collections::HashMap; | |
use rand::Rng; | |
/* | |
Make a shorten and restore method to shorten a url and expand it. | |
*/ | |
const ALPHAS : &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; | |
struct ShortUrls { | |
short_map: HashMap<String, String>, | |
url_map: HashMap<String, String>, | |
} | |
impl ShortUrls { | |
fn shorten(&mut self, url: String) -> String { | |
//check if key exists | |
match self.url_map.get(&url) { | |
Some(short) => return String::from(short), | |
None => {} | |
} | |
let mut shortened: String; | |
loop { | |
//generate | |
shortened = generate_key(); | |
//check for conflict | |
if !self.short_map.contains_key(&shortened) { | |
break; | |
} | |
println!("Conflict with key {shortened}"); | |
} | |
//insert for loop up later | |
self.short_map.insert(String::from(&shortened), url.to_string()); | |
self.url_map.insert(url.to_string(), String::from(&shortened)); | |
shortened | |
} | |
fn restore(&self, shortened: &String) -> Option<&String> { | |
let url = self.short_map.get(shortened); | |
return url; | |
} | |
} | |
fn generate_key() -> String { | |
let mut shortened = String::with_capacity(6); | |
let mut rng = rand::thread_rng(); | |
for _ in 0..6 { | |
let index: i32 = (rng.gen::<f64>() * ALPHAS.len() as f64) as i32; // generates a float between 0 and 1 | |
let index_sized = index as usize; | |
match ALPHAS.chars().nth(index_sized) { | |
Some(ch) => shortened.push(ch), | |
None => println!("No char, what do we do now?") | |
} | |
} | |
shortened | |
} | |
fn main() { | |
let mut urls = ShortUrls { | |
short_map: HashMap::new(), | |
url_map: HashMap::new(), | |
}; | |
let to_shorten = vec![ | |
"https://www.google.com", | |
"https://www.microsoft.com", | |
"https://www.gnarlywoodgroup.com", | |
"https://www.microsoft.com", //check for existing key | |
"https://stackoverflow.com/", | |
"https://www.inconsistent.software", | |
]; | |
let mut shortens = Vec::new(); | |
//generate | |
for url in to_shorten { | |
let shortened = urls.shorten(String::from(url)); | |
shortens.push(shortened); | |
} | |
//read back | |
for short_url in shortens { | |
find(&urls, &short_url); | |
} | |
} | |
fn find(urls: &ShortUrls, shortened: &String) { | |
let restored = urls.restore(&shortened); | |
match restored { | |
Some(url) => println!("{shortened}: {url}"), | |
None => println!("{shortened} is empty.") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment