1use std::sync::Arc;
12use std::time::{Duration, SystemTime, UNIX_EPOCH};
13
14#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
16pub enum Weekday {
17 Monday,
18 Tuesday,
19 Wednesday,
20 Thursday,
21 Friday,
22 Saturday,
23 Sunday,
24}
25
26impl Weekday {
27 fn from_days_since_epoch(days: i64) -> Self {
29 match (days + 3).rem_euclid(7) {
31 0 => Weekday::Monday,
32 1 => Weekday::Tuesday,
33 2 => Weekday::Wednesday,
34 3 => Weekday::Thursday,
35 4 => Weekday::Friday,
36 5 => Weekday::Saturday,
37 _ => Weekday::Sunday,
38 }
39 }
40
41 pub fn number_from_monday(self) -> u8 {
43 self as u8 + 1
44 }
45}
46
47#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
49pub struct LocalDate {
50 pub year: i32,
51 pub month: u8,
53 pub day: u8,
55 pub weekday: Weekday,
56}
57
58impl LocalDate {
59 fn from_days_since_epoch(days: i64) -> Self {
61 let z = days + 719_468;
64 let era = z.div_euclid(146_097);
65 let day_of_era = z.rem_euclid(146_097);
66 let year_of_era =
67 (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
68 let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
69 let shifted_month = (5 * day_of_year + 2) / 153;
70 let day = day_of_year - (153 * shifted_month + 2) / 5 + 1;
71 let month = if shifted_month < 10 {
72 shifted_month + 3
73 } else {
74 shifted_month - 9
75 };
76 let year = year_of_era + era * 400 + i64::from(month <= 2);
77 LocalDate {
78 year: year as i32,
79 month: month as u8,
80 day: day as u8,
81 weekday: Weekday::from_days_since_epoch(days),
82 }
83 }
84
85 pub fn days_since_epoch(&self) -> i64 {
87 let month = i64::from(self.month);
88 let year = i64::from(self.year) - i64::from(month <= 2);
89 let era = year.div_euclid(400);
90 let year_of_era = year.rem_euclid(400);
91 let shifted_month = if month > 2 { month - 3 } else { month + 9 };
92 let day_of_year = (153 * shifted_month + 2) / 5 + i64::from(self.day) - 1;
93 let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
94 era * 146_097 + day_of_era - 719_468
95 }
96}
97
98#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
100pub struct LocalDateTime {
101 pub date: LocalDate,
102 pub hour: u8,
104 pub minute: u8,
105 pub second: u8,
107 pub nanosecond: u32,
108 pub utc_offset_seconds: i32,
111}
112
113pub fn today() -> LocalDate {
115 now_local().date
116}
117
118pub fn now_local() -> LocalDateTime {
120 local_at(platform::now())
121}
122
123pub fn local_at(instant: SystemTime) -> LocalDateTime {
125 let (seconds, nanosecond) = match instant.duration_since(UNIX_EPOCH) {
126 Ok(after) => (after.as_secs() as i64, after.subsec_nanos()),
127 Err(before) => {
128 let before = before.duration();
129 let whole = before.as_secs() as i64;
130 match before.subsec_nanos() {
131 0 => (-whole, 0),
132 part => (-whole - 1, 1_000_000_000 - part),
133 }
134 }
135 };
136 let offset = platform::utc_offset_seconds(seconds);
137 let local = seconds + i64::from(offset);
138 let days = local.div_euclid(86_400);
139 let second_of_day = local.rem_euclid(86_400);
140 LocalDateTime {
141 date: LocalDate::from_days_since_epoch(days),
142 hour: (second_of_day / 3600) as u8,
143 minute: (second_of_day / 60 % 60) as u8,
144 second: (second_of_day % 60) as u8,
145 nanosecond,
146 utc_offset_seconds: offset,
147 }
148}
149
150fn until_midnight(now: &LocalDateTime) -> Duration {
152 let into_day = u64::from(now.hour) * 3600 + u64::from(now.minute) * 60 + u64::from(now.second);
153 let left = 86_400u64.saturating_sub(into_day).max(1);
154 Duration::from_secs(left).saturating_sub(Duration::from_nanos(u64::from(now.nanosecond)))
155}
156
157const LONGEST_WAIT: Duration = Duration::from_secs(60);
160
161const PAST_MIDNIGHT: Duration = Duration::from_millis(20);
163
164pub struct DateChangeSubscription {
166 id: u64,
167}
168
169impl Drop for DateChangeSubscription {
170 fn drop(&mut self) {
171 watch::remove(self.id);
172 }
173}
174
175pub fn subscribe_date_change(notify: Arc<dyn Fn() + Send + Sync>) -> DateChangeSubscription {
180 DateChangeSubscription {
181 id: watch::add(notify),
182 }
183}
184
185mod watch {
187 use super::{LocalDate, today};
188 use std::sync::{Arc, Mutex, MutexGuard};
189
190 pub(super) type Notify = Arc<dyn Fn() + Send + Sync>;
191
192 pub(super) struct Watch {
193 pub(super) subscribers: Vec<(u64, Notify)>,
194 pub(super) next_id: u64,
195 pub(super) seen: Option<LocalDate>,
197 pub(super) armed: bool,
199 }
200
201 pub(super) static WATCH: Mutex<Watch> = Mutex::new(Watch {
202 subscribers: Vec::new(),
203 next_id: 1,
204 seen: None,
205 armed: false,
206 });
207
208 pub(super) fn lock() -> MutexGuard<'static, Watch> {
209 WATCH.lock().unwrap_or_else(|poison| poison.into_inner())
210 }
211
212 pub(super) fn add(notify: Notify) -> u64 {
213 let mut watch = lock();
214 let id = watch.next_id;
215 watch.next_id += 1;
216 if watch.subscribers.is_empty() {
219 watch.seen = Some(today());
220 }
221 watch.subscribers.push((id, notify));
222 if !watch.armed {
223 watch.armed = true;
224 super::platform::arm();
225 }
226 drop(watch);
227 super::platform::changed();
228 id
229 }
230
231 pub(super) fn remove(id: u64) {
232 let mut watch = lock();
233 watch
234 .subscribers
235 .retain(|(subscriber, _)| *subscriber != id);
236 drop(watch);
237 super::platform::changed();
238 }
239
240 pub(super) fn check() {
244 let now = today();
245 let woken: Vec<Notify> = {
246 let mut watch = lock();
247 if watch.seen == Some(now) {
248 return;
249 }
250 watch.seen = Some(now);
251 watch
252 .subscribers
253 .iter()
254 .map(|(_, notify)| notify.clone())
255 .collect()
256 };
257 for notify in woken {
258 notify();
259 }
260 }
261}
262
263#[cfg(not(target_family = "wasm"))]
264mod platform {
265 use super::{LONGEST_WAIT, PAST_MIDNIGHT, now_local, until_midnight, watch};
266 use std::sync::Condvar;
267 use std::time::SystemTime;
268
269 pub(super) fn now() -> SystemTime {
270 SystemTime::now()
271 }
272
273 static CHANGED: Condvar = Condvar::new();
275
276 pub(super) fn changed() {
277 CHANGED.notify_all();
278 }
279
280 pub(super) fn arm() {
283 let started = std::thread::Builder::new()
284 .name("compose-rust-date".to_owned())
285 .spawn(run);
286 if started.is_err() {
287 watch::lock().armed = false;
290 }
291 }
292
293 fn run() {
294 loop {
295 let wait = until_midnight(&now_local()).min(LONGEST_WAIT) + PAST_MIDNIGHT;
296 let mut watch = watch::lock();
297 if !watch.subscribers.is_empty() {
298 watch = CHANGED
299 .wait_timeout(watch, wait)
300 .unwrap_or_else(|poison| poison.into_inner())
301 .0;
302 }
303 if watch.subscribers.is_empty() {
304 watch.armed = false;
305 return;
306 }
307 drop(watch);
308 watch::check();
309 }
310 }
311
312 #[cfg(unix)]
313 pub(super) fn utc_offset_seconds(seconds: i64) -> i32 {
314 use std::ffi::{c_char, c_int, c_long};
315
316 #[repr(C)]
319 struct Tm {
320 tm_sec: c_int,
321 tm_min: c_int,
322 tm_hour: c_int,
323 tm_mday: c_int,
324 tm_mon: c_int,
325 tm_year: c_int,
326 tm_wday: c_int,
327 tm_yday: c_int,
328 tm_isdst: c_int,
329 tm_gmtoff: c_long,
330 tm_zone: *const c_char,
331 }
332
333 unsafe extern "C" {
334 fn tzset();
335 fn localtime_r(time: *const c_long, result: *mut Tm) -> *mut Tm;
336 }
337
338 let Some(time) = c_long::try_from(seconds).ok() else {
339 return 0;
340 };
341 let mut tm = Tm {
342 tm_sec: 0,
343 tm_min: 0,
344 tm_hour: 0,
345 tm_mday: 0,
346 tm_mon: 0,
347 tm_year: 0,
348 tm_wday: 0,
349 tm_yday: 0,
350 tm_isdst: 0,
351 tm_gmtoff: 0,
352 tm_zone: std::ptr::null(),
353 };
354 let converted = unsafe {
359 tzset();
360 localtime_r(&time, &mut tm)
361 };
362 if converted.is_null() {
363 return 0;
364 }
365 tm.tm_gmtoff as i32
366 }
367
368 #[cfg(windows)]
369 pub(super) fn utc_offset_seconds(seconds: i64) -> i32 {
370 use std::ffi::{CString, c_char, c_int};
371 use std::sync::Mutex;
372
373 #[repr(C)]
375 #[derive(Default)]
376 struct Tm {
377 tm_sec: c_int,
378 tm_min: c_int,
379 tm_hour: c_int,
380 tm_mday: c_int,
381 tm_mon: c_int,
382 tm_year: c_int,
383 tm_wday: c_int,
384 tm_yday: c_int,
385 tm_isdst: c_int,
386 }
387
388 unsafe extern "C" {
389 fn _tzset();
390 fn _putenv_s(name: *const c_char, value: *const c_char) -> c_int;
391 fn _localtime64_s(result: *mut Tm, time: *const i64) -> c_int;
392 }
393
394 static SYNCED: Mutex<Option<String>> = Mutex::new(None);
398 let wanted = std::env::var("TZ").ok();
399 {
400 let mut synced = SYNCED.lock().unwrap_or_else(|poison| poison.into_inner());
401 if *synced != wanted {
402 if let Ok(value) = CString::new(wanted.clone().unwrap_or_default()) {
403 unsafe { _putenv_s(c"TZ".as_ptr(), value.as_ptr()) };
405 }
406 *synced = wanted;
407 }
408 }
409 let mut tm = Tm::default();
410 let failed = unsafe {
412 _tzset();
413 _localtime64_s(&mut tm, &seconds)
414 };
415 if failed != 0 {
416 return 0;
417 }
418 let date = super::LocalDate {
421 year: tm.tm_year + 1900,
422 month: (tm.tm_mon + 1) as u8,
423 day: tm.tm_mday as u8,
424 weekday: super::Weekday::Monday,
425 };
426 let wall = date.days_since_epoch() * 86_400
427 + i64::from(tm.tm_hour) * 3600
428 + i64::from(tm.tm_min) * 60
429 + i64::from(tm.tm_sec);
430 (wall - seconds) as i32
431 }
432}
433
434#[cfg(target_family = "wasm")]
435mod platform {
436 use super::{PAST_MIDNIGHT, now_local, until_midnight, watch};
437 use std::cell::Cell;
438 use std::time::{Duration, SystemTime, UNIX_EPOCH};
439
440 #[link(wasm_import_module = "compose_rust_time")]
443 unsafe extern "C" {
444 fn now_millis() -> f64;
446 fn utc_offset_minutes(millis: f64) -> i32;
448 fn wake_after(millis: f64);
451 }
452
453 pub(super) fn now() -> SystemTime {
454 let millis = unsafe { now_millis() };
456 UNIX_EPOCH + Duration::from_millis(millis.max(0.0) as u64)
457 }
458
459 pub(super) fn utc_offset_seconds(seconds: i64) -> i32 {
460 unsafe { utc_offset_minutes(seconds as f64 * 1000.0) * 60 }
462 }
463
464 pub(super) fn changed() {}
465
466 thread_local! {
467 static DUE: Cell<f64> = const { Cell::new(0.0) };
470 }
471
472 pub(super) fn arm() {
473 schedule();
474 }
475
476 fn schedule() {
477 let wait = (until_midnight(&now_local()).min(super::LONGEST_WAIT) + PAST_MIDNIGHT)
480 .as_millis() as f64;
481 unsafe {
483 DUE.with(|due| due.set(now_millis() + wait));
484 wake_after(wait);
485 }
486 }
487
488 pub(crate) fn frame() {
491 let armed = {
492 let mut watch = watch::lock();
493 if watch.subscribers.is_empty() {
494 watch.armed = false;
495 }
496 watch.armed
497 };
498 if !armed || unsafe { now_millis() } < DUE.with(Cell::get) {
500 return;
501 }
502 watch::check();
503 schedule();
504 }
505}
506
507#[cfg(target_family = "wasm")]
510pub(crate) fn on_frame() {
511 platform::frame();
512}