sntpc 0.11.0

Library for making SNTP requests
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
//! Rust SNTP client implementation
//!
//! # Overview
//!
//! This crate provides an async-first SNTP client for sending requests to NTP servers
//! and processing responses to extract accurate timestamps.
//!
//! Supported protocol version: [SNTPv4 (RFC 5905)](https://datatracker.ietf.org/doc/html/rfc5905)
//!
//! Note: RFC 5905 §14 defines `SNTPv4` and references RFC 4330 for SNTP client operational semantics.
//!
//! ## Quick Start
//!
//! Add to your `Cargo.toml`:
//! ```toml
//! [dependencies]
//! sntpc = "0.11"
//! ```
//!
//! For common usage patterns, choose a network adapter:
//! - [`sntpc-net-std`](https://docs.rs/sntpc-net-std) - Standard library UDP sockets
//! - [`sntpc-net-tokio`](https://docs.rs/sntpc-net-tokio) - Tokio async runtime
//! - [`sntpc-net-embassy`](https://docs.rs/sntpc-net-embassy) - Embassy embedded runtime
//! - [`sntpc-time-embassy`](https://docs.rs/sntpc-time-embassy) - Timestamp generation based on the `embassy-time` interface
//!
//! ## Features
//!
//! - `std` - Standard library support (includes [`StdTimestampGen`])
//! - `sync` - Synchronous API in [`sync`] module (default is async)
//! - `utils` - OS-specific utilities for system time sync ⚠️ **Unstable API**
//! - `log` - Debug logging via `log` crate
//! - `defmt` - Debug logging via `defmt` (mutually exclusive with `log`)
//! - `dispersion` - Compute total dispersion per RFC 5905 §9.2, exposed via [`NtpResult::dispersion`]
//!
//! <div class="warning">
//!
//! **Warning**: `log` and `defmt` are mutually exclusive features. If both are enabled,
//! `defmt` takes priority.
//! </div>
//!
//! ## Architecture
//!
//! The library is designed to work in both `std` and `no_std` environments through two key traits:
//! - [`NtpUdpSocket`] - Implement for your UDP socket type
//! - [`NtpTimestampGenerator`] - Implement for your timestamp source
//!
//! For `std` environments, [`StdTimestampGen`] is provided.
//!
//! ### API Approaches
//!
//! - [`get_time`] - Complete request/response in a single call (suitable for most cases)
//! - [`sntp_send_request`] and [`sntp_process_response`] - Split send/receive workflow
//!   (useful when the TCP/IP stack requires polling or has custom timing requirements)
//!
//! ## Limitations
//!
//! - **Broadcast mode** (NTP mode 5) is not supported. The library only supports unicast client mode (mode 3 → mode 4).
//!   For broadcast client requirements, see RFC 5905 §14.
//! - **Minimum poll interval**: Clients should not send requests at intervals less than one minute per RFC 4330 §5.
//!   The library does not enforce this; it is the caller's responsibility.
//! - **NTP era rollover**: `NtpResult.seconds` is `u64`. Wire timestamps roll
//!   over every `2^32` seconds; `sntpc` reconstructs the era as whichever of
//!   the nearest three eras (±2^31 seconds, ~68 years) around the timestamp
//!   generator's `timestamp_sec()` best matches the wire value. A pivot more
//!   than half an era off silently produces a wrong-era result — no error is
//!   raised. See the README's "NTP era rollover and embedded cold start"
//!   section for embedded cold-start guidance.
//!
//! ## Examples
//!
//! See the [examples directory](https://github.com/vpetrigo/sntpc/tree/master/examples) for complete examples:
//! - `simple-request` - Basic synchronous usage
//! - `tokio` - Async with tokio runtime
//! - `embassy-net` - Embedded async with embassy
//! - `smoltcp-request` - Custom `no_std` networking
//! - And more...
//!
//! Refer to individual function documentation for minimal code examples
#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(feature = "utils")]
pub mod utils;

mod log;
mod types;

pub use crate::types::*;

#[cfg(any(feature = "log", feature = "defmt"))]
use crate::log::debug;

use cfg_if::cfg_if;

use core::net;

/// Retrieves the current time from an NTP server.
///
/// This asynchronous function performs the complete SNTP flow:
/// sending a request to the specified NTP server and processing the server's response.
/// It calculates the roundtrip delay, time offset, and other relevant information.
///
/// # Arguments
///
/// * `addr` - The socket address (`SocketAddr`) of the NTP server.
/// * `socket` - A reference to an object implementing the [`NtpUdpSocket`] trait that allows
///   sending/receiving UDP packets.
/// * `context` - An SNTP context (`NtpContext<T>`) containing a timestamp generator that implements
///   the [`NtpTimestampGenerator`] trait. This ensures precise timestamp creation for request and response processing.
///
/// # Returns
///
/// Returns a `Result<NtpResult>`:
/// * `Ok(NtpResult)` - Successfully retrieved time from the server, including:
///   - Roundtrip delay
///   - Time offset
///   - Stratum level
///   - Precision
/// * `Err(Error)` - Encountered an error, such as:
///   - Network communication issues
///   - Incorrect or invalid server response
///
/// # Examples
///
/// Basic usage with standard library components:
///
/// ```no_run
/// use sntpc::{get_time, NtpContext, StdTimestampGen};
/// use std::net::SocketAddr;
///
/// # #[cfg(feature = "std")]
/// # async fn example() -> sntpc::Result<()> {
/// use sntpc_net_std::UdpSocketWrapper;
/// use std::net::UdpSocket;
///
/// let socket = UdpSocket::bind("0.0.0.0:0").expect("Unable to bind socket");
/// let socket = UdpSocketWrapper::new(socket);
/// let context = NtpContext::new(StdTimestampGen::default());
/// let addr: SocketAddr = "time.google.com:123".parse().unwrap();
///
/// let result = get_time(addr, &socket, context).await?;
/// println!("Time: {}.{}", result.sec(), result.sec_fraction());
/// # Ok(())
/// # }
/// ```
///
/// For custom implementations of [`NtpUdpSocket`] and [`NtpTimestampGenerator`],
/// see the examples in the repository, particularly `examples/smoltcp-request`
///
/// # Errors
///
/// This function returns an `Err` in any of the following cases:
/// * The SNTP packet could not be sent to the server.
/// * The response payload is invalid or indicates an error.
/// * Mismatch between the expected and actual server addresses.
pub async fn get_time<U, T>(addr: net::SocketAddr, socket: &U, context: NtpContext<T>) -> Result<NtpResult>
where
    U: NtpUdpSocket,
    T: NtpTimestampGenerator + Copy,
{
    let result = sntp_send_request(addr, socket, context).await?;

    sntp_process_response(addr, socket, context, result).await
}

