Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@oconnor663
Last active March 15, 2019 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oconnor663/7a9035c4dcf0e364db10a07f428a3a59 to your computer and use it in GitHub Desktop.
Save oconnor663/7a9035c4dcf0e364db10a07f428a3a59 to your computer and use it in GitHub Desktop.
Rust HN fetch example
[package]
name = "fetch_hn"
version = "0.1.0"
edition = "2018"
[dependencies]
serde = { version = "1.0.89", features = ["derive"] }
reqwest = "0.9.11"
crossbeam-utils = "0.6.5"
use serde::Deserialize;
use std::sync::Mutex;
const STORIES_URL: &str = "https://hacker-news.firebaseio.com/v0/topstories.json";
const ITEM_URL_BASE: &str = "https://hacker-news.firebaseio.com/v0/item";
#[derive(Deserialize)]
struct Story {
title: String,
}
fn main() {
let story_ids: Vec<u64> = reqwest::get(STORIES_URL).unwrap().json().unwrap();
// AtomicUsize would be simpler than Mutex here, but the point of this is
// to give a Mutex example.
let cursor = Mutex::new(0);
crossbeam_utils::thread::scope(|s| {
for _ in 0..8 {
s.spawn(|_| loop {
let index = {
let mut cursor_guard = cursor.lock().unwrap();
let index = *cursor_guard;
if index >= story_ids.len() {
return;
}
*cursor_guard += 1;
index
};
let story_url = format!("{}/{}.json", ITEM_URL_BASE, story_ids[index]);
let story: Story = reqwest::get(&story_url).unwrap().json().unwrap();
println!("{}", story.title);
});
}
})
.unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment