1use std::io;
15#[cfg(any(target_os = "linux", test))]
16use std::sync::atomic::{AtomicBool, Ordering};
17use std::time::Duration;
18
19use crate::MacAddress;
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub struct Received {
24 pub source: MacAddress,
25 pub length: usize,
27 pub time: Option<Duration>,
30}
31
32pub struct StampedSocket {
35 inner: platform::StampedSocket,
36}
37
38impl StampedSocket {
39 pub fn open(interface: &str, ethertype: u16) -> io::Result<Self> {
42 Ok(Self {
43 inner: platform::StampedSocket::open(interface, ethertype)?,
44 })
45 }
46
47 pub fn join_multicast(&self, group: MacAddress) -> io::Result<()> {
49 self.inner.join_multicast(group)
50 }
51
52 pub fn send(&self, destination: MacAddress, payload: &[u8]) -> io::Result<()> {
54 self.inner.send(destination, payload)
55 }
56
57 pub fn send_stamped(&self, destination: MacAddress, payload: &[u8]) -> io::Result<()> {
63 self.inner.send_stamped(destination, payload)
64 }
65
66 pub fn transmit_time(&self, timeout: Duration) -> io::Result<Option<Duration>> {
73 self.inner.transmit_time(timeout)
74 }
75
76 pub fn receive(
79 &self,
80 buffer: &mut [u8],
81 timeout: Option<Duration>,
82 ) -> io::Result<Option<Received>> {
83 self.inner.receive(buffer, timeout)
84 }
85}
86
87pub fn wait_any(sockets: &[&StampedSocket], timeout: Option<Duration>) -> io::Result<Vec<usize>> {
92 let inner: Vec<&platform::StampedSocket> = sockets.iter().map(|socket| &socket.inner).collect();
93 platform::wait_any(&inner, timeout)
94}
95
96#[cfg(target_os = "linux")]
100pub fn wait_any_or(
101 sockets: &[&StampedSocket],
102 also: std::os::fd::BorrowedFd<'_>,
103 timeout: Option<Duration>,
104) -> io::Result<(Vec<usize>, bool)> {
105 wait_any_with(sockets, &[also], timeout)
106 .map(|(readable, others)| (readable, !others.is_empty()))
107}
108
109#[cfg(target_os = "linux")]
113pub fn wait_any_with(
114 sockets: &[&StampedSocket],
115 others: &[std::os::fd::BorrowedFd<'_>],
116 timeout: Option<Duration>,
117) -> io::Result<(Vec<usize>, Vec<usize>)> {
118 let inner: Vec<&platform::StampedSocket> = sockets.iter().map(|socket| &socket.inner).collect();
119 platform::wait_any_or(&inner, others, timeout)
120}
121
122pub fn enable(interface: &str) -> io::Result<()> {
128 platform::enable(interface)
129}
130
131#[derive(Clone, Copy, Debug, PartialEq, Eq)]
133pub struct Setting {
134 pub tx_type: i32,
135 pub rx_filter: i32,
136}
137
138impl Setting {
139 pub fn is_enabled(&self) -> bool {
142 self.tx_type == 1 && self.rx_filter == 1
143 }
144}
145
146pub fn setting(interface: &str) -> io::Result<Setting> {
150 platform::setting(interface)
151}
152
153#[cfg(any(target_os = "linux", test))]
156fn raw_hardware(stamps: [(i64, i64); 3]) -> Option<Duration> {
157 let (seconds, nanoseconds) = stamps[2];
158 (seconds > 0 || nanoseconds > 0).then(|| Duration::new(seconds as u64, nanoseconds as u32))
159}
160
161#[cfg(any(target_os = "linux", test))]
164#[derive(Debug, PartialEq, Eq)]
165enum Taken {
166 Wanted,
168 Late,
170 Ahead(u32),
174}
175
176#[cfg(any(target_os = "linux", test))]
180fn taken(number: Option<u32>, wanted: u32, numbered: &AtomicBool) -> Taken {
181 let Some(number) = number else {
182 return Taken::Wanted;
183 };
184 if number != 0 {
185 numbered.store(true, Ordering::Relaxed);
186 }
187 if !numbered.load(Ordering::Relaxed) || number == wanted {
188 return Taken::Wanted;
189 }
190 if wanted.wrapping_sub(number) < 1 << 31 {
192 Taken::Late
193 } else {
194 Taken::Ahead(number)
195 }
196}
197
198#[cfg(target_os = "linux")]
199#[allow(unsafe_code)]
200mod platform {
201 use std::io;
202 use std::mem::{size_of, size_of_val, zeroed};
203 use std::os::fd::{AsRawFd, OwnedFd};
204 use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
205 use std::time::Duration;
206
207 use super::{Received, Taken, taken};
208 use crate::MacAddress;
209
210 const SO_TIMESTAMPING: libc::c_int = 37;
212 const SIOCSHWTSTAMP: libc::c_ulong = 0x89b0;
213 const SIOCGHWTSTAMP: libc::c_ulong = 0x89b1;
214 const HWTSTAMP_TX_ON: libc::c_int = 1;
215 const HWTSTAMP_FILTER_ALL: libc::c_int = 1;
216 const SOF_TIMESTAMPING_TX_HARDWARE: u32 = 1 << 0;
217 const SOF_TIMESTAMPING_RX_HARDWARE: u32 = 1 << 2;
218 const SOF_TIMESTAMPING_RAW_HARDWARE: u32 = 1 << 6;
219 const SOF_TIMESTAMPING_OPT_ID: u32 = 1 << 7;
222 const SOF_TIMESTAMPING_OPT_TSONLY: u32 = 1 << 11;
224 const PACKET_TX_TIMESTAMP: libc::c_int = 16;
227 const SO_EE_ORIGIN_TIMESTAMPING: u8 = 4;
228
229 #[repr(C)]
232 #[derive(Clone, Copy)]
233 #[allow(dead_code)]
234 struct ExtendedError {
235 errno: u32,
236 origin: u8,
237 kind: u8,
238 code: u8,
239 pad: u8,
240 info: u32,
241 data: u32,
242 }
243
244 #[repr(C)]
246 struct HardwareConfig {
247 flags: libc::c_int,
248 tx_type: libc::c_int,
249 rx_filter: libc::c_int,
250 }
251
252 pub fn enable(interface: &str) -> io::Result<()> {
253 let fd = crate::broker::open(crate::broker::Kind::Datagram)?;
254 let mut config = HardwareConfig {
255 flags: 0,
256 tx_type: 0,
257 rx_filter: 0,
258 };
259 if configure(&fd, interface, SIOCGHWTSTAMP, &mut config).is_ok()
260 && config.tx_type == HWTSTAMP_TX_ON
261 && config.rx_filter == HWTSTAMP_FILTER_ALL
262 {
263 return Ok(());
264 }
265 config = HardwareConfig {
266 flags: 0,
267 tx_type: HWTSTAMP_TX_ON,
268 rx_filter: HWTSTAMP_FILTER_ALL,
269 };
270 configure(&fd, interface, SIOCSHWTSTAMP, &mut config)
271 }
272
273 pub fn setting(interface: &str) -> io::Result<super::Setting> {
274 let fd = crate::broker::open(crate::broker::Kind::Datagram)?;
275 let mut config = HardwareConfig {
276 flags: 0,
277 tx_type: 0,
278 rx_filter: 0,
279 };
280 configure(&fd, interface, SIOCGHWTSTAMP, &mut config)?;
281 Ok(super::Setting {
282 tx_type: config.tx_type,
283 rx_filter: config.rx_filter,
284 })
285 }
286
287 fn configure(
290 fd: &OwnedFd,
291 interface: &str,
292 request_code: libc::c_ulong,
293 config: &mut HardwareConfig,
294 ) -> io::Result<()> {
295 let mut request: libc::ifreq = unsafe { zeroed() };
297 let name = interface.as_bytes();
298 if name.len() >= request.ifr_name.len() {
299 return Err(io::Error::new(
300 io::ErrorKind::InvalidInput,
301 "interface name too long",
302 ));
303 }
304 for (slot, octet) in request.ifr_name.iter_mut().zip(name) {
305 *slot = *octet as libc::c_char;
306 }
307 request.ifr_ifru.ifru_data = std::ptr::from_mut(config).cast();
308 if unsafe { libc::ioctl(fd.as_raw_fd(), request_code as _, &raw mut request) } < 0 {
311 return Err(io::Error::last_os_error());
312 }
313 Ok(())
314 }
315
316 pub struct StampedSocket {
317 fd: OwnedFd,
318 index: i32,
319 ethertype: u16,
320 stamped: AtomicU32,
323 numbered: AtomicBool,
327 }
328
329 fn timeout_ms(timeout: Option<Duration>) -> libc::c_int {
330 match timeout {
331 Some(timeout) => timeout.as_nanos().div_ceil(1_000_000).min(i32::MAX as u128) as i32,
333 None => -1,
334 }
335 }
336
337 fn wait(fd: &OwnedFd, events: libc::c_short, timeout: Option<Duration>) -> io::Result<bool> {
339 let mut poll = libc::pollfd {
340 fd: fd.as_raw_fd(),
341 events,
342 revents: 0,
343 };
344 let ready = unsafe { libc::poll(&raw mut poll, 1, timeout_ms(timeout)) };
346 if ready < 0 {
347 let error = io::Error::last_os_error();
348 return match error.kind() {
349 io::ErrorKind::Interrupted => Ok(false),
350 _ => Err(error),
351 };
352 }
353 Ok(ready > 0 && poll.revents & (events | libc::POLLERR) != 0)
354 }
355
356 pub fn wait_any(
357 sockets: &[&StampedSocket],
358 timeout: Option<Duration>,
359 ) -> io::Result<Vec<usize>> {
360 wait_any_or(sockets, &[], timeout).map(|(readable, _)| readable)
361 }
362
363 pub fn wait_any_or(
364 sockets: &[&StampedSocket],
365 others: &[std::os::fd::BorrowedFd<'_>],
366 timeout: Option<Duration>,
367 ) -> io::Result<(Vec<usize>, Vec<usize>)> {
368 let deadline = timeout.map(|timeout| std::time::Instant::now() + timeout);
369 let mut polls: Vec<libc::pollfd> = sockets
370 .iter()
371 .map(|socket| socket.fd.as_raw_fd())
372 .chain(others.iter().map(|other| other.as_raw_fd()))
373 .map(|fd| libc::pollfd {
374 fd,
375 events: libc::POLLIN,
376 revents: 0,
377 })
378 .collect();
379 loop {
380 let left = deadline
381 .map(|deadline| deadline.saturating_duration_since(std::time::Instant::now()));
382 let ready = unsafe {
385 libc::poll(
386 polls.as_mut_ptr(),
387 polls.len() as libc::nfds_t,
388 timeout_ms(left),
389 )
390 };
391 if ready < 0 {
392 let error = io::Error::last_os_error();
393 if error.kind() == io::ErrorKind::Interrupted {
394 continue;
395 }
396 return Err(error);
397 }
398 let readable: Vec<usize> = polls[..sockets.len()]
399 .iter()
400 .enumerate()
401 .filter(|(_, poll)| poll.revents & libc::POLLIN != 0)
402 .map(|(position, _)| position)
403 .collect();
404 let others_ready: Vec<usize> = polls[sockets.len()..]
405 .iter()
406 .enumerate()
407 .filter(|(_, poll)| poll.revents & (libc::POLLIN | libc::POLLERR) != 0)
408 .map(|(position, _)| position)
409 .collect();
410 for (socket, poll) in sockets.iter().zip(&polls) {
413 if poll.revents & libc::POLLERR != 0 {
414 socket.drop_late_times()?;
415 }
416 }
417 if !readable.is_empty()
418 || !others_ready.is_empty()
419 || ready == 0
420 || left.is_some_and(|left| left.is_zero())
421 {
422 return Ok((readable, others_ready));
423 }
424 }
425 }
426
427 struct Message {
430 length: usize,
431 time: Option<Duration>,
432 number: Option<u32>,
433 }
434
435 fn receive_message(
438 fd: &OwnedFd,
439 buffer: &mut [u8],
440 address: &mut libc::sockaddr_ll,
441 flags: libc::c_int,
442 ) -> io::Result<Option<Message>> {
443 let mut control = [0u64; 64];
444 let mut part = libc::iovec {
445 iov_base: buffer.as_mut_ptr().cast(),
446 iov_len: buffer.len(),
447 };
448 let mut message: libc::msghdr = unsafe { zeroed() };
450 message.msg_name = std::ptr::from_mut(address).cast();
451 message.msg_namelen = size_of::<libc::sockaddr_ll>() as libc::socklen_t;
452 message.msg_iov = &raw mut part;
453 message.msg_iovlen = 1;
454 message.msg_control = control.as_mut_ptr().cast();
455 message.msg_controllen = size_of_val(&control) as _;
456 let length =
459 unsafe { libc::recvmsg(fd.as_raw_fd(), &raw mut message, flags | libc::MSG_DONTWAIT) };
460 if length < 0 {
461 let error = io::Error::last_os_error();
462 return match error.kind() {
463 io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted => Ok(None),
464 _ => Err(error),
465 };
466 }
467 let mut time = None;
468 let mut number = None;
469 let mut header = unsafe { libc::CMSG_FIRSTHDR(&raw const message) };
473 while !header.is_null() {
474 let (level, kind, data) = unsafe {
476 (
477 (*header).cmsg_level,
478 (*header).cmsg_type,
479 libc::CMSG_DATA(header),
480 )
481 };
482 if level == libc::SOL_SOCKET && kind == SO_TIMESTAMPING {
483 let stamps: [libc::timespec; 3] = unsafe { std::ptr::read_unaligned(data.cast()) };
485 time = super::raw_hardware(stamps.map(|stamp| (stamp.tv_sec, stamp.tv_nsec)));
486 }
487 if level == libc::SOL_PACKET && kind == PACKET_TX_TIMESTAMP {
488 let error: ExtendedError = unsafe { std::ptr::read_unaligned(data.cast()) };
490 if error.origin == SO_EE_ORIGIN_TIMESTAMPING {
491 number = Some(error.data);
492 }
493 }
494 header = unsafe { libc::CMSG_NXTHDR(&raw const message, header) };
496 }
497 Ok(Some(Message {
498 length: length as usize,
499 time,
500 number,
501 }))
502 }
503
504 impl StampedSocket {
505 pub fn open(interface: &str, ethertype: u16) -> io::Result<Self> {
506 let index = crate::interfaces::index_of(interface).ok_or_else(|| {
507 io::Error::new(
508 io::ErrorKind::NotFound,
509 format!("no interface named {interface}"),
510 )
511 })?;
512 let fd = crate::broker::open(crate::broker::Kind::Datagram)?;
513 let flags = SOF_TIMESTAMPING_RX_HARDWARE
516 | SOF_TIMESTAMPING_RAW_HARDWARE
517 | SOF_TIMESTAMPING_OPT_ID
518 | SOF_TIMESTAMPING_OPT_TSONLY;
519 let value = flags as libc::c_int;
520 let set = unsafe {
523 libc::setsockopt(
524 fd.as_raw_fd(),
525 libc::SOL_SOCKET,
526 SO_TIMESTAMPING,
527 (&raw const value).cast(),
528 size_of::<libc::c_int>() as libc::socklen_t,
529 )
530 };
531 if set < 0 {
532 return Err(io::Error::last_os_error());
533 }
534 let socket = Self {
535 fd,
536 index,
537 ethertype,
538 stamped: AtomicU32::new(0),
539 numbered: AtomicBool::new(false),
540 };
541 let address = socket.address(None);
542 let bound = unsafe {
545 libc::bind(
546 socket.fd.as_raw_fd(),
547 (&raw const address).cast(),
548 size_of::<libc::sockaddr_ll>() as libc::socklen_t,
549 )
550 };
551 if bound < 0 {
552 return Err(io::Error::last_os_error());
553 }
554 Ok(socket)
555 }
556
557 fn address(&self, destination: Option<MacAddress>) -> libc::sockaddr_ll {
558 let mut address: libc::sockaddr_ll = unsafe { zeroed() };
560 address.sll_family = libc::AF_PACKET as u16;
561 address.sll_protocol = self.ethertype.to_be();
562 address.sll_ifindex = self.index;
563 if let Some(destination) = destination {
564 address.sll_halen = 6;
565 address.sll_addr[..6].copy_from_slice(&destination.0);
566 }
567 address
568 }
569
570 pub fn join_multicast(&self, group: MacAddress) -> io::Result<()> {
571 let mut request: libc::packet_mreq = unsafe { zeroed() };
573 request.mr_ifindex = self.index;
574 request.mr_type = libc::PACKET_MR_MULTICAST as u16;
575 request.mr_alen = 6;
576 request.mr_address[..6].copy_from_slice(&group.0);
577 let joined = unsafe {
580 libc::setsockopt(
581 self.fd.as_raw_fd(),
582 libc::SOL_PACKET,
583 libc::PACKET_ADD_MEMBERSHIP,
584 (&raw const request).cast(),
585 size_of::<libc::packet_mreq>() as libc::socklen_t,
586 )
587 };
588 if joined < 0 {
589 return Err(io::Error::last_os_error());
590 }
591 Ok(())
592 }
593
594 pub fn send(&self, destination: MacAddress, payload: &[u8]) -> io::Result<()> {
595 let address = self.address(Some(destination));
596 let sent = unsafe {
599 libc::sendto(
600 self.fd.as_raw_fd(),
601 payload.as_ptr().cast(),
602 payload.len(),
603 0,
604 (&raw const address).cast(),
605 size_of::<libc::sockaddr_ll>() as libc::socklen_t,
606 )
607 };
608 if sent < 0 {
609 return Err(io::Error::last_os_error());
610 }
611 Ok(())
612 }
613
614 fn drop_late_times(&self) -> io::Result<()> {
615 let mut stale: libc::sockaddr_ll = unsafe { zeroed() };
617 let mut buffer = [0u8; 64];
618 while receive_message(&self.fd, &mut buffer, &mut stale, libc::MSG_ERRQUEUE)?.is_some()
619 {
620 }
621 Ok(())
622 }
623
624 pub fn send_stamped(&self, destination: MacAddress, payload: &[u8]) -> io::Result<()> {
625 self.drop_late_times()?;
626 let mut address = self.address(Some(destination));
627 let mut part = libc::iovec {
628 iov_base: payload.as_ptr().cast_mut().cast(),
629 iov_len: payload.len(),
630 };
631 let mut control = [0u64; 4];
632 let mut message: libc::msghdr = unsafe { zeroed() };
634 message.msg_name = (&raw mut address).cast();
635 message.msg_namelen = size_of::<libc::sockaddr_ll>() as libc::socklen_t;
636 message.msg_iov = &raw mut part;
637 message.msg_iovlen = 1;
638 message.msg_control = control.as_mut_ptr().cast();
639 message.msg_controllen = unsafe { libc::CMSG_SPACE(size_of::<u32>() as u32) } as _;
641 unsafe {
644 let header = libc::CMSG_FIRSTHDR(&raw const message);
645 (*header).cmsg_level = libc::SOL_SOCKET;
646 (*header).cmsg_type = SO_TIMESTAMPING;
647 (*header).cmsg_len = libc::CMSG_LEN(size_of::<u32>() as u32) as _;
648 std::ptr::write_unaligned(
649 libc::CMSG_DATA(header).cast::<u32>(),
650 SOF_TIMESTAMPING_TX_HARDWARE,
651 );
652 }
653 if unsafe { libc::sendmsg(self.fd.as_raw_fd(), &raw const message, 0) } < 0 {
656 return Err(io::Error::last_os_error());
657 }
658 self.stamped.fetch_add(1, Ordering::Relaxed);
659 Ok(())
660 }
661
662 pub fn transmit_time(&self, timeout: Duration) -> io::Result<Option<Duration>> {
663 let deadline = std::time::Instant::now() + timeout;
664 let wanted = self.stamped.load(Ordering::Relaxed).wrapping_sub(1);
665 loop {
666 let mut address: libc::sockaddr_ll = unsafe { zeroed() };
668 let mut buffer = [0u8; 64];
669 if let Some(message) =
670 receive_message(&self.fd, &mut buffer, &mut address, libc::MSG_ERRQUEUE)?
671 {
672 match taken(message.number, wanted, &self.numbered) {
673 Taken::Late => continue,
674 Taken::Ahead(number) => {
675 self.stamped
676 .store(number.wrapping_add(1), Ordering::Relaxed);
677 }
678 Taken::Wanted => {}
679 }
680 return Ok(message.time);
681 }
682 let left = deadline.saturating_duration_since(std::time::Instant::now());
683 if left.is_zero() || !wait(&self.fd, 0, Some(left))? {
684 return Ok(None);
685 }
686 }
687 }
688
689 pub fn receive(
690 &self,
691 buffer: &mut [u8],
692 timeout: Option<Duration>,
693 ) -> io::Result<Option<Received>> {
694 if !wait(&self.fd, libc::POLLIN, timeout)? {
695 return Ok(None);
696 }
697 let mut address: libc::sockaddr_ll = unsafe { zeroed() };
699 loop {
700 let Some(Message { length, time, .. }) =
701 receive_message(&self.fd, buffer, &mut address, 0)?
702 else {
703 return Ok(None);
704 };
705 if address.sll_pkttype == libc::PACKET_OUTGOING {
707 continue;
708 }
709 let mut source = [0; 6];
710 source.copy_from_slice(&address.sll_addr[..6]);
711 return Ok(Some(Received {
712 source: MacAddress(source),
713 length: length.min(buffer.len()),
714 time,
715 }));
716 }
717 }
718 }
719}
720
721#[cfg(not(target_os = "linux"))]
722mod platform {
723 use std::io;
724 use std::time::Duration;
725
726 use super::Received;
727 use crate::MacAddress;
728
729 fn unsupported() -> io::Error {
730 io::Error::new(
731 io::ErrorKind::Unsupported,
732 "hardware time stamps are not supported on this system yet",
733 )
734 }
735
736 pub fn enable(_interface: &str) -> io::Result<()> {
737 Err(unsupported())
738 }
739
740 pub fn setting(_interface: &str) -> io::Result<super::Setting> {
741 Err(unsupported())
742 }
743
744 pub fn wait_any(
745 _sockets: &[&StampedSocket],
746 _timeout: Option<Duration>,
747 ) -> io::Result<Vec<usize>> {
748 Err(unsupported())
749 }
750
751 pub struct StampedSocket;
752
753 impl StampedSocket {
754 pub fn open(_interface: &str, _ethertype: u16) -> io::Result<Self> {
755 Err(unsupported())
756 }
757
758 pub fn join_multicast(&self, _group: MacAddress) -> io::Result<()> {
759 Err(unsupported())
760 }
761
762 pub fn send(&self, _destination: MacAddress, _payload: &[u8]) -> io::Result<()> {
763 Err(unsupported())
764 }
765
766 pub fn send_stamped(&self, _destination: MacAddress, _payload: &[u8]) -> io::Result<()> {
767 Err(unsupported())
768 }
769
770 pub fn transmit_time(&self, _timeout: Duration) -> io::Result<Option<Duration>> {
771 Err(unsupported())
772 }
773
774 pub fn receive(
775 &self,
776 _buffer: &mut [u8],
777 _timeout: Option<Duration>,
778 ) -> io::Result<Option<Received>> {
779 Err(unsupported())
780 }
781 }
782}
783
784#[cfg(test)]
785mod tests {
786 use super::*;
787
788 #[test]
789 fn a_setting_is_enabled_only_as_enable_sets_it() {
790 let setting = |tx_type, rx_filter| Setting { tx_type, rx_filter };
791 assert!(setting(1, 1).is_enabled());
792 assert!(!setting(1, 0).is_enabled(), "receive stamps off");
793 assert!(!setting(0, 1).is_enabled(), "send stamps off");
794 assert!(!setting(1, 12).is_enabled(), "PTPv2 event frames only");
795 }
796
797 #[cfg(target_os = "linux")]
798 #[test]
799 fn a_wait_wakes_for_the_other_too() {
800 use std::os::fd::AsFd;
801 use std::os::unix::net::UnixDatagram;
802 let (near, far) = UnixDatagram::pair().expect("pair");
803 let started = std::time::Instant::now();
804 let none = wait_any_or(&[], near.as_fd(), Some(Duration::from_millis(20))).expect("wait");
805 assert_eq!(none, (Vec::new(), false));
806 far.send(b"changed").expect("send");
807 let woken = wait_any_or(&[], near.as_fd(), Some(Duration::from_secs(5))).expect("wait");
808 assert_eq!(woken, (Vec::new(), true));
809 assert!(started.elapsed() < Duration::from_secs(1));
810 }
811
812 #[test]
813 fn a_time_sent_pairs_by_its_number_once_the_kernel_numbers_them() {
814 let numbered = AtomicBool::new(false);
815 assert_eq!(taken(None, 7, &numbered), Taken::Wanted);
816 assert_eq!(taken(Some(0), 0, &numbered), Taken::Wanted);
818 assert_eq!(taken(Some(0), 1, &numbered), Taken::Wanted);
819 assert_eq!(taken(Some(2), 2, &numbered), Taken::Wanted);
820 assert_eq!(taken(Some(1), 2, &numbered), Taken::Late);
821 assert_eq!(taken(Some(4), 3, &numbered), Taken::Ahead(4));
822 assert_eq!(taken(Some(u32::MAX), 0, &numbered), Taken::Late);
823 assert_eq!(taken(Some(0), u32::MAX, &numbered), Taken::Ahead(0));
824 }
825
826 #[test]
827 fn a_kernel_that_numbers_nothing_has_its_times_taken_in_order() {
828 let numbered = AtomicBool::new(false);
829 for wanted in 0..5 {
830 assert_eq!(taken(Some(0), wanted, &numbered), Taken::Wanted);
831 }
832 }
833
834 #[test]
835 fn the_raw_hardware_time_is_the_last_of_three() {
836 assert_eq!(
837 raw_hardware([(1_793_300_000, 5), (0, 0), (265_258, 495_597_656)]),
838 Some(Duration::new(265_258, 495_597_656))
839 );
840 assert_eq!(raw_hardware([(1_793_300_000, 5), (0, 0), (0, 0)]), None);
841 }
842}