1use crate::ticks::Tick;
7
8const MONTH_ABBR: [&str; 12] = [
9 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
10];
11
12pub fn format_unix_tick(ts: f64, span_secs: f64) -> String {
16 if !ts.is_finite() {
17 return String::new();
18 }
19 let (y, m, d, hh, mm, ss) = civil_from_unix(ts.floor() as i64);
20 if span_secs >= 86400.0 * 60.0 {
21 format!("{y:04}-{m:02}")
22 } else if span_secs >= 86400.0 * 2.0 {
23 format!("{y:04}-{m:02}-{d:02}")
24 } else if span_secs >= 3600.0 * 6.0 {
25 format!("{m:02}-{d:02} {hh:02}h")
26 } else if span_secs >= 60.0 {
27 format!("{hh:02}:{mm:02}")
28 } else {
29 format!("{hh:02}:{mm:02}:{ss:02}")
30 }
31}
32
33pub fn format_concise_datetime_ticks(values: &[f64]) -> (Vec<String>, Option<String>) {
39 if values.is_empty() {
40 return (Vec::new(), None);
41 }
42 let civils: Vec<(i32, u32, u32, u32, u32, u32)> = values
43 .iter()
44 .map(|&v| {
45 if v.is_finite() {
46 civil_from_unix(v.floor() as i64)
47 } else {
48 (0, 1, 1, 0, 0, 0)
49 }
50 })
51 .collect();
52
53 let mut level = 5usize;
55 for lv in (0..=5).rev() {
56 let mut unique = Vec::new();
57 for c in &civils {
58 let part = match lv {
59 0 => c.0 as i64,
60 1 => c.1 as i64,
61 2 => c.2 as i64,
62 3 => c.3 as i64,
63 4 => c.4 as i64,
64 _ => c.5 as i64,
65 };
66 if !unique.contains(&part) {
67 unique.push(part);
68 }
69 }
70 if unique.len() > 1 {
71 level = lv;
72 break;
73 }
74 if lv == 0 {
75 level = 5;
76 }
77 }
78
79 let labels: Vec<String> = civils
80 .iter()
81 .map(|&(y, m, d, hh, mm, ss)| match level {
82 0 => format!("{y:04}"),
83 1 if m == 1 => format!("{y:04}"),
84 1 => month_abbr(m).to_string(),
85 2 if d == 1 => month_abbr(m).to_string(),
86 2 => format!("{d:02}"),
87 3 if hh == 0 => format!("{}-{d:02}", month_abbr(m)),
88 3 | 4 => format!("{hh:02}:{mm:02}"),
89 5 if ss == 0 && mm == 0 => format!("{hh:02}:{mm:02}"),
90 _ => format!("{hh:02}:{mm:02}:{ss:02}"),
91 })
92 .collect();
93
94 let offset = match level {
95 0 => None,
96 1 => civils.last().map(|&(y, _, _, _, _, _)| format!("{y:04}")),
97 2 => civils
98 .last()
99 .map(|&(y, m, _, _, _, _)| format!("{y:04}-{}", month_abbr(m))),
100 3 | 4 => civils
101 .last()
102 .map(|&(y, m, d, _, _, _)| format!("{y:04}-{}-{d:02}", month_abbr(m))),
103 _ => civils.last().map(|&(y, m, d, hh, mm, _)| {
104 format!("{y:04}-{}-{d:02} {hh:02}:{mm:02}", month_abbr(m))
105 }),
106 };
107
108 (labels, offset)
109}
110
111fn month_abbr(m: u32) -> &'static str {
112 MONTH_ABBR
113 .get((m.saturating_sub(1) as usize).min(11))
114 .copied()
115 .unwrap_or("Jan")
116}
117
118#[derive(Debug, Clone, Copy)]
120pub struct DatetimeLocator {
121 pub target_count: usize,
122}
123
124impl Default for DatetimeLocator {
125 fn default() -> Self {
126 Self { target_count: 6 }
127 }
128}
129
130impl DatetimeLocator {
131 pub fn new(target_count: usize) -> Self {
132 Self {
133 target_count: target_count.max(2),
134 }
135 }
136
137 pub fn ticks(&self, min: f64, max: f64) -> Vec<Tick> {
139 let (min, max) = if min <= max { (min, max) } else { (max, min) };
140 if !min.is_finite() || !max.is_finite() {
141 return Vec::new();
142 }
143 let span = (max - min).max(1.0);
144 let rough = span / (self.target_count as f64 - 1.0).max(1.0);
145 let unit = choose_unit(rough);
146
147 let values = match unit {
148 TimeUnit::Fixed(step) => fixed_step_ticks(min, max, step),
149 TimeUnit::Month(n) => month_ticks(min, max, n),
150 TimeUnit::Year(n) => year_ticks(min, max, n),
151 };
152
153 let (labels, _offset) = format_concise_datetime_ticks(&values);
154 values
156 .into_iter()
157 .zip(labels)
158 .map(|(value, label)| Tick { label, value })
159 .collect()
160 }
161}
162
163#[derive(Debug, Clone, Copy)]
164enum TimeUnit {
165 Fixed(f64),
166 Month(u32),
167 Year(u32),
168}
169
170fn choose_unit(rough: f64) -> TimeUnit {
171 const SEC: f64 = 1.0;
172 const MIN: f64 = 60.0;
173 const HOUR: f64 = 3600.0;
174 const DAY: f64 = 86_400.0;
175 const WEEK: f64 = 7.0 * DAY;
176 const MONTH: f64 = 30.0 * DAY;
177 const YEAR: f64 = 365.25 * DAY;
178
179 let candidates: &[(f64, TimeUnit)] = &[
180 (1.0 * SEC, TimeUnit::Fixed(1.0)),
181 (2.0 * SEC, TimeUnit::Fixed(2.0)),
182 (5.0 * SEC, TimeUnit::Fixed(5.0)),
183 (10.0 * SEC, TimeUnit::Fixed(10.0)),
184 (15.0 * SEC, TimeUnit::Fixed(15.0)),
185 (30.0 * SEC, TimeUnit::Fixed(30.0)),
186 (1.0 * MIN, TimeUnit::Fixed(MIN)),
187 (2.0 * MIN, TimeUnit::Fixed(2.0 * MIN)),
188 (5.0 * MIN, TimeUnit::Fixed(5.0 * MIN)),
189 (10.0 * MIN, TimeUnit::Fixed(10.0 * MIN)),
190 (15.0 * MIN, TimeUnit::Fixed(15.0 * MIN)),
191 (30.0 * MIN, TimeUnit::Fixed(30.0 * MIN)),
192 (1.0 * HOUR, TimeUnit::Fixed(HOUR)),
193 (2.0 * HOUR, TimeUnit::Fixed(2.0 * HOUR)),
194 (3.0 * HOUR, TimeUnit::Fixed(3.0 * HOUR)),
195 (6.0 * HOUR, TimeUnit::Fixed(6.0 * HOUR)),
196 (12.0 * HOUR, TimeUnit::Fixed(12.0 * HOUR)),
197 (1.0 * DAY, TimeUnit::Fixed(DAY)),
198 (2.0 * DAY, TimeUnit::Fixed(2.0 * DAY)),
199 (1.0 * WEEK, TimeUnit::Fixed(WEEK)),
200 (1.0 * MONTH, TimeUnit::Month(1)),
201 (2.0 * MONTH, TimeUnit::Month(2)),
202 (3.0 * MONTH, TimeUnit::Month(3)),
203 (6.0 * MONTH, TimeUnit::Month(6)),
204 (1.0 * YEAR, TimeUnit::Year(1)),
205 (2.0 * YEAR, TimeUnit::Year(2)),
206 (5.0 * YEAR, TimeUnit::Year(5)),
207 (10.0 * YEAR, TimeUnit::Year(10)),
208 ];
209
210 let mut best = candidates[0].1;
211 let mut best_score = f64::INFINITY;
212 for &(size, unit) in candidates {
213 let score = (size - rough).abs() / rough.max(1.0);
214 let score = if size < rough { score + 0.15 } else { score };
216 if score < best_score {
217 best_score = score;
218 best = unit;
219 }
220 }
221 best
222}
223
224fn fixed_step_ticks(min: f64, max: f64, step: f64) -> Vec<f64> {
225 if step <= 0.0 || !step.is_finite() {
226 return vec![min, max];
227 }
228 let start = (min / step).ceil() * step;
229 let mut out = Vec::new();
230 let mut v = start;
231 let mut guard = 0;
232 while v <= max + step * 1e-9 && guard < 64 {
233 if v >= min - step * 1e-9 {
234 out.push(v.clamp(min, max));
235 }
236 v += step;
237 guard += 1;
238 }
239 if out.is_empty() {
240 out.push(min);
241 if (max - min).abs() > 1e-9 {
242 out.push(max);
243 }
244 }
245 dedup_close(&mut out, step * 1e-6);
246 out
247}
248
249fn month_ticks(min: f64, max: f64, every: u32) -> Vec<f64> {
250 let every = every.max(1);
251 let (y, m, _, _, _, _) = civil_from_unix(min.floor() as i64);
252 let mut cy = y;
253 let mut cm = m;
254 let mut t = unix_from_civil(cy, cm, 1, 0, 0, 0) as f64;
256 if t < min {
257 advance_months(&mut cy, &mut cm, 1);
258 t = unix_from_civil(cy, cm, 1, 0, 0, 0) as f64;
259 }
260 let month_index = (cy * 12 + cm as i32 - 1) as i64;
262 let rem = month_index.rem_euclid(every as i64);
263 if rem != 0 {
264 advance_months(&mut cy, &mut cm, (every as i64 - rem) as u32);
265 t = unix_from_civil(cy, cm, 1, 0, 0, 0) as f64;
266 }
267
268 let mut out = Vec::new();
269 let mut guard = 0;
270 while t <= max + 1.0 && guard < 64 {
271 if t >= min - 1.0 {
272 out.push(t.clamp(min, max));
273 }
274 advance_months(&mut cy, &mut cm, every);
275 t = unix_from_civil(cy, cm, 1, 0, 0, 0) as f64;
276 guard += 1;
277 }
278 if out.is_empty() {
279 out.push(min);
280 }
281 out
282}
283
284fn year_ticks(min: f64, max: f64, every: u32) -> Vec<f64> {
285 let every = every.max(1) as i32;
286 let (y, _, _, _, _, _) = civil_from_unix(min.floor() as i64);
287 let mut cy = y;
288 let mut t = unix_from_civil(cy, 1, 1, 0, 0, 0) as f64;
289 if t < min {
290 cy += 1;
291 t = unix_from_civil(cy, 1, 1, 0, 0, 0) as f64;
292 }
293 let rem = cy.rem_euclid(every);
294 if rem != 0 {
295 cy += every - rem;
296 t = unix_from_civil(cy, 1, 1, 0, 0, 0) as f64;
297 }
298
299 let mut out = Vec::new();
300 let mut guard = 0;
301 while t <= max + 1.0 && guard < 64 {
302 if t >= min - 1.0 {
303 out.push(t.clamp(min, max));
304 }
305 cy += every;
306 t = unix_from_civil(cy, 1, 1, 0, 0, 0) as f64;
307 guard += 1;
308 }
309 if out.is_empty() {
310 out.push(min);
311 }
312 out
313}
314
315fn advance_months(y: &mut i32, m: &mut u32, n: u32) {
316 let idx = *y as i64 * 12 + (*m as i64 - 1) + n as i64;
317 *y = (idx.div_euclid(12)) as i32;
318 *m = (idx.rem_euclid(12) + 1) as u32;
319}
320
321fn dedup_close(values: &mut Vec<f64>, eps: f64) {
322 if values.is_empty() {
323 return;
324 }
325 let mut out = vec![values[0]];
326 for &v in values.iter().skip(1) {
327 if (v - *out.last().unwrap()).abs() > eps {
328 out.push(v);
329 }
330 }
331 *values = out;
332}
333
334pub fn civil_from_unix(ts: i64) -> (i32, u32, u32, u32, u32, u32) {
336 let secs_per_day = 86_400_i64;
337 let mut days = ts.div_euclid(secs_per_day);
338 let mut sod = ts.rem_euclid(secs_per_day);
339 if sod < 0 {
340 sod += secs_per_day;
341 days -= 1;
342 }
343 let (y, m, d) = civil_from_days(days);
344 let hh = (sod / 3600) as u32;
345 let mm = ((sod % 3600) / 60) as u32;
346 let ss = (sod % 60) as u32;
347 (y, m, d, hh, mm, ss)
348}
349
350pub fn unix_from_civil(y: i32, m: u32, d: u32, hh: u32, mm: u32, ss: u32) -> i64 {
352 let days = days_from_civil(y, m, d);
353 days * 86_400 + i64::from(hh) * 3600 + i64::from(mm) * 60 + i64::from(ss)
354}
355
356fn civil_from_days(z: i64) -> (i32, u32, u32) {
358 let z = z + 719_468;
359 let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
360 let doe = (z - era * 146_097) as u64;
361 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
362 let y = (yoe as i64) + era * 400;
363 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
364 let mp = (5 * doy + 2) / 153;
365 let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
366 let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
367 let y = if m <= 2 { y + 1 } else { y };
368 (y as i32, m, d)
369}
370
371fn days_from_civil(y: i32, m: u32, d: u32) -> i64 {
373 let y = if m <= 2 { y - 1 } else { y };
374 let era = if y >= 0 { y } else { y - 399 } / 400;
375 let yoe = (y - era * 400) as u32;
376 let mp = if m > 2 { m - 3 } else { m + 9 };
377 let doy = (153 * mp + 2) / 5 + d - 1;
378 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
379 i64::from(era) * 146_097 + i64::from(doe) - 719_468
380}
381
382#[cfg(test)]
383mod tests {
384 use super::*;
385
386 #[test]
387 fn epoch_is_1970_01_01() {
388 let (y, m, d, hh, mm, ss) = civil_from_unix(0);
389 assert_eq!((y, m, d, hh, mm, ss), (1970, 1, 1, 0, 0, 0));
390 }
391
392 #[test]
393 fn known_date() {
394 let (y, m, d, _, _, _) = civil_from_unix(1_577_836_800);
396 assert_eq!((y, m, d), (2020, 1, 1));
397 }
398
399 #[test]
400 fn roundtrip_civil_unix() {
401 let ts = unix_from_civil(2020, 1, 1, 12, 30, 45);
402 let (y, m, d, hh, mm, ss) = civil_from_unix(ts);
403 assert_eq!((y, m, d, hh, mm, ss), (2020, 1, 1, 12, 30, 45));
404 }
405
406 #[test]
407 fn daily_ticks_land_on_midnight() {
408 let start = 1_577_836_800.0; let end = start + 10.0 * 86_400.0;
410 let ticks = DatetimeLocator::new(6).ticks(start, end);
411 assert!(ticks.len() >= 3);
412 for t in &ticks {
413 let (_, _, _, hh, mm, ss) = civil_from_unix(t.value as i64);
414 assert_eq!((hh, mm, ss), (0, 0, 0), "tick {}", t.value);
415 }
416 }
417
418 #[test]
419 fn concise_day_span_labels() {
420 let start = 1_577_836_800.0; let vals: Vec<f64> = (0..6).map(|i| start + (i * 2) as f64 * 86_400.0).collect();
422 let (labels, offset) = format_concise_datetime_ticks(&vals);
423 assert_eq!(labels[0], "Jan");
424 assert_eq!(labels[1], "03");
425 assert_eq!(offset.as_deref(), Some("2020-Jan"));
426 }
427
428 #[test]
429 fn month_ticks_on_first() {
430 let start = unix_from_civil(2020, 1, 15, 0, 0, 0) as f64;
431 let end = unix_from_civil(2020, 8, 15, 0, 0, 0) as f64;
432 let ticks = DatetimeLocator::new(6).ticks(start, end);
433 assert!(ticks.len() >= 3);
434 for t in &ticks {
435 let (_, _, d, hh, mm, ss) = civil_from_unix(t.value.round() as i64);
436 if t.value > start + 1.0 && t.value < end - 1.0 {
438 assert_eq!((d, hh, mm, ss), (1, 0, 0, 0), "{}", t.label);
439 }
440 }
441 }
442}