@@ -18,18 +18,31 @@ ptr: *anyopaque,
1818/// Virtual table for the digital i/o functions.
1919vtable : * const VTable ,
2020
21- /// API
21+ /// Object created by make_timeout to perform to hold
22+ /// a duration.
23+ pub const Timeout = struct {
24+ clock : Clock_Device ,
25+ time : mdf.time.Absolute ,
26+
27+ pub fn is_reached (self : @This ()) bool {
28+ return self .clock .is_reached (self .time );
29+ }
30+
31+ pub fn diff (self : @This ()) mdf.time.Duration {
32+ return self .time .diff (self .clock .get_time_since_boot ());
33+ }
34+ };
35+
2236pub fn is_reached (td : Clock_Device , time : mdf.time.Absolute ) bool {
2337 const now = td .get_time_since_boot ();
2438 return time .is_reached_by (now );
2539}
2640
27- pub fn make_timeout (td : Clock_Device , timeout : mdf.time.Duration ) mdf.time.Absolute {
28- return @as (mdf .time .Absolute , @enumFromInt (td .get_time_since_boot ().to_us () + timeout .to_us ()));
29- }
30-
31- pub fn make_timeout_us (td : Clock_Device , timeout_us : u64 ) mdf.time.Absolute {
32- return @as (mdf .time .Absolute , @enumFromInt (td .get_time_since_boot ().to_us () + timeout_us ));
41+ pub fn make_timeout (td : Clock_Device , timeout : mdf.time.Duration ) Timeout {
42+ return .{
43+ .clock = td ,
44+ .time = td .get_time_since_boot ().add_duration (timeout ),
45+ };
3346}
3447
3548pub fn sleep_ms (td : Clock_Device , time_ms : u32 ) void {
@@ -44,8 +57,8 @@ pub fn sleep_us(td: Clock_Device, time_us: u64) void {
4457 }
4558
4659 // Otherwise, fall back to polling
47- const end_time = td .make_timeout_us ( time_us );
48- while (! td .is_reached (end_time )) {}
60+ const end_time = td .make_timeout (. from_us ( time_us ) );
61+ while (! end_time .is_reached ()) {}
4962}
5063
5164/// VTable methods
@@ -116,17 +129,17 @@ test Test_Device {
116129 ttd .elapse_time (2 );
117130 try std .testing .expectEqual (2 , td .get_time_since_boot ().to_us ());
118131
119- try std .testing .expect (! td .is_reached (@enumFromInt (4 )));
132+ // Time reached
133+ try std .testing .expect (! td .is_reached (.from_us (3 )));
120134 ttd .elapse_time (2 );
121- try std .testing .expect (td .is_reached (@enumFromInt ( 4 )));
135+ try std .testing .expect (td .is_reached (. from_us ( 3 )));
122136
123137 // Timeouts
124- try std .testing .expectEqual (
125- 54 ,
126- @intFromEnum (td .make_timeout (mdf .time .Duration .from_us (50 ))),
127- );
128- ttd .elapse_time (50 );
129- try std .testing .expectEqual (104 , @intFromEnum (td .make_timeout_us (50 )));
138+ const timeout = td .make_timeout (.from_us (50 ));
139+ ttd .elapse_time (40 );
140+ try std .testing .expectEqual (mdf .time .Duration .from_us (10 ), timeout .diff ());
141+ ttd .elapse_time (10 );
142+ try std .testing .expect (timeout .is_reached ());
130143
131144 try std .testing .expectEqual (0 , ttd .get_total_sleep_time ());
132145 td .sleep_ms (1000 );
0 commit comments