-
Notifications
You must be signed in to change notification settings - Fork 7
rely less on macros #29
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
remi-dupre
wants to merge
5
commits into
main
Choose a base branch
from
less-macros
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,21 +1,38 @@ | ||
| //! Tools used to fetch input contents from adventofcode.com. | ||
|
|
||
| use std::error::Error; | ||
| use std::fs::{create_dir_all, read_to_string, File}; | ||
| use std::io::Write; | ||
| use std::fs::{self, create_dir_all, read_to_string, File}; | ||
| use std::io::{self, Write}; | ||
| use std::io::{stdin, stdout}; | ||
| use std::path::{Path, PathBuf}; | ||
| use std::time::Instant; | ||
|
|
||
| use attohttpc::header::{COOKIE, USER_AGENT}; | ||
| use regex::Regex; | ||
|
|
||
| use crate::params::InputChoice; | ||
| use crate::utils::Line; | ||
| use crate::{input, Day, Error, Year}; | ||
|
|
||
| const BASE_URL: &str = "https://adventofcode.com"; | ||
| const USER_AGENT_VALUE: &str = "github.com/remi-dupre/aoc by [email protected]"; | ||
|
|
||
| fn input_path(year: u16, day: u8) -> PathBuf { | ||
| format!("input/{}/day{}.txt", year, day).into() | ||
| format!("input/{year}/day{day}.txt").into() | ||
| } | ||
|
|
||
| fn output_path(year: u16, day: u8, part: u8) -> PathBuf { | ||
| format!("output/{year}/day{day}-{part}.txt").into() | ||
| } | ||
|
|
||
| pub fn get_input_data(day: Day, year: Year, input: &InputChoice) -> String { | ||
| match input { | ||
| InputChoice::Download => input::get_input(year, day).expect("could not fetch input"), | ||
| InputChoice::File(file) => fs::read_to_string(file).expect("failed to read from stdin"), | ||
| InputChoice::Stdin => { | ||
| let input = io::stdin().lock(); | ||
| io::read_to_string(input).expect("failed to read specified file") | ||
| } | ||
| } | ||
| } | ||
|
|
||
| fn token_path() -> PathBuf { | ||
|
|
@@ -27,35 +44,69 @@ fn token_path() -> PathBuf { | |
| .unwrap_or_else(|| ".token".into()) | ||
| } | ||
|
|
||
| pub fn get_input(year: u16, day: u8) -> Result<String, Box<dyn Error>> { | ||
| let mut result = get_from_path_or_else(&input_path(year, day), || { | ||
| fn session_cookie() -> Result<String, Error> { | ||
| let token = get_conn_token()?; | ||
| Ok(format!("session={token}")) | ||
| } | ||
|
|
||
| fn get_input(year: u16, day: u8) -> Result<String, Error> { | ||
| let url = format!("{}/{}/day/{}/input", BASE_URL, year, day); | ||
|
|
||
| let fetch_from_web = move || { | ||
| let start = Instant::now(); | ||
| let url = format!("{}/{}/day/{}/input", BASE_URL, year, day); | ||
| let session_cookie = format!("session={}", get_conn_token()?); | ||
|
|
||
| let resp = attohttpc::get(&url) | ||
| .header(COOKIE, session_cookie) | ||
| .header(COOKIE, session_cookie()?) | ||
| .header(USER_AGENT, USER_AGENT_VALUE) | ||
| .send()?; | ||
|
|
||
| let elapsed = start.elapsed(); | ||
| let mut result = resp.text()?; | ||
|
|
||
| println!( | ||
| " - {}", | ||
| Line::new("downloaded input file").with_duration(elapsed) | ||
| ); | ||
| Line::new("download input file") | ||
| .with_duration(elapsed) | ||
| .println(); | ||
|
|
||
| resp.text() | ||
| })?; | ||
| if result.ends_with('\n') { | ||
| result.pop(); | ||
| } | ||
|
|
||
| if result.ends_with('\n') { | ||
| result.pop(); | ||
| } | ||
| Ok(result) | ||
| }; | ||
|
|
||
| Ok(result) | ||
| get_from_path_or_else(&input_path(year, day), fetch_from_web) | ||
| } | ||
|
|
||
| fn get_conn_token() -> Result<String, std::io::Error> { | ||
| pub fn get_expected(year: u16, day: u8, part: u8) -> Result<Option<String>, Error> { | ||
| let pattern = | ||
| Regex::new(r"Your puzzle answer was <code>(.*)</code>\.").expect("could no build pattern"); | ||
|
|
||
| let url = format!("https://adventofcode.com/{year}/day/{day}"); | ||
|
|
||
| let fetch_from_web = move || { | ||
| let start = Instant::now(); | ||
|
|
||
| let resp = attohttpc::get(&url) | ||
| .header(COOKIE, session_cookie()?) | ||
| .header(USER_AGENT, USER_AGENT_VALUE) | ||
| .send()?; | ||
|
|
||
| let elapsed = start.elapsed(); | ||
| let body = resp.text()?; | ||
| Line::new("get expected").with_duration(elapsed).println(); | ||
|
|
||
| let Some(found) = pattern.captures_iter(&body).nth(usize::from(part) - 1) else { | ||
| return Ok(None); | ||
| }; | ||
|
|
||
| let expected = found.get(1).expect("no capture in pattern").as_str(); | ||
| Ok(Some(expected.to_string())) | ||
| }; | ||
|
|
||
| try_get_from_path_or_else(&output_path(year, day, part), fetch_from_web) | ||
| } | ||
|
|
||
| fn get_conn_token() -> Result<String, Error> { | ||
| get_from_path_or_else(&token_path(), || { | ||
| let mut stdout = stdout(); | ||
| write!(&mut stdout, "Write your connection token: ")?; | ||
|
|
@@ -67,20 +118,44 @@ fn get_conn_token() -> Result<String, std::io::Error> { | |
| }) | ||
| } | ||
|
|
||
| fn get_from_path_or_else<E: Error>( | ||
| fn get_from_path_or_else( | ||
| path: &Path, | ||
| fallback: impl FnOnce() -> Result<String, E>, | ||
| ) -> Result<String, E> { | ||
| fallback: impl FnOnce() -> Result<String, Error>, | ||
| ) -> Result<String, Error> { | ||
| let from_path = read_to_string(path); | ||
|
|
||
| if let Ok(res) = from_path { | ||
| Ok(res) | ||
| } else { | ||
| let res = fallback()?; | ||
|
|
||
| create_dir_all(path.parent().expect("no parent directory")) | ||
| .and_then(|_| File::create(path)) | ||
| .and_then(|mut file| file.write_all(res.as_bytes())) | ||
| .unwrap_or_else(|err| eprintln!("could not write {}: {}", path.display(), err)); | ||
|
|
||
| Ok(res) | ||
| } | ||
| } | ||
|
|
||
| fn try_get_from_path_or_else( | ||
| path: &Path, | ||
| fallback: impl FnOnce() -> Result<Option<String>, Error>, | ||
| ) -> Result<Option<String>, Error> { | ||
| let from_path = read_to_string(path); | ||
|
|
||
| if let Ok(res) = from_path { | ||
| Ok(Some(res)) | ||
| } else { | ||
| let res = fallback()?; | ||
|
|
||
| if let Some(res) = &res { | ||
| create_dir_all(path.parent().expect("no parent directory")) | ||
| .and_then(|_| File::create(path)) | ||
| .and_then(|mut file| file.write_all(res.as_bytes())) | ||
| .unwrap_or_else(|err| eprintln!("could not write {}: {}", path.display(), err)); | ||
| } | ||
|
|
||
| Ok(res) | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Asked to comment here from my PR fixing borrowed data in returned iterators.
Ultimately, this crate and aoc-runner/'cargo aoc' are just conveniences. When folk are doing the competitive side of AOC, Rust is probably the wrong choice for most if not all puzzles - countless one-liners in numpy for instance are faster to create because of the super high level capabilities there.
What I and some others I know do is just do it in Rust for fun. For the lols. And there we end up playing code golf and seeing how fast we can get some algorithms. Last year I had some down to 300ns - and the generator was 4us - 10x slower than the actual runner.
In that scenario there was nothing borrowed, but sometimes it is convenient to just return a generator straight from stack where no allocations take place, and then for that being able to
a) borrow the input and return a struct with borrowed refers from the generator and
b) borrow the input passed to the runner to process it (with a cheap clone since the whole struct is a handful of words)
... is super convenient.
It was in fact one of the things that brought me to aoc-main vs 'cargo aoc'.
The other thing I'd love is a better way to manage many-year collections of aoc puzzles. Right now I use branches, because both aoc-main and aoc-runner want to both own the entry point, but not provide a year multiplexer.