ergonomic-windows 0.1.0

Ergonomic, safe Rust wrappers for Windows APIs - handles, processes, registry, file system, UI controls, Direct2D graphics, and more
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
//! Time and timer utilities.
//!
//! Provides safe wrappers for Windows high-resolution timers,
//! system time, and time zone information.

use crate::error::Result;
use std::time::Duration;
use windows::Win32::Foundation::{FILETIME, SYSTEMTIME};
use windows::Win32::System::Performance::{QueryPerformanceCounter, QueryPerformanceFrequency};
use windows::Win32::System::SystemInformation::{GetLocalTime, GetSystemTime, GetTickCount64};
use windows::Win32::System::Time::{
    FileTimeToSystemTime, GetTimeZoneInformation, SystemTimeToFileTime, TIME_ZONE_INFORMATION,
};

/// A high-resolution performance counter.
pub struct PerformanceCounter {
    frequency: i64,
}

impl PerformanceCounter {
    /// Creates a new performance counter.
    pub fn new() -> Result<Self> {
        let mut frequency = 0i64;
        // SAFETY: QueryPerformanceFrequency is safe with valid output parameter
        unsafe {
            QueryPerformanceFrequency(&mut frequency)?;
        }
        Ok(Self { frequency })
    }

    /// Gets the current counter value.
    pub fn now(&self) -> Result<i64> {
        let mut count = 0i64;
        // SAFETY: QueryPerformanceCounter is safe with valid output parameter
        unsafe {
            QueryPerformanceCounter(&mut count)?;
        }
        Ok(count)
    }

    /// Calculates the elapsed time between two counter values.
    pub fn elapsed(&self, start: i64, end: i64) -> Duration {
        let delta = end - start;
        let secs = delta / self.frequency;
        let nanos = ((delta % self.frequency) * 1_000_000_000) / self.frequency;
        Duration::new(secs as u64, nanos as u32)
    }

    /// Gets the frequency of the counter (counts per second).
    pub fn frequency(&self) -> i64 {
        self.frequency
    }

    /// Measures the duration of a closure.
    pub fn measure<F, R>(&self, f: F) -> Result<(R, Duration)>
    where
        F: FnOnce() -> R,
    {
        let start = self.now()?;
        let result = f();
        let end = self.now()?;
        Ok((result, self.elapsed(start, end)))
    }
}

impl Default for PerformanceCounter {
    fn default() -> Self {
        Self::new().expect("Failed to create performance counter")
    }
}

/// Gets the number of milliseconds since the system started.
pub fn tick_count() -> u64 {
    // SAFETY: GetTickCount64 has no preconditions
    unsafe { GetTickCount64() }
}

/// System time with date and time components.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SystemTime {
    /// Year (1601-30827).
    pub year: u16,
    /// Month (1-12).
    pub month: u16,
    /// Day of week (0 = Sunday, 6 = Saturday).
    pub day_of_week: u16,
    /// Day of month (1-31).
    pub day: u16,
    /// Hour (0-23).
    pub hour: u16,
    /// Minute (0-59).
    pub minute: u16,
    /// Second (0-59).
    pub second: u16,
    /// Milliseconds (0-999).
    pub milliseconds: u16,
}

impl SystemTime {
    /// Gets the current system time (UTC).
    pub fn now_utc() -> Self {
        // SAFETY: GetSystemTime is safe and always succeeds
        let st = unsafe { GetSystemTime() };
        Self::from_windows(st)
    }

    /// Gets the current local time.
    pub fn now_local() -> Self {
        // SAFETY: GetLocalTime is safe and always succeeds
        let st = unsafe { GetLocalTime() };
        Self::from_windows(st)
    }

    fn from_windows(st: SYSTEMTIME) -> Self {
        Self {
            year: st.wYear,
            month: st.wMonth,
            day_of_week: st.wDayOfWeek,
            day: st.wDay,
            hour: st.wHour,
            minute: st.wMinute,
            second: st.wSecond,
            milliseconds: st.wMilliseconds,
        }
    }

