Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ attohttpc = { version = "0.24", default_features = false, features = ["tls"] }
clap = { version = "4", features = ["string"] }
colored = "2"
dirs = "4"
regex = "1"

# Optional dependencies
criterion = { version = "0.4", optional = true }
4 changes: 2 additions & 2 deletions src/bin/example.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ mod day2 {
}

mod day3 {
pub fn generator(_: &str) -> Option<&str> {
pub fn generator(_: String) -> Option<String> {
Copy link
Contributor

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.

None
}

Expand All @@ -56,7 +56,7 @@ mod day3 {
}

mod day4 {
pub fn generator(_: &str) -> Result<i64, impl std::fmt::Display + std::fmt::Debug> {
pub fn generator(_: String) -> Result<i64, impl std::fmt::Display> {
"five".parse()
}

Expand Down
121 changes: 98 additions & 23 deletions src/input.rs
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 {
Expand All @@ -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: ")?;
Expand All @@ -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)
}
}
Loading