/// Sends an SNTP request to an NTP server.
///
/// This function creates an SNTP packet using the given timestamp generator and
/// sends it to the given NTP server via the provided UDP socket.
///
/// # Arguments
///
/// * `dest` - The socket address (`SocketAddr`) of the NTP server.
/// * `socket` - A reference to an object implementing the [`NtpUdpSocket`] trait
///   that is used to send/receive UDP packets.
/// * `context` - An SNTP context (`NtpContext<T>`) containing a timestamp generator
///   that implements the [`NtpTimestampGenerator`] trait to provide a custom mechanism for generating timestamps.
///
/// # Returns
///
/// Returns a `Result<SendRequestResult>`:
/// * `Ok(SendRequestResult)` - If the packet was successfully sent, includes details
///   about the request, such as the originate timestamp.
/// * `Err(Error)` - If there was an error in sending the request, such as a network failure.
///
/// # Examples
///
/// For most use cases, prefer [`get_time`] which handles both sending and receiving.
/// Use this function directly only when you need split send/receive workflow:
///
/// ```no_run
/// use sntpc::{sntp_send_request, sntp_process_response, NtpContext, StdTimestampGen};
/// use std::net::SocketAddr;
///
/// # #[cfg(feature = "std")]
/// # async fn example() -> sntpc::Result<()> {
/// use sntpc_net_std::UdpSocketWrapper;
/// use std::net::UdpSocket;
///
/// let socket = UdpSocket::bind("0.0.0.0:0").expect("Unable to bind socket");
/// let socket = UdpSocketWrapper::new(socket);
/// let context = NtpContext::new(StdTimestampGen::default());
/// let addr: SocketAddr = "time.google.com:123".parse().unwrap();
///
/// let request_result = sntp_send_request(addr, &socket, context).await?;
/// // ... custom processing or polling here ...
/// let response = sntp_process_response(addr, &socket, context, request_result).await?;
/// # Ok(())
/// # }
/// ```
///
/// For custom implementations, see `examples/smoltcp-request`
///
/// # Errors
///
/// Returns `Err` if:
/// * The SNTP packet fails to send to the provided address due to network issues.
/// * The socket behavior does not conform to the expectations of the [`NtpUdpSocket`] trait.
pub async fn sntp_send_request<U, T>(
    dest: net::SocketAddr,
    socket: &U,
    context: NtpContext<T>,
) -> Result<SendRequestResult>
where
    U: NtpUdpSocket,
    T: NtpTimestampGenerator,
{
    #[cfg(any(feature = "log", feature = "defmt"))]
    debug!("send request - Address: {:?}", dest);
    let request = NtpPacket::new(context.timestamp_gen);

    send_request(dest, &request, socket).await?;
    Ok(SendRequestResult::from(request))
}

/// Processes the response from an NTP server.
///
/// This function validates the SNTP response, ensuring that it comes from the expected server and that
/// the payload size and structure are correct. It then calculates and returns the offset and
/// roundtrip delay based on the time information.
///
/// # Arguments
///
/// * `dest` - The expected socket address (`SocketAddr`) of the NTP server.
/// * `socket` - A reference to an object implementing the [`NtpUdpSocket`] trait
///   used for receiving the response.
/// * `context` - An SNTP context (`NtpContext<T>`) containing a timestamp generator
///   that manages internal time calculations.
/// * `send_req_result` - The result of the previously sent request, containing the originate timestamp
///   of the SNTP request.
///
/// # Returns
///
/// Returns a `Result<NtpResult>`:
/// * `Ok(NtpResult)` - If the response is valid, includes:
///   - Calculated clock offset
///   - Roundtrip delay
///   - Stratum level
///   - Precision level
/// * `Err(Error)` - On failure, for reasons such as:
///   - Mismatched server response address
///   - Invalid packet size or structure
///   - Incorrect mode or incorrect originate timestamp in the response
///
/// # Examples
///
/// This function is typically used in conjunction with [`sntp_send_request`]:
///
/// ```no_run
/// use sntpc::{sntp_send_request, sntp_process_response, NtpContext, StdTimestampGen};
/// use std::net::SocketAddr;
///
/// # #[cfg(feature = "std")]
/// # async fn example() -> sntpc::Result<()> {
/// use sntpc_net_std::UdpSocketWrapper;
/// use std::net::UdpSocket;
///
/// let socket = UdpSocket::bind("0.0.0.0:0").expect("Unable to bind socket");
/// let socket = UdpSocketWrapper::new(socket);
/// let context = NtpContext::new(StdTimestampGen::default());
/// let addr: SocketAddr = "time.google.com:123".parse().unwrap();
///
/// let request_result = sntp_send_request(addr, &socket, context).await?;
/// let response = sntp_process_response(addr, &socket, context, request_result).await?;
///
/// println!("Offset: {} µs, Roundtrip: {} µs", response.offset(), response.roundtrip());
/// # Ok(())
/// # }
/// ```
///
/// For complete examples, see [`get_time`] or `examples/smoltcp-request`
///
/// # Errors
///
/// This function returns an `Err` in any of the following situations:
/// * The source address of the response does not match the server address used for the request.
/// * The size of the response is incorrect or does not match the expected format.
/// * The mode or version in the response is invalid.
/// * `KoD` packets are surfaced as `Error::KissOfDeath(...)`; callers must apply
///   their own policy (e.g. stop using DENY/RSTR servers, back off on RATE).
pub async fn sntp_process_response<U, T>(
    dest: net::SocketAddr,
    socket: &U,
    mut context: NtpContext<T>,
    send_req_result: SendRequestResult,
) -> Result<NtpResult>
where
    U: NtpUdpSocket,
    T: NtpTimestampGenerator,
{
    let mut response_buf = RawNtpPacket::default();
    let (response, src) = socket.recv_from(response_buf.0.as_mut()).await?;
    context.timestamp_gen.init();
    let recv_unix_seconds = context.timestamp_gen.timestamp_sec();
    let recv_timestamp =
        ntp_wire_timestamp_from_unix(recv_unix_seconds, context.timestamp_gen.timestamp_subsec_micros());
    #[cfg(any(feature = "log", feature = "defmt"))]
    debug!("Response: {}", response);

    if dest != src {
        return Err(Error::ResponseAddressMismatch);
    }

    if response < NTP_PACKET_LEN {
        return Err(Error::IncorrectPayload);
    }

    let client_precision = context.timestamp_gen.precision();
    let result = process_response(
        send_req_result,
        response_buf,
        recv_timestamp,
        recv_unix_seconds,
        client_precision,
    );

    #[cfg(any(feature = "log", feature = "defmt"))]
    if let Ok(r) = &result {
        debug!("{:?}", r);
    }

    result
}

