first commit

This commit is contained in:
Lucas Schumacher 2024-07-02 20:53:20 -04:00
commit 63a9734b46
5 changed files with 80 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

7
Cargo.lock generated Normal file
View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "loader"
version = "0.1.0"

8
Cargo.toml Normal file
View File

@ -0,0 +1,8 @@
[package]
name = "loader"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

18
src/lib.rs Normal file
View File

@ -0,0 +1,18 @@
pub use std::sync::mpsc::TryRecvError;
use std::sync::mpsc::{self, Receiver};
pub struct Loader<T> {
rx: Receiver<T>,
}
impl<T: Send + 'static> Loader<T> {
pub fn new<F: FnOnce() -> T + Send + 'static>(f: F) -> Loader<T> {
let (tx, rx) = mpsc::sync_channel(0);
std::thread::spawn(move || tx.send(f()).unwrap());
return Loader { rx };
}
#[inline(always)]
pub fn try_recv(&self) -> Result<T, TryRecvError> {
self.rx.try_recv()
}
}

46
src/main.rs Normal file
View File

@ -0,0 +1,46 @@
use loader::{Loader, TryRecvError};
use std::{
io::{self, stdout, Write},
num::IntErrorKind,
time::{Duration, Instant},
};
const FPS: u64 = 12;
const NSPF: u64 = ((1.0 / FPS as f64) * 1.0e9) as u64;
const FRAME_DUR: Duration = Duration::from_nanos(NSPF);
fn main() {
let stdin = io::stdin();
loop {
print!("How many seconds: ");
stdout().flush().unwrap();
let mut input = String::new();
stdin.read_line(&mut input).unwrap();
let seconds: u64 = match input.strip_suffix("\n").unwrap_or(&input).parse() {
Ok(i) => i,
Err(e) if *e.kind() == IntErrorKind::Empty => break,
Err(e) => {
println!("Error parsing number: {:?}", e.kind());
continue;
}
};
let loader: Loader<String> = Loader::new(move || {
std::thread::sleep(Duration::from_secs(seconds));
return format!("Hello World {}", seconds);
});
let start = Instant::now();
let mut res = loader.try_recv();
while res == Err(TryRecvError::Empty) {
print!("\rWaiting... {:.2}s", start.elapsed().as_secs_f32());
std::io::stdout().flush().unwrap();
std::thread::sleep(FRAME_DUR);
res = loader.try_recv();
}
let elapsed = start.elapsed();
println!("\nDone! {:.2}s", elapsed.as_secs_f32());
println!("{}\n", res.unwrap());
}
}