    fn into_windows(self) -> SYSTEMTIME {
        SYSTEMTIME {
            wYear: self.year,
            wMonth: self.month,
            wDayOfWeek: self.day_of_week,
            wDay: self.day,
            wHour: self.hour,
            wMinute: self.minute,
            wSecond: self.second,
            wMilliseconds: self.milliseconds,
        }
    }

    /// Converts to a file time (100-nanosecond intervals since Jan 1, 1601).
    pub fn to_file_time(&self) -> Result<u64> {
        let st = (*self).into_windows();
        let mut ft = FILETIME::default();
        // SAFETY: SystemTimeToFileTime is safe with valid parameters
        unsafe {
            SystemTimeToFileTime(&st, &mut ft)?;
        }
        Ok(((ft.dwHighDateTime as u64) << 32) | (ft.dwLowDateTime as u64))
    }

    /// Creates from a file time.
    pub fn from_file_time(file_time: u64) -> Result<Self> {
        let ft = FILETIME {
            dwLowDateTime: file_time as u32,
            dwHighDateTime: (file_time >> 32) as u32,
        };
        let mut st = SYSTEMTIME::default();
        // SAFETY: FileTimeToSystemTime is safe with valid parameters
        unsafe {
            FileTimeToSystemTime(&ft, &mut st)?;
        }
        Ok(Self::from_windows(st))
    }

    /// Returns the day name.
    pub fn day_name(&self) -> &'static str {
        match self.day_of_week {
            0 => "Sunday",
            1 => "Monday",
            2 => "Tuesday",
            3 => "Wednesday",
            4 => "Thursday",
            5 => "Friday",
            6 => "Saturday",
            _ => "Unknown",
        }
    }

    /// Returns the month name.
    pub fn month_name(&self) -> &'static str {
        match self.month {
            1 => "January",
            2 => "February",
            3 => "March",
            4 => "April",
            5 => "May",
            6 => "June",
            7 => "July",
            8 => "August",
            9 => "September",
            10 => "October",
            11 => "November",
            12 => "December",
            _ => "Unknown",
        }
    }
}

impl std::fmt::Display for SystemTime {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:03}",
            self.year, self.month, self.day, self.hour, self.minute, self.second, self.milliseconds
        )
    }
}

/// Time zone status.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TimeZoneStatus {
    /// Time zone uses standard time.
    Standard,
    /// Time zone uses daylight saving time.
    Daylight,
    /// Time zone status is unknown.
    Unknown,
}

/// Time zone information.
#[derive(Debug)]
pub struct TimeZone {
    /// Bias in minutes from UTC.
    pub bias: i32,
    /// Standard time name.
    pub standard_name: String,
    /// Standard time bias in minutes.
    pub standard_bias: i32,
    /// Daylight time name.
    pub daylight_name: String,
    /// Daylight time bias in minutes.
    pub daylight_bias: i32,
    /// Current status.
    pub status: TimeZoneStatus,
}

impl TimeZone {
    /// Gets the current time zone information.
    pub fn current() -> Result<Self> {
        let mut tzi = TIME_ZONE_INFORMATION::default();
        // SAFETY: GetTimeZoneInformation is safe
        let result = unsafe { GetTimeZoneInformation(&mut tzi) };

        // TIME_ZONE_ID_UNKNOWN = 0, TIME_ZONE_ID_STANDARD = 1, TIME_ZONE_ID_DAYLIGHT = 2
        let status = match result {
            1 => TimeZoneStatus::Standard,
            2 => TimeZoneStatus::Daylight,
            _ => TimeZoneStatus::Unknown,
        };

        let standard_name = String::from_utf16_lossy(
            &tzi.StandardName[..tzi.StandardName.iter().position(|&c| c == 0).unwrap_or(32)],
        );
        let daylight_name = String::from_utf16_lossy(
            &tzi.DaylightName[..tzi.DaylightName.iter().position(|&c| c == 0).unwrap_or(32)],
        );

        Ok(Self {
            bias: tzi.Bias,
            standard_name,
            standard_bias: tzi.StandardBias,
            daylight_name,
            daylight_bias: tzi.DaylightBias,
            status,
        })
    }