async fn send_request<U>(dest: net::SocketAddr, req: &NtpPacket, socket: &U) -> Result<()>
where
    U: NtpUdpSocket,
{
    let buf = RawNtpPacket::from(req);

    match socket.send_to(&buf.0, dest).await {
        Ok(size) => {
            if size == buf.0.len() {
                Ok(())
            } else {
                Err(Error::Network)
            }
        }
        Err(_) => Err(Error::Network),
    }
}

/// Synchronous interface for the SNTP client
#[cfg(feature = "sync")]
pub mod sync {
    #[cfg(any(feature = "log", feature = "defmt"))]
    use crate::log::debug;
    use crate::net;
    use crate::types::{NtpContext, NtpResult, NtpTimestampGenerator, NtpUdpSocket, Result, SendRequestResult};
    pub(crate) const SYNC_EXECUTOR_NUMBER_OF_TASKS: usize = 1;

    use miniloop::executor::Executor;
    /// Send request to a NTP server with the given address and process the response in a single call
    ///
    /// May be useful under an environment with `std` networking implementation, where all
    /// network stuff is hidden within system's kernel. For environment with custom
    /// Uses [`NtpUdpSocket`] and [`NtpTimestampGenerator`] trait bounds to allow generic specification
    /// of objects that can be used with the library
    ///
    /// # Arguments
    ///
    /// - `pool_addrs` - Server's name or IP address with port specification as a string
    /// - `socket` - UDP socket object that will be used during NTP request-response
    ///   communication
    /// - `context` - SNTP client context to provide timestamp generation feature
    ///
    /// # Errors
    ///
    /// Will return `Err` if an SNTP request cannot be sent or SNTP response fails
    pub fn get_time<U, T>(addr: net::SocketAddr, socket: &U, context: NtpContext<T>) -> Result<NtpResult>
    where
        U: NtpUdpSocket,
        T: NtpTimestampGenerator + Copy,
    {
        let result = sntp_send_request(addr, socket, context)?;
        #[cfg(any(feature = "log", feature = "defmt"))]
        debug!("{:?}", result);

        sntp_process_response(addr, socket, context, result)
    }

    /// Send an SNTP request to the specified destination synchronously.
    ///
    /// This function is a synchronous wrapper for the asynchronous [`crate::sntp_send_request`].
    /// It uses an executor to block the current thread while waiting for the underlying
    /// asynchronous operation to complete.
    ///
    /// # Arguments
    ///
    /// * `dest` - The destination NTP server's socket address to send the request to.
    /// * `socket` - A reference to an object implementing the [`NtpUdpSocket`] trait to send/receive data.
    /// * `context` - The SNTP client context (implementing [`NtpTimestampGenerator`]) that
    ///   assists in generating timestamps for the request.
    ///
    /// # Errors
    ///
    /// Returns an `Err` if the underlying async SNTP request fails for any reason,
    /// such as network failure, invalid server response, or timeout.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use sntpc::sync::sntp_send_request;
    /// use sntpc::{NtpContext, StdTimestampGen};
    /// use std::net::SocketAddr;
    ///
    /// # #[cfg(feature = "std")]
    /// # fn example() -> sntpc::Result<()> {
    /// use sntpc_net_std::UdpSocketWrapper;
    /// use std::net::UdpSocket;
    ///
    /// let socket = UdpSocket::bind("0.0.0.0:0").expect("Unable to bind socket");
    /// let socket = UdpSocketWrapper::new(socket);
    /// let context = NtpContext::new(StdTimestampGen::default());
    /// let addr: SocketAddr = "time.google.com:123".parse().unwrap();
    ///
    /// let request_result = sntp_send_request(addr, &socket, context)?;
    /// println!("Request sent with timestamp: {:?}", request_result);
    /// # Ok(())
    /// # }
    /// ```
    pub fn sntp_send_request<U, T>(
        dest: net::SocketAddr,
        socket: &U,
        context: NtpContext<T>,
    ) -> Result<SendRequestResult>
    where
        U: NtpUdpSocket,
        T: NtpTimestampGenerator + Copy,
    {
        Executor::<1>::new().block_on(crate::sntp_send_request(dest, socket, context))
    }

    /// Processes the response from an SNTP server and calculates the NTP offset and round-trip delay.
    ///
    /// This is a synchronous wrapper around the asynchronous SNTP response processing function.
    /// It uses an executor to block the current thread while waiting for the underlying
    /// asynchronous operation to complete.
    ///
    /// # Arguments
    ///
    /// - `dest` - The destination NTP server's socket address from which the response was received.
    /// - `socket` - A reference to an object implementing the [`NtpUdpSocket`] trait used for network communication.
    /// - `context` - The SNTP client context (implementing [`NtpTimestampGenerator`]) responsible for generating and validating timestamps.
    /// - `send_req_result` - The result obtained from sending the SNTP request, including the originate timestamp.
    ///
    /// # Errors
    ///
    /// Returns an `Err` if the underlying async SNTP response processing fails for any reason,
    /// such as:
    /// - Incorrect origin timestamp in the response,
    /// - An invalid mode in the response (`SNTP_UNICAST`),
    /// - A mismatch between the request and response versions,
    /// - Errors in the response headers (e.g., incorrect stratum, leap indicator),
    /// - Network errors during processing.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use sntpc::sync::{sntp_send_request, sntp_process_response};
    /// use sntpc::{NtpContext, StdTimestampGen};
    /// use std::net::SocketAddr;
    ///
    /// # #[cfg(feature = "std")]
    /// # fn example() -> sntpc::Result<()> {
    /// use sntpc_net_std::UdpSocketWrapper;
    /// use std::net::UdpSocket;
    ///
    /// let socket = UdpSocket::bind("0.0.0.0:0").expect("Unable to bind socket");
    /// let socket = UdpSocketWrapper::new(socket);
    /// let context = NtpContext::new(StdTimestampGen::default());
    /// let addr: SocketAddr = "time.google.com:123".parse().unwrap();
    ///
    /// let request_result = sntp_send_request(addr, &socket, context)?;
    /// let ntp_result = sntp_process_response(addr, &socket, context, request_result)?;
    ///
    /// println!("NTP Result: {:?}", ntp_result);
    /// # Ok(())
    /// # }
    /// ```
    pub fn sntp_process_response<U, T>(
        dest: net::SocketAddr,
        socket: &U,
        context: NtpContext<T>,
        send_req_result: SendRequestResult,
    ) -> Result<NtpResult>
    where
        U: NtpUdpSocket,
        T: NtpTimestampGenerator + Copy,
    {
        Executor::<SYNC_EXECUTOR_NUMBER_OF_TASKS>::new().block_on(crate::sntp_process_response(
            dest,
            socket,
            context,
            send_req_result,
        ))
    }
}

/// Convert log2(seconds) precision to microseconds.
/// For example, precision = -20 gives 2^-20 seconds ≈ 0.954 µs, rounded to 1 µs.
fn precision_to_micros(precision: i8) -> u64 {
    if precision >= 0 {
        let shift = precision.cast_unsigned();
        // 2^precision seconds * 1_000_000 µs/second
        1_000_000u64 << shift
    } else {
        let shift = precision.abs().cast_unsigned();

        if shift >= 64 {
            0 // Extremely fine precision, rounds to 0 microseconds
        } else {
            // 2^precision seconds = 1_000_000 / 2^shift microseconds
            // Compute with rounding to nearest integer
            let divisor = 1u64 << shift;
            let numer = 1_000_000u64;
            (numer + (divisor / 2)) / divisor
        }
    }
}

fn process_response(
    send_req_result: SendRequestResult,
    resp: RawNtpPacket,
    recv_timestamp: u64,
    recv_unix_seconds: u64,
    client_precision: i8,
) -> Result<NtpResult> {
    let packet = NtpPacket::from_be_bytes(&resp.0);

    cfg_if!(
        if #[cfg(any(feature = "log", feature = "defmt"))] {
            let debug_packet = DebugNtpPacket::new(&packet, recv_timestamp);
            debug!("{:#?}", debug_packet);
        }
    );

    validate_response(&packet, &send_req_result)?;
    // System clock offset:
    // theta = T(B) - T(A) = 1/2 * [(T2-T1) + (T3-T4)]
    // Round-trip delay:
    // delta = T(ABA) = (T4-T1) - (T3-T2).
    // where:
    // - T1 = client's TX timestamp
    // - T2 = server's RX timestamp
    // - T3 = server's TX timestamp
    // - T4 = client's RX timestamp
    let t1 = packet.origin_timestamp;
    let t2 = packet.recv_timestamp;
    let t3 = packet.tx_timestamp;
    let t4 = recv_timestamp;
    let units = Units::Microseconds;
    let roundtrip = roundtrip_calculate(t1, t2, t3, t4, units, precision_to_micros(client_precision));
    let offset = offset_calculate(t1, t2, t3, t4, units);
    let timestamp = reconstruct_timestamp(packet.tx_timestamp, recv_unix_seconds).ok_or(Error::InvalidTimestamp)?;
    let li = shifter(packet.li_vn_mode, LI_MASK, LI_SHIFT);

    #[cfg(any(feature = "log", feature = "defmt"))]
    debug!("Roundtrip delay: {} {}. Offset: {} {}", roundtrip, units, offset, units);

    #[cfg(feature = "dispersion")]
    let dispersion = dispersion_calculate(t1, t4, packet.precision, client_precision);
    #[cfg(not(feature = "dispersion"))]
    let _ = client_precision;
    #[cfg(not(feature = "dispersion"))]
    let dispersion: u64 = 0;

    Ok(NtpResult {
        seconds: timestamp.unix_seconds,
        seconds_fraction: timestamp.fraction,
        roundtrip,
        offset,
        stratum: packet.stratum,
        precision: packet.precision,
        leap_indicator: li,
        root_delay: packet.root_delay,
        root_dispersion: packet.root_dispersion,
        reference_id: packet.ref_id.to_be_bytes(), // Convert to network byte order for external use
        reference_timestamp: packet.ref_timestamp,
        poll: packet.poll,
        dispersion,
    })
}

/// Validate an NTP response packet according to RFC 5905 §A.5.1.1
fn validate_response(packet: &NtpPacket, send_req_result: &SendRequestResult) -> Result<()> {
    // Origin timestamp check
    if send_req_result.originate_timestamp != packet.origin_timestamp {
        return Err(Error::IncorrectOriginTimestamp);
    }

    let mode = shifter(packet.li_vn_mode, MODE_MASK, MODE_SHIFT);
    let li = shifter(packet.li_vn_mode, LI_MASK, LI_SHIFT);
    let resp_version = shifter(packet.li_vn_mode, VERSION_MASK, VERSION_SHIFT);
    let req_version = shifter(send_req_result.version, VERSION_MASK, VERSION_SHIFT);

    // Mode check: only unicast (mode 4) is supported.
    // Broadcast mode (mode 5) is not supported. See RFC 5905 §14 for broadcast client requirements.
    if mode != SNTP_UNICAST {
        return Err(Error::IncorrectMode);
    }

    // Kiss-of-death check (stratum 0 indicates KoD packet)
    // Must be checked BEFORE LI check, because KoD packets may have LI=3 and should
    // be identified as KoD rather than UnsynchronizedClock.
    if packet.stratum == 0 {
        return Err(Error::KissOfDeath(KissOfDeathCode::from_bytes(
            packet.ref_id.to_be_bytes(),
        )));
    }

    // Leap indicator check: LI=3 means clock unsynchronized per RFC 5905 §7.3 Figure 9
    if li == LI_UNSYNCHRONIZED {
        return Err(Error::UnsynchronizedClock);
    }

    // Version interop: accept lower versions down to VN=1, but not VN=0 or higher
    if resp_version == 0 || resp_version > req_version {
        return Err(Error::IncorrectResponseVersion);
    }

    // Stratum check
    if packet.stratum >= 16 {
        return Err(Error::IncorrectStratumHeaders);
    }

    // Zero transmit timestamp check (RFC 5905 §A.5.1.1, RFC 4330 §5)
    if packet.tx_timestamp == 0 {
        return Err(Error::InvalidTimestamp);
    }

    // Root distance validation (RFC 5905 §A.5.1.1)
    // `root_delay/2 + root_dispersion` must be < `MAXDISP`
    if (packet.root_delay / 2).saturating_add(packet.root_dispersion) >= MAXDISP {
        return Err(Error::ExcessiveRootDistance);
    }
    // Reference timestamp must not be newer than transmit timestamp.
    // A zero reference timestamp means unknown and preserves the previous
    // validation semantics; nonzero timestamps are compared with wrapping
    // arithmetic so adjacent-era packets around rollover are handled correctly.
    if packet.ref_timestamp != 0 && packet.ref_timestamp.wrapping_sub(packet.tx_timestamp).cast_signed() > 0 {
        return Err(Error::BackwardReferenceTimestamp);
    }

    Ok(())
}

fn shifter(val: u8, mask: u8, shift: u8) -> u8 {
    (val & mask) >> shift
}

#[cfg(feature = "dispersion")]
fn dispersion_calculate(t1: u64, t4: u64, server_precision: i8, client_precision: i8) -> u64 {
    let server_precision_usecs = precision_to_micros(server_precision);
    let client_precision_usecs = precision_to_micros(client_precision);
    // PHI = 15 ppm = 15 microseconds per second. RFC 5905 Appendix A bases the
    // PHI term on the elapsed client time (T4 - T1), not the adjusted delay.
    let elapsed = t4.wrapping_sub(t1).cast_signed();
    let elapsed = if elapsed <= 0 { 0 } else { elapsed.cast_unsigned() };
    let elapsed_sec = elapsed >> 32;
    let elapsed_sec_fraction = elapsed & u64::from(u32::MAX);
    let elapsed_usecs = convert_delays(elapsed_sec, elapsed_sec_fraction, u64::from(USEC_IN_SEC));
    let phi_term = elapsed_usecs * 15 / 1_000_000;

    server_precision_usecs
        .saturating_add(client_precision_usecs)
        .saturating_add(phi_term)
}

fn convert_delays(sec: u64, fraction: u64, units: u64) -> u64 {
    sec * units + fraction * units / (1u64 << 32)
}

fn ntp_wire_timestamp_from_unix(unix_seconds: u64, micros: u32) -> u64 {
    let ntp_seconds = unix_seconds.wrapping_add(u64::from(NtpPacket::NTP_TIMESTAMP_DELTA));
    let fraction = u64::from(micros) * NTP_ERA_SECONDS / u64::from(USEC_IN_SEC);
    ((ntp_seconds & u64::from(u32::MAX)) << 32) | fraction
}

#[derive(Copy, Clone)]
struct ReconstructedTimestamp {
    unix_seconds: u64,
    fraction: u32,
}

/// Reconstructs the full NTP era + seconds value for a 32-bit wire timestamp
/// (`raw`) using `local_unix_context_seconds` as a pivot.
///
/// Only the three candidate eras `{base_era - 1, base_era, base_era + 1}`
/// (where `base_era` is the pivot's era) are considered; the candidate whose
/// absolute distance from the pivot is smallest wins. On an exact tie between
/// two candidates, the earlier-listed (older) era wins, because candidates are
/// scanned oldest-to-newest and only a *strictly* smaller distance replaces
/// the current best.
fn reconstruct_timestamp(raw: u64, local_unix_context_seconds: u64) -> Option<ReconstructedTimestamp> {
    if raw == 0 {
        return None;
    }

    let raw_secs = raw >> 32;
    let raw_fraction = u32::try_from(raw & u64::from(u32::MAX)).unwrap();
    let local_ntp = local_unix_context_seconds.checked_add(u64::from(NtpPacket::NTP_TIMESTAMP_DELTA))?;
    let base_era = local_ntp >> 32;
    let mut best_candidate = None;
    for era in [base_era.wrapping_sub(1), base_era, base_era.wrapping_add(1)] {
        let candidate_ntp = (era << 32) | raw_secs;
        if candidate_ntp < u64::from(NtpPacket::NTP_TIMESTAMP_DELTA) {
            continue;
        }

        let distance = candidate_ntp.abs_diff(local_ntp);
        if match best_candidate {
            None => true,
            Some((_, best)) => distance < best,
        } {
            best_candidate = Some((candidate_ntp, distance));
        }
    }
    let (candidate_ntp, _) = best_candidate?;

    Some(ReconstructedTimestamp {
        unix_seconds: candidate_ntp - u64::from(NtpPacket::NTP_TIMESTAMP_DELTA),
        fraction: raw_fraction,
    })
}

fn roundtrip_calculate(t1: u64, t2: u64, t3: u64, t4: u64, units: Units, min_us: u64) -> u64 {
    // delta = (T4 - T1) - (T3 - T2)
    // Differences are computed with two's-complement wrapping arithmetic so
    // adjacent-era timestamps around rollover produce the correct duration.
    // If (T4 - T1) <= (T3 - T2), delay is non-positive and clamps to precision.
    let outbound = t4.wrapping_sub(t1).cast_signed();
    let server_time = t3.wrapping_sub(t2).cast_signed();
    let delta = outbound.saturating_sub(server_time);

    if delta <= 0 {
        return min_us;
    }

    let delta = delta.cast_unsigned();
    let delta_sec = (delta & SECONDS_MASK) >> 32;
    let delta_sec_fraction = delta & SECONDS_FRAC_MASK;

    let value = match units {
        Units::Milliseconds => convert_delays(delta_sec, delta_sec_fraction, u64::from(MSEC_IN_SEC)),
        Units::Microseconds => convert_delays(delta_sec, delta_sec_fraction, u64::from(USEC_IN_SEC)),
    };

    value.max(min_us)
}

fn offset_calculate(t1: u64, t2: u64, t3: u64, t4: u64, units: Units) -> i64 {
    let theta = (t2.wrapping_sub(t1).cast_signed() / 2).saturating_add(t3.wrapping_sub(t4).cast_signed() / 2);
    let theta_sec = (theta.unsigned_abs() & SECONDS_MASK) >> 32;
    let theta_sec_fraction = theta.unsigned_abs() & SECONDS_FRAC_MASK;

    match units {
        Units::Milliseconds => {
            convert_delays(theta_sec, theta_sec_fraction, u64::from(MSEC_IN_SEC)).cast_signed() * theta.signum()
        }
        Units::Microseconds => {
            convert_delays(theta_sec, theta_sec_fraction, u64::from(USEC_IN_SEC)).cast_signed() * theta.signum()
        }
    }
}

fn get_ntp_timestamp<T: NtpTimestampGenerator>(timestamp_gen: &T) -> u64 {
    ntp_wire_timestamp_from_unix(timestamp_gen.timestamp_sec(), timestamp_gen.timestamp_subsec_micros())
}

/// Convert second fraction value to milliseconds value
#[allow(clippy::cast_possible_truncation)]
#[must_use]
pub fn fraction_to_milliseconds(sec_fraction: u32) -> u32 {
    (u64::from(sec_fraction) * u64::from(MSEC_IN_SEC) / (1u64 << 32)) as u32
}

/// Convert second fraction value to microseconds value
#[must_use]
pub fn fraction_to_microseconds(sec_fraction: u32) -> u32 {
    (u64::from(sec_fraction) * u64::from(USEC_IN_SEC) / (1u64 << 32)) as u32
}

/// Convert second fraction value to nanoseconds value
#[must_use]
pub fn fraction_to_nanoseconds(sec_fraction: u32) -> u32 {
    (u64::from(sec_fraction) * u64::from(NSEC_IN_SEC) / (1u64 << 32)) as u32
}

/// Convert second fraction value to picoseconds value
#[must_use]
pub fn fraction_to_picoseconds(sec_fraction: u32) -> u64 {
    u64::try_from(u128::from(sec_fraction) * u128::from(PSEC_IN_SEC) / (1u128 << 32)).unwrap_or(0)
}

#[cfg(test)]
mod sntpc_ntp_result_tests {
    use crate::{
        Error, NTP_ERA_SECONDS, NtpPacket, SendRequestResult, ntp_wire_timestamp_from_unix, offset_calculate,
        reconstruct_timestamp, roundtrip_calculate, types::Units, validate_response,
    };

    struct Timestamps(u64, u64, u64, u64);
    struct OffsetCalcTestCase {
        timestamp: Timestamps,
        expected: i64,
    }

    impl OffsetCalcTestCase {
        fn new(t1: u64, t2: u64, t3: u64, t4: u64, expected: i64) -> Self {
            OffsetCalcTestCase {
                timestamp: Timestamps(t1, t2, t3, t4),
                expected,
            }
        }

        fn t1(&self) -> u64 {
            self.timestamp.0
        }

        fn t2(&self) -> u64 {
            self.timestamp.1
        }

        fn t3(&self) -> u64 {
            self.timestamp.2
        }

        fn t4(&self) -> u64 {
            self.timestamp.3
        }
    }

    #[test]
    fn test_offset_calculate_us() {
        let tests = [
            OffsetCalcTestCase::new(
                16_893_142_954_672_769_962,
                16_893_142_959_053_084_959,
                16_893_142_959_053_112_968,
                16_893_142_954_793_063_406,
                1_005_870,
            ),
            OffsetCalcTestCase::new(
                16_893_362_966_131_575_843,
                16_893_362_966_715_800_791,
                16_893_362_966_715_869_584,
                16_893_362_967_084_349_913,
                25115,
            ),
            OffsetCalcTestCase::new(
                16_893_399_716_399_327_198,
                16_893_399_716_453_045_029,
                16_893_399_716_453_098_083,
                16_893_399_716_961_924_964,
                -52981,
            ),
            OffsetCalcTestCase::new(
                9_487_534_663_484_046_772u64,
                16_882_120_099_581_835_046u64,
                16_882_120_099_583_884_144u64,
                9_487_534_663_651_464_597u64,
                1_721_686_086_620_926,
            ),
        ];

        for t in tests {
            let offset = offset_calculate(t.t1(), t.t2(), t.t3(), t.t4(), Units::Microseconds);
            let expected = t.expected;
            assert_eq!(offset, expected);
        }
    }

    #[test]
    fn test_offset_calculate_across_era_boundary() {
        // t1/t2 are just before the era rollover, t3/t4 just after; wrapping_sub
        // must still recover the correct signed offset across the boundary.
        let t1 = 0xffff_ffff_0000_0000u64;
        let t2 = 0xffff_ffff_6000_0000u64;
        let t3 = 0x0000_0000_4000_0000u64;
        let t4 = 0x0000_0000_8000_0000u64;
        assert_eq!(offset_calculate(t1, t2, t3, t4, Units::Microseconds), 62_500);
    }

    #[test]
    fn test_offset_calculate_ms() {
        let tests = [
            OffsetCalcTestCase::new(
                16_893_142_954_672_769_962,
                16_893_142_959_053_084_959,
                16_893_142_959_053_112_968,
                16_893_142_954_793_063_406,
                1_005_870 / 1_000,
            ),
            OffsetCalcTestCase::new(
                16_893_362_966_131_575_843,
                16_893_362_966_715_800_791,
                16_893_362_966_715_869_584,
                16_893_362_967_084_349_913,
                25115 / 1_000,
            ),
            OffsetCalcTestCase::new(
                16_893_399_716_399_327_198,
                16_893_399_716_453_045_029,
                16_893_399_716_453_098_083,
                16_893_399_716_961_924_964,
                -52981 / 1_000,
            ),
            OffsetCalcTestCase::new(
                9_487_534_663_484_046_772u64,
                16_882_120_099_581_835_046u64,
                16_882_120_099_583_884_144u64,
                9_487_534_663_651_464_597u64,
                1_721_686_086_620_926 / 1_000,
            ),
        ];

        for t in tests {
            let offset = offset_calculate(t.t1(), t.t2(), t.t3(), t.t4(), Units::Milliseconds);
            let expected = t.expected;
            assert_eq!(offset, expected);
        }
    }

    #[test]
    fn test_units_str_representation() {
        assert_eq!(format!("{}", Units::Milliseconds), "ms");
        assert_eq!(format!("{}", Units::Microseconds), "us");
    }

    #[test]
    fn test_roundtrip_calculate_normal() {
        // Normal case: T4 > T1, T3 > T2, positive delay
        let t1 = 1_000_000_000u64;
        let t2 = 1_000_010_000u64;
        let t3 = 1_000_020_000u64;
        let t4 = 1_000_030_000u64;
        let result = roundtrip_calculate(t1, t2, t3, t4, Units::Microseconds, 0);
        assert!(result > 0);
    }

    #[test]
    fn test_roundtrip_calculate_clock_backward() {
        // T4 < T1 (clock went backward) — should clamp to precision minimum
        let t1 = 2_000_000_000u64;
        let t2 = 1_000_010_000u64;
        let t3 = 1_000_020_000u64;
        let t4 = 1_000_030_000u64;
        let result = roundtrip_calculate(t1, t2, t3, t4, Units::Microseconds, 1);
        assert_eq!(result, 1);
    }

    #[test]
    fn test_roundtrip_calculate_negative_delay() {
        // (T4-T1) < (T3-T2) — negative delay, should clamp to precision minimum
        let t1 = 1_000_000_000u64;
        let t2 = 1_000_100_000u64;
        let t3 = 1_000_200_000u64;
        let t4 = 1_000_050_000u64;
        let result = roundtrip_calculate(t1, t2, t3, t4, Units::Microseconds, 1);
        assert_eq!(result, 1);
    }

    #[test]
    fn test_roundtrip_calculate_all_zeros() {
        let result = roundtrip_calculate(0, 0, 0, 0, Units::Microseconds, 1);
        assert_eq!(result, 1);
    }

    #[test]
    fn test_ntp_wire_timestamp_from_unix_rollover() {
        assert_eq!(ntp_wire_timestamp_from_unix(2_085_978_495, 0), 0xffff_ffff_0000_0000);
        assert_eq!(ntp_wire_timestamp_from_unix(2_085_978_496, 0), 0);
        assert_eq!(ntp_wire_timestamp_from_unix(2_085_978_497, 0), 0x0000_0001_0000_0000);
    }

    #[test]
    fn test_reconstruct_timestamp_rollover_and_zero() {
        assert!(reconstruct_timestamp(0, 2_085_978_496).is_none());
        assert_eq!(
            reconstruct_timestamp(0x0000_0001_0000_0000, 0).unwrap().unix_seconds,
            2_085_978_497
        );

        let just_after = ntp_wire_timestamp_from_unix(2_085_978_497, 123_456);
        let reconstructed = reconstruct_timestamp(just_after, 2_085_978_497).unwrap();
        assert_eq!(reconstructed.unix_seconds, 2_085_978_497);
        assert_eq!(
            reconstructed.fraction,
            u32::try_from(123_456u64 * NTP_ERA_SECONDS / 1_000_000).unwrap()
        );

        let just_before = ntp_wire_timestamp_from_unix(2_085_978_495, 0);
        let reconstructed = reconstruct_timestamp(just_before, 2_085_978_496).unwrap();
        assert_eq!(reconstructed.unix_seconds, 2_085_978_495);
    }

    #[test]
    fn test_reconstruct_timestamp_skips_pre_unix_candidate() {
        let raw = 100_000_000u64 << 32;

        assert_eq!(reconstruct_timestamp(raw, 0).unwrap().unix_seconds, 2_185_978_496);
    }

    #[test]
    fn test_reconstruct_timestamp_supports_era_2_plus() {
        let unix_seconds = 6_380_955_792u64 + 123;
        let raw = ntp_wire_timestamp_from_unix(unix_seconds, 42);

        let reconstructed = reconstruct_timestamp(raw, unix_seconds).unwrap();
        assert_eq!(reconstructed.unix_seconds, unix_seconds);
        assert_eq!(
            reconstructed.fraction,
            u32::try_from(42u64 * NTP_ERA_SECONDS / 1_000_000).unwrap()
        );
    }

    #[test]
    fn test_reconstruct_timestamp_tie_prefers_earlier_era() {
        let local_ntp = (1u64 << 32) + 1 + (1u64 << 31);
        let local_unix_seconds = local_ntp - u64::from(NtpPacket::NTP_TIMESTAMP_DELTA);

        let reconstructed = reconstruct_timestamp(1u64 << 32, local_unix_seconds).unwrap();
        assert_eq!(reconstructed.unix_seconds, 2_085_978_497);
    }

    #[test]
    fn test_reconstruct_timestamp_half_era_boundary_switches_after_tie() {
        let raw = 1u64 << 32;
        let era_1_ntp = (1u64 << 32) + 1;
        let era_1_unix = era_1_ntp - u64::from(NtpPacket::NTP_TIMESTAMP_DELTA);
        let era_2_unix = era_1_unix + NTP_ERA_SECONDS;

        let before_tie = era_1_ntp + (1u64 << 31) - 1;
        assert_eq!(
            reconstruct_timestamp(raw, before_tie - u64::from(NtpPacket::NTP_TIMESTAMP_DELTA))
                .unwrap()
                .unix_seconds,
            era_1_unix
        );

        let after_tie = era_1_ntp + (1u64 << 31) + 1;
        assert_eq!(
            reconstruct_timestamp(raw, after_tie - u64::from(NtpPacket::NTP_TIMESTAMP_DELTA))
                .unwrap()
                .unix_seconds,
            era_2_unix
        );
    }

    #[test]
    fn test_reconstruct_timestamp_uses_bad_pivot_wrong_era() {
        let actual_unix_seconds = 6_380_955_792u64 + 123;
        let stale_pivot = actual_unix_seconds - NTP_ERA_SECONDS;
        let raw = ntp_wire_timestamp_from_unix(actual_unix_seconds, 0);

        let reconstructed = reconstruct_timestamp(raw, stale_pivot).unwrap();
        assert_eq!(reconstructed.unix_seconds, stale_pivot);
        assert_ne!(reconstructed.unix_seconds, actual_unix_seconds);
    }

    #[test]
    fn test_reconstruct_timestamp_uses_bad_pivot_two_eras_stale() {
        // A pivot stale by 2+ eras is still outside the {base_era-1, base_era,
        // base_era+1} search window, so reconstruction silently lands on the
        // stale era rather than failing — it never returns `None` just because
        // the pivot is old.
        let actual_unix_seconds = 3 * NTP_ERA_SECONDS + 1_000;
        let stale_pivot = actual_unix_seconds - 2 * NTP_ERA_SECONDS;
        let raw = ntp_wire_timestamp_from_unix(actual_unix_seconds, 0);

        let reconstructed = reconstruct_timestamp(raw, stale_pivot).unwrap();
        assert_eq!(reconstructed.unix_seconds, stale_pivot);
        assert_ne!(reconstructed.unix_seconds, actual_unix_seconds);
    }

    #[test]
    fn test_reconstruct_timestamp_zero_secs_nonzero_fraction() {
        // raw_secs == 0 (an exact NTP era-boundary instant) but the fraction is
        // nonzero; the raw==0 short-circuit must not fire here.
        let raw = 10_000u64;
        let reconstructed = reconstruct_timestamp(raw, 0).unwrap();
        assert_eq!(reconstructed.unix_seconds, 2_085_978_496);
        assert_eq!(reconstructed.fraction, 10_000);
    }

    #[test]
    fn test_reconstruct_timestamp_roundtrip_across_eras() {
        for era in 0..=2u64 {
            let unix_seconds = era * NTP_ERA_SECONDS + 1_000;
            let raw = ntp_wire_timestamp_from_unix(unix_seconds, 500_000);
            let reconstructed = reconstruct_timestamp(raw, unix_seconds).unwrap();
            assert_eq!(reconstructed.unix_seconds, unix_seconds, "era {era}");
            assert_eq!(
                reconstructed.fraction,
                u32::try_from(500_000u64 * NTP_ERA_SECONDS / 1_000_000).unwrap(),
                "era {era}"
            );
        }
    }

    #[test]
    fn test_roundtrip_calculate_rollover_wraps() {
        let t1 = 0xffff_ffff_0000_0000;
        let t2 = 0xffff_ffff_8000_0000;
        let t3 = 0x0000_0000_8000_0000;
        let t4 = 0x0000_0001_0000_0000;
        assert_eq!(roundtrip_calculate(t1, t2, t3, t4, Units::Microseconds, 1), 1_000_000);
    }

    #[test]
    fn test_validate_response_rejects_zero_tx_timestamp() {
        let packet = NtpPacket {
            li_vn_mode: 0x24,
            stratum: 1,
            poll: 0,
            precision: 0,
            root_delay: 0,
            root_dispersion: 0,
            ref_id: 0,
            ref_timestamp: 0,
            origin_timestamp: 1,
            recv_timestamp: 0,
            tx_timestamp: 0,
        };
        let send = SendRequestResult {
            originate_timestamp: 1,
            version: packet.li_vn_mode,
        };
        assert!(matches!(
            validate_response(&packet, &send),
            Err(Error::InvalidTimestamp)
        ));
    }

    #[cfg(feature = "dispersion")]
    #[test]
    fn test_precision_to_micros() {
        // 2^0 seconds = 1_000_000 microseconds
        assert_eq!(super::precision_to_micros(0), 1_000_000);
        // 2^1 seconds = 2_000_000 microseconds
        assert_eq!(super::precision_to_micros(1), 2_000_000);
        // 2^-10 seconds ≈ 977 microseconds
        assert!(super::precision_to_micros(-10) >= 976);
        assert!(super::precision_to_micros(-10) <= 978);
        // 2^-20 seconds ≈ 1 microsecond
        assert_eq!(super::precision_to_micros(-20), 1);
        // 2^-30 seconds ≈ 0 microseconds (rounds down)
        assert_eq!(super::precision_to_micros(-30), 0);
    }

    #[cfg(feature = "dispersion")]
    #[test]
    fn test_dispersion_computation() {
        use crate::NtpResult;

        // With server precision -20 (≈1µs) and client precision -20 (≈1µs)
        // and roundtrip of 1000µs:
        // dispersion = 1 + 1 + (1000 * 15 / 1_000_000) = 2 + 0 = 2µs
        let result = NtpResult::new(0, 0, 1000, 0, 1, -20, 0, 0, 0, [0; 4], 0, 0, 0);
        // NtpResult::new doesn't compute dispersion, it's computed in process_response
        // This test verifies the dispersion field is stored correctly
        assert_eq!(result.dispersion(), 0);

        // Create result with a non-zero dispersion
        let result = NtpResult::new(0, 0, 1000, 0, 1, -20, 0, 0, 0, [0; 4], 0, 0, 42);
        assert_eq!(result.dispersion(), 42);
    }

    #[cfg(feature = "dispersion")]
    #[test]
    fn test_dispersion_calculate_uses_elapsed_client_time() {
        let t1 = 1u64 << 32;
        let t4 = 3u64 << 32;

        // precision -20 is approximately 1µs for both server and client.
        // Elapsed client time is 2 seconds, so PHI contributes 30µs.
        assert_eq!(super::dispersion_calculate(t1, t4, -20, -20), 32);

        // If T4 is before T1 within the ambiguity window, elapsed clamps to 0.
        assert_eq!(super::dispersion_calculate(t4, t1, -20, -20), 2);

        // Adjacent-era rollover with one second elapsed still contributes PHI.
        assert_eq!(super::dispersion_calculate(0xffff_ffff_0000_0000, 0, -20, -20), 17);

        // Rollover crossing with nonzero fractional seconds: elapsed is 0.75s
        // (t1 is 0.5s before rollover, t4 is 0.25s after), contributing ~11µs PHI.
        assert_eq!(
            super::dispersion_calculate(0xffff_ffff_8000_0000, 0x0000_0000_4000_0000, -20, -20),
            13
        );
    }

    #[test]
    fn test_dispersion_field_default() {
        use crate::NtpResult;

        // Without the dispersion feature, dispersion is always 0
        let result = NtpResult::new(0, 0, 1000, 0, 1, -20, 0, 0, 0, [0; 4], 0, 0, 0);
        assert_eq!(result.dispersion(), 0);
    }
}