Skip to content

Instantly share code, notes, and snippets.

@dialogbox
Last active September 4, 2018 15:08
Show Gist options
  • Save dialogbox/421d92d1a1248c5699636e98483db69a to your computer and use it in GitHub Desktop.
Save dialogbox/421d92d1a1248c5699636e98483db69a to your computer and use it in GitHub Desktop.
Rust sample code for quick start session.
use hyper::rt::{self, Future, Stream};
use hyper::Client;
use hyper::Body;
use hyper;
use tokio::runtime::Runtime;
use hyper_tls::HttpsConnector;
use std::io::{self, Write};
const HN_API_URL_TOPSTORIES: &str = "https://hacker-news.firebaseio.com/v0/topstories.json";
#[cfg(test)]
mod test {
use super::*;
use std::str;
#[test]
fn top_story_list_test() {
let https = HttpsConnector::new(4).expect("TLS initialization failed");
let client = Client::builder().build::<_, Body>(https);
let uri = HN_API_URL_TOPSTORIES.parse().unwrap();
let request = client
.get(uri)
.and_then(|res| res.into_body().concat2())
.map(|res| {
println!("{}", str::from_utf8(&res.to_vec()).unwrap());
})
.map_err(|err| {
println!("Error: {}", err);
});
let mut runtime = Runtime::new().unwrap();
match runtime.block_on(request) {
Ok(s) => {
println!("After wait: Result: {:#?}", &s);
}
Err(_) => (),
};
}
}
use std::collections::HashMap;
use std::fs;
fn count_word(contents: &str) -> Vec<(String, u32)> {
let mut wordcount = HashMap::new();
for s in contents.split_whitespace() {
let c = wordcount.entry(s).or_insert(0);
*c += 1;
}
let mut wordcount: Vec<(&str, u32)> = wordcount.into_iter().collect();
wordcount.sort_by(|&a, &b| b.1.cmp(&a.1));
return wordcount.iter().map(|&(w, count)| (w.to_owned(), count)).collect();
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn count_word_test() {
let contents = fs::read_to_string("src/word_count.rs").expect("file not found");
let mut wordcount = HashMap::new();
for s in contents.split_whitespace() {
let c = wordcount.entry(s).or_insert(0);
*c += 1;
}
let mut wordcount: Vec<(&&str, &u32)> = wordcount.iter().collect();
wordcount.sort_by(|a, b| b.1.cmp(a.1));
for (w, count) in wordcount.iter().take(5) {
println!("{}: {}", w, count);
}
}
#[test]
fn count_word_fn_test() {
let contents = fs::read_to_string("src/word_count.rs").expect("file not found");
for (w, count) in count_word(&contents).iter().take(5) {
println!("{}: {}", w, count);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment