diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 9fd1aaf..72f08b2 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -77,7 +77,7 @@ jobs: matrix: rust: [stable] target: [x86_64-unknown-linux-gnu, x86_64-pc-windows-msvc, i686-pc-windows-msvc, x86_64-apple-darwin, aarch64-apple-darwin] #x86_64-unknown-linux-musl, - package: ["time", "timer", "counter"] + package: ["counter"] include: - os: ubuntu-latest target: x86_64-unknown-linux-gnu diff --git a/Cargo.lock b/Cargo.lock index f33b20a..f30b058 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3043,7 +3043,7 @@ checksum = "e8c5dfa5e08767553704aa0ffd9d9794d527103c736aba9854773851fd7497eb" dependencies = [ "colored", "log", - "time 0.3.36", + "time", "windows-sys 0.48.0", ] @@ -3239,13 +3239,6 @@ dependencies = [ "syn 2.0.66", ] -[[package]] -name = "time" -version = "0.1.3" -dependencies = [ - "winapi", -] - [[package]] name = "time" version = "0.3.36" @@ -3279,10 +3272,6 @@ dependencies = [ "time-core", ] -[[package]] -name = "timer" -version = "0.1.0" - [[package]] name = "tiny-skia" version = "0.11.4" diff --git a/Cargo.toml b/Cargo.toml index a28e012..d6fe10b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = [ "counter","time","timer"] +members = [ "counter"] resolver = "2" [profile.release] diff --git a/time/Cargo.lock b/time/Cargo.lock deleted file mode 100644 index 1e77d82..0000000 --- a/time/Cargo.lock +++ /dev/null @@ -1,32 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "time" -version = "0.1.3" -dependencies = [ - "winapi", -] - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/time/Cargo.toml b/time/Cargo.toml deleted file mode 100644 index d723706..0000000 --- a/time/Cargo.toml +++ /dev/null @@ -1,9 +0,0 @@ -[package] -name = "time" -version = "0.1.3" -edition = "2021" -publish = false - -[target.'cfg(target_family="windows")'.dependencies.winapi] -version = "0.3" -features = ["timezoneapi","impl-default","impl-debug","errhandlingapi"] \ No newline at end of file diff --git a/time/LICENSE b/time/LICENSE deleted file mode 100644 index 2bdefa8..0000000 --- a/time/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2022 C0D3 M4513R - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/time/Readme.md b/time/Readme.md deleted file mode 100644 index f3be6d7..0000000 --- a/time/Readme.md +++ /dev/null @@ -1,10 +0,0 @@ -# time -This repository is a binary, that writes the current time to a file. -The produced executable will expect a path to a file. -In that file specified the current time will be written. - -## Known potential problems -- On Windows the program will check for changes to the timezone every minute. -- On Platforms other than Windows the program will always write UTC to the file. - -Example commandline: `time.exe "C:\Users\some-user\Documents\time.txt"` \ No newline at end of file diff --git a/time/src/main.rs b/time/src/main.rs deleted file mode 100644 index 56cb9ed..0000000 --- a/time/src/main.rs +++ /dev/null @@ -1,112 +0,0 @@ -#[allow(unused_imports)] -use std::fs::{File, OpenOptions}; -use std::io::{Seek, SeekFrom, Write}; -use std::thread::sleep; -use std::time::{Duration, Instant}; - -type Result = std::result::Result; -#[cfg(target_family = "windows")] -mod windows; - -fn main() -> Result<()> { - let env: Vec = std::env::args().collect(); - if env.len() < 2 { - println!( - "Enter the FilePath, to write the time to as a argument {:#?}", - env - ); - pause(); - return Ok(()); - } - - let mut timezone = get_convert_utc_to_local(); - let filepath = unsafe { env.get_unchecked(1) }; - //Safety: Checked above - println!( - "The contents of the following file will be deleted. -It will be used for this program, to write the current system time to. -'{}'", - filepath - ); - pause(); - let mut test = OpenOptions::new() - .write(true) - .truncate(true) - .create(true) - .open(filepath)?; - - #[cfg(debug_assertions)] - let mut times = 0; - - let mut min = 0; - loop { - let time = std::time::SystemTime::now(); - let s = Instant::now(); - let dur = time - .duration_since(std::time::UNIX_EPOCH) - .expect("The clock was set to before 1970-01-01 00:00:00. Please set your clock."); - let local = timezone(dur); //Convert to Local time, if possible. - let seconds = local.as_secs() % 60; - let minutes = local.as_secs() / 60 % 60; - let hours = local.as_secs() / 60 / 60 % 24; - if min != minutes { - min = minutes; - timezone = get_convert_utc_to_local(); - } - let time = format!("{:02}:{:02}:{:02}", hours, minutes, seconds); - match test.seek(SeekFrom::Start(0)) { - Ok(_) => match test.write_all(time.as_bytes()){ - Ok(_) => {} - Err(err) => { - eprintln!("Could not write to file. File write returned {err}"); - } - }, - Err(err) => { - eprintln!("Could not seek in file: {err}"); - } - } - let dur_subsec_millis = local.subsec_millis(); - - #[cfg(debug_assertions)] - { - times += 1; - if dur_subsec_millis as u128 + s.elapsed().as_millis() > 100 && times > 10 { - panic!( - "Something went wrong. We wrote {}ms after the second changed.", - dur_subsec_millis as u128 + s.elapsed().as_millis() - ); - } - println!( - "{}ms slow, processing & writing took {}ns", - dur_subsec_millis, - s.elapsed().as_nanos() - ); - } - sleep( - Duration::from_millis(1000) - - Duration::from_millis(dur_subsec_millis as u64) - - s.elapsed(), - ); - } -} - -fn pause() { - println!("Press any key to continue..."); - let clin = std::io::stdin(); - let mut str = "".to_string(); - clin.read_line(&mut str).unwrap(); - println!("Resuming."); -} -fn get_convert_utc_to_local() -> impl Fn(Duration) -> Duration { - #[cfg(debug_assertions)] - println!("Checking Timezone"); - #[cfg(target_family = "windows")] - { - windows::get_convert_utc_to_local() - } - #[cfg(not(target_family = "windows"))] - { - //todo: not implemented. - |x| x - } -} diff --git a/time/src/windows.rs b/time/src/windows.rs deleted file mode 100644 index 7475652..0000000 --- a/time/src/windows.rs +++ /dev/null @@ -1,46 +0,0 @@ -#![cfg(target_family = "windows")] - -use std::ffi::{OsStr, OsString}; -use std::ops::{Add, Sub}; -use std::os::windows::ffi::OsStringExt; -use std::time::Duration; -use winapi::um::errhandlingapi::GetLastError; -use winapi::um::timezoneapi::{ - GetDynamicTimeZoneInformation, DYNAMIC_TIME_ZONE_INFORMATION, PDYNAMIC_TIME_ZONE_INFORMATION, - TIME_ZONE_ID_INVALID, -}; - -pub fn get_convert_utc_to_local() -> impl Fn(Duration) -> Duration { - let mut total_bias; - //Get Bias - { - let mut info = DYNAMIC_TIME_ZONE_INFORMATION::default(); - let r = - unsafe { GetDynamicTimeZoneInformation(&mut info as PDYNAMIC_TIME_ZONE_INFORMATION) }; - if r == TIME_ZONE_ID_INVALID { - eprintln!("Error Occurred whilst getting information on UTC to timezone conversion information.\n\ - System error code is:{}. For meaning of the code go here: https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes",unsafe{GetLastError()}); - eprintln!("Will continue, but the time will now be in UTC instead of the local time."); - info = DYNAMIC_TIME_ZONE_INFORMATION::default(); - } - - //We should have a bias here in every case, because even if the syscall fails, we reinitialise info. - total_bias = info.Bias; - match r { - 1 => total_bias += info.StandardBias, //No DST - 2 => total_bias += info.DaylightBias, //DST - _ => {} - } - } - //Make a fn, to apply bias - let op = if total_bias < 0 { - total_bias *= -1; - Duration::add - } else { - Duration::sub - }; - let total_bias = total_bias as u64; - //we now know, that total_bias>=0. So we can create a Duration. - let correction = Duration::from_secs(total_bias * 60); - move |x| op(x, correction) -} diff --git a/timer/.gitignore b/timer/.gitignore deleted file mode 100644 index ea8c4bf..0000000 --- a/timer/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/target diff --git a/timer/Cargo.lock b/timer/Cargo.lock deleted file mode 100644 index c311279..0000000 --- a/timer/Cargo.lock +++ /dev/null @@ -1,7 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "timer" -version = "0.1.0" diff --git a/timer/Cargo.toml b/timer/Cargo.toml deleted file mode 100644 index 31d9d56..0000000 --- a/timer/Cargo.toml +++ /dev/null @@ -1,9 +0,0 @@ -[package] -name = "timer" -version = "0.1.0" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -#[dependencies] -#no-panic = "0.1.15" \ No newline at end of file diff --git a/timer/src/error.rs b/timer/src/error.rs deleted file mode 100644 index 3c57d50..0000000 --- a/timer/src/error.rs +++ /dev/null @@ -1,26 +0,0 @@ -use std::fmt::{Debug, Display, Formatter}; - -#[repr(C)] -pub enum Error { - EarlierThanUnixEpoch, - InstantAdd, - CreateInstant -} -impl Display for Error{ - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - match self { - Error::EarlierThanUnixEpoch => write!(f,"The time gotten was earlier than the Unix epoch(0:0:0 1.1.1971)"), - Error::InstantAdd => write!(f,"There was an error adding a Duration to a Instant"), - Error::CreateInstant => write!(f,"There was an error creating a Instant"), - } - - } -} -impl Debug for Error{ - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - std::fmt::Display::fmt(&self,f) - } -} - -impl std::error::Error for Error { -} \ No newline at end of file diff --git a/timer/src/main.rs b/timer/src/main.rs deleted file mode 100644 index b60558f..0000000 --- a/timer/src/main.rs +++ /dev/null @@ -1,249 +0,0 @@ -extern crate core; - -use std::fs::OpenOptions; -use std::io::Write; -use std::ops::{Add, Div}; -use std::path::PathBuf; -use std::str::FromStr; -use std::thread::yield_now; -use std::time::{Duration,Instant}; -//use std::process::Termination; - -mod error; -type Result = std::result::Result; -//needs to be in 0..1000 -const SLEEP_CUTOFF:u32 = 50; - -#[export_name = "main_fn"] -fn main() -> Result<(),Box> { - let env: Vec = std::env::args().collect(); - if env.len()<= 1 { - println!("Correct usage is: '{} [seconds] [minutes] [hours] [days]', where <> args are required, and [] is optional.", env.get(0).expect("No executable found in first parameter.")); - println!("Default timer length is 12h, if nothing else is specified."); - return Ok(()); - } else if env.len() < 2 { - println!( - "Enter the FilePath, to write the time to as a argument {:#?}", - env - ); - pause(); - return Ok(()); - }else if env.len() < 3 { - println!("No default duration set. Using 12h."); - } - let timer; - { - let mut init_timer_sec:u64=0; - const ZERO:&'static str = "0"; - fn arg_to_num(env:&Vec,n:usize, zro:T)->T{ - match T::from_str(env.get(n).unwrap_or(&ZERO.to_string()).as_str()) { - Ok(v)=>v, - Err(_)=>zro, - } - } - //seconds - init_timer_sec += arg_to_num(&env,2, 0); - //minutes - init_timer_sec +=arg_to_num(&env,3, 0)*60; - //hours - init_timer_sec +=arg_to_num(&env,4, 0)*60*60; - //days - init_timer_sec +=arg_to_num(&env,5, 0)*60*60*24; - //init timer - if init_timer_sec==0{ - init_timer_sec=12*60*60;//12h default. - } - timer=Duration::from_secs(init_timer_sec); - } - - let filepath = unsafe { env.get_unchecked(1) }; - //Safety: Checked above - println!( - "The contents of the following file will be deleted. -It will be used for this program, to write the current system time to. -'{}'", - filepath - ); - write_replace(PathBuf::from(filepath),"".to_string()); - let filepath= std::fs::canonicalize(filepath).expect("Filepath not valid"); - - pause(); - #[cfg(debug_assertions)] - { - let s = new_instant()?; - println!("The output of the next line may be wierd. Ignore if you don't understand it."); - println!("Start-Time is around {:#?}, and End-Time should be around {:#?}",s,s.checked_add(timer)); - println!("Times may vary, according to timezone, however the relative distance should be the same."); - } - timer_loop(timer,filepath); - #[allow(unreachable_code)] - { - println!("Timer is done"); - pause(); - Ok(()) - } -} - - -// #[no_panic::no_panic] -// #[no_mangle] -//For now this doesn't stop. The timer keeps going. -fn timer_loop(duration:Duration,filepath:PathBuf)->!{ - let start = Instant::now(); - let end = start.add(duration); - #[cfg(debug_assertions)] - println!("Actual start time is {:#?} and end time is {:#?}", start, end); - - let inner_loop = ||->Result<()>{ - let time = sleep(start)?; - #[cfg(debug_assertions)] - let s = new_instant()?; - let mut neg = false; - let local = match end.checked_duration_since(time){ - Some(v)=>v, - None=>{neg=true;time.checked_duration_since(end).ok_or(error::Error::InstantAdd)?}, - }; - #[cfg(debug_assertions)] - { - println!("lost {}ms to sleep inaccuracies",local.subsec_millis()); - } - let seconds = local.as_secs() % 60; - let minutes = local.as_secs() / 60 % 60; - let hours = local.as_secs() / 60 / 60 % 24; - - let time = format!("{}{:02}:{:02}:{:02}",if neg {"-"} else {""}, hours, minutes, seconds); - #[cfg(debug_assertions)] - let w = new_instant()?; - #[cfg(debug_assertions)] - { - println!("Got String to write after {}ys", s.elapsed().as_micros()); - } - if let Err(_) = std::panic::catch_unwind(||write_replace(filepath.clone(),time)){ - //We cannot handle this error anyways, if the os won't let us. Let this just fly by. - std::io::stderr().write_all(b"Could not write to file.").ok(); - } - - - #[cfg(debug_assertions)] - { - let dur_subsec_millis = local.subsec_millis(); - println!("Writing took {}ys, processing time was {}ys and together that is {}ys", w.elapsed().as_micros(), w.duration_since(s).as_micros(), s.elapsed().as_micros()); - if dur_subsec_millis as u128 + s.elapsed().as_millis() > 100 { - eprintln!( - "Something went wrong. We wrote {}ms after the second changed.", - dur_subsec_millis as u128 + s.elapsed().as_millis() - ); - } - let sleep_dur=Duration::from_millis(1000).checked_sub(Duration::from_millis(dur_subsec_millis as u64)).and_then(|x|x.checked_sub(s.elapsed())).unwrap_or(Duration::new(0,0)); - println!( - "{}ms slow, processing & writing took {}ys. sleeping for {}ms", - dur_subsec_millis, - s.elapsed().as_nanos().div(&1000), - sleep_dur.as_millis() - ); - } - Ok(()) - - // sleep( - // Duration::from_millis(1000) - // - Duration::from_millis(dur_subsec_millis as u64) - // - s.elapsed() - // ); - }; - loop{ - //just ignore EVERYTHING. We want stability - std::panic::catch_unwind(inner_loop).ok(); - } -} -fn write_replace(filepath:PathBuf, time:String){ - use std::io::{Seek, SeekFrom}; - #[cfg(target_os = "windows")] - use std::os::windows::fs::FileExt; - let file = OpenOptions::new() - .write(true) - .truncate(true) - .create(true) - .open(filepath); - let mut file = match file{ - Err(e) => {std::io::stderr().write_all(e.to_string().as_bytes()).ok();return}, - Ok(v)=>v, - }; - let r = file.seek(SeekFrom::Start(0)); - if let Err(er)=r { - eprintln!( - "Could not seek. Error for seek is {}. ", - er - ); - #[cfg(target_os = "windows")] - { - let r1 = file.seek_write(time.as_bytes(), 0); - if let Err(er1) = r1{ - eprintln!( - "Could not seek, or seek and write.\n\ - Error for seek is {}. Error for seek and write is {}.", - er, - er1 - ); - } - } - #[cfg(not(target_os = "windows"))] - { - eprintln!( - "Could not seek then write.\n\ - Error for seek is {}.", - er - ); - } - } else { - let r = file.write_all(time.as_bytes()); - if let Err(e) = r { - eprintln!( - "Could not write to file. File write returned {}", - e - ); - } - } -} - -// #[no_mangle] -fn sleep(earlier:Instant)->Result{ - let sec =new_instant()?.checked_duration_since(earlier).ok_or(error::Error::InstantAdd)?.as_secs(); - let inner_loop = ||{ - let s = new_instant()?; - let local = s.checked_duration_since(earlier).ok_or(Some(error::Error::InstantAdd))?; - if local.subsec_millis()sec && !local.is_zero() { - return Ok(s); - } - std::hint::spin_loop(); - // yield_now(); - Err(None) - }; - loop { - match std::panic::catch_unwind(inner_loop){ - Ok(Ok(v)) => return Ok(v), - Ok(Err(Some(v))) => return Err(v), - Ok(Err(None)) => (), - Err(_)=>(), - } - } -} -#[inline(never)] -fn new_instant() -> Result{ - std::panic::catch_unwind(||Instant::now()).or_else(|_|Err(error::Error::CreateInstant)) -} - - - -// #[no_mangle] -fn pause() { - println!("Press any key to continue..."); - let clin = std::io::stdin(); - let mut str = "".to_string(); - clin.read_line(&mut str).ok(); - println!("Resuming."); -} \ No newline at end of file