    /// Gets the total bias (including daylight bias if applicable) in minutes.
    pub fn total_bias(&self) -> i32 {
        match self.status {
            TimeZoneStatus::Daylight => self.bias + self.daylight_bias,
            _ => self.bias + self.standard_bias,
        }
    }

    /// Gets the UTC offset as a duration.
    pub fn utc_offset(&self) -> Duration {
        Duration::from_secs((self.total_bias().abs() * 60) as u64)
    }

    /// Returns true if currently in daylight saving time.
    pub fn is_daylight_saving(&self) -> bool {
        self.status == TimeZoneStatus::Daylight
    }
}

/// A simple stopwatch for measuring elapsed time.
pub struct Stopwatch {
    counter: PerformanceCounter,
    start: i64,
    elapsed: Duration,
    running: bool,
}

impl Stopwatch {
    /// Creates and starts a new stopwatch.
    pub fn start_new() -> Result<Self> {
        let counter = PerformanceCounter::new()?;
        let start = counter.now()?;
        Ok(Self {
            counter,
            start,
            elapsed: Duration::ZERO,
            running: true,
        })
    }

    /// Creates a new stopped stopwatch.
    pub fn new() -> Result<Self> {
        let counter = PerformanceCounter::new()?;
        Ok(Self {
            counter,
            start: 0,
            elapsed: Duration::ZERO,
            running: false,
        })
    }

    /// Starts or resumes the stopwatch.
    pub fn start(&mut self) -> Result<()> {
        if !self.running {
            self.start = self.counter.now()?;
            self.running = true;
        }
        Ok(())
    }

    /// Stops the stopwatch.
    pub fn stop(&mut self) -> Result<()> {
        if self.running {
            let end = self.counter.now()?;
            self.elapsed += self.counter.elapsed(self.start, end);
            self.running = false;
        }
        Ok(())
    }

    /// Resets the stopwatch.
    pub fn reset(&mut self) {
        self.elapsed = Duration::ZERO;
        self.running = false;
    }

    /// Restarts the stopwatch (reset + start).
    pub fn restart(&mut self) -> Result<()> {
        self.reset();
        self.start()
    }

    /// Gets the elapsed time.
    pub fn elapsed(&self) -> Result<Duration> {
        if self.running {
            let end = self.counter.now()?;
            Ok(self.elapsed + self.counter.elapsed(self.start, end))
        } else {
            Ok(self.elapsed)
        }
    }

    /// Returns true if the stopwatch is running.
    pub fn is_running(&self) -> bool {
        self.running
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_performance_counter() {
        let counter = PerformanceCounter::new().unwrap();
        assert!(counter.frequency() > 0);

        let start = counter.now().unwrap();
        std::thread::sleep(Duration::from_millis(10));
        let end = counter.now().unwrap();

        let elapsed = counter.elapsed(start, end);
        assert!(elapsed >= Duration::from_millis(5));
    }

    #[test]
    fn test_tick_count() {
        let t1 = tick_count();
        std::thread::sleep(Duration::from_millis(50));
        let t2 = tick_count();
        // Allow for some tolerance - t2 should be >= t1
        assert!(t2 >= t1, "tick_count should be monotonically increasing");
    }

    #[test]
    fn test_system_time() {
        let utc = SystemTime::now_utc();
        let local = SystemTime::now_local();

        assert!(utc.year >= 2024);
        assert!(local.year >= 2024);
        assert!(utc.month >= 1 && utc.month <= 12);
    }

    #[test]
    fn test_time_zone() {
        let tz = TimeZone::current().unwrap();
        // Bias should be reasonable (within +/- 14 hours)
        assert!(tz.bias.abs() <= 14 * 60);
    }

    #[test]
    fn test_stopwatch() {
        let mut sw = Stopwatch::start_new().unwrap();
        std::thread::sleep(Duration::from_millis(10));
        sw.stop().unwrap();

        let elapsed = sw.elapsed().unwrap();
        assert!(elapsed >= Duration::from_millis(5));

        // After stop, elapsed should not change
        std::thread::sleep(Duration::from_millis(10));
        let elapsed2 = sw.elapsed().unwrap();
        assert_eq!(elapsed, elapsed2);
    }
}