Skip to main content

qualia_core_db/sensing/authority/
clock_discipline.rs

1//! Clock-discipline verification, TAI/UTC leap-second table binding, sinusoidal phase
2//! uncertainty bounds ($\Delta\phi_{\max} = 2\pi f u_t$, C02-C03), and explicit I/Q carrier
3//! convention conversion (`z_QAC = conj(z_EMF)`, C02-C08).
4
5use core::cmp::Ordering;
6use core::f64::consts::TAU;
7
8use crate::sensing::acquisition::{Clock, ComplexConvention};
9use crate::sensing::authority::certificates::{CalibrationValidityWindow, RationalInstant};
10use crate::sensing::SemanticId;
11
12/// Domain separator for BLAKE3 leap-second table commitments.
13pub const LEAP_SECOND_TABLE_DOMAIN: &[u8] = b"QUALIA-LEAP-SECOND-TABLE-v1\0";
14
15/// Maximum entries in a zero-heap bounded TAI-UTC leap-second table.
16pub const MAX_LEAP_SECOND_ENTRIES: usize = 64;
17
18/// Clock scale defined by Shared Schema 1 (`Clock.scale`).
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20#[repr(u32)]
21pub enum ClockScale {
22    /// International Atomic Time (TAI), continuous SI seconds without leap seconds.
23    Tai = 0,
24    /// Coordinated Universal Time (UTC), requires an explicit `LeapSecondTable` for TAI conversion.
25    Utc = 1,
26    /// Relative / monotonic hardware or solver clock; requires an explicit `origin` (`SemanticId`).
27    MonotonicRelative = 2,
28}
29
30impl ClockScale {
31    pub const fn from_code(code: u32) -> Result<Self, ClockDisciplineError> {
32        match code {
33            0 => Ok(Self::Tai),
34            1 => Ok(Self::Utc),
35            2 => Ok(Self::MonotonicRelative),
36            _ => Err(ClockDisciplineError::InvalidClockScale),
37        }
38    }
39}
40
41/// One step in an authenticated IERS/BIPM TAI-minus-UTC leap-second schedule.
42#[derive(Clone, Copy, Debug, PartialEq, Eq)]
43pub struct LeapSecondStep {
44    /// Effective UTC Unix epoch second (inclusive) when `tai_minus_utc_seconds` takes effect.
45    pub effective_utc_second: i64,
46    /// Integer `TAI - UTC` offset in seconds (e.g. `37` after 2017-01-01T00:00:00Z).
47    pub tai_minus_utc_seconds: i32,
48}
49
50/// Authenticated, bounded TAI/UTC leap-second table with validity horizon and clock uncertainty.
51/// Per C02-C03, POSIX/UTC-to-TAI mapping requires an identified leap-second table and uncertainty;
52/// no floating global epoch or fixed universal UTC offset substitutes for it.
53#[derive(Clone, Copy, Debug, PartialEq)]
54pub struct LeapSecondTable {
55    table_id: SemanticId,
56    steps: [LeapSecondStep; MAX_LEAP_SECOND_ENTRIES],
57    step_count: usize,
58    valid_from_utc_sec: i64,
59    valid_until_utc_sec: i64,
60    table_uncertainty_seconds: f64,
61    table_digest: [u8; 32],
62}
63
64impl LeapSecondTable {
65    pub fn new(
66        table_id: SemanticId,
67        steps_slice: &[LeapSecondStep],
68        valid_from_utc_sec: i64,
69        valid_until_utc_sec: i64,
70        table_uncertainty_seconds: f64,
71    ) -> Result<Self, ClockDisciplineError> {
72        if table_id.value().is_none() {
73            return Err(ClockDisciplineError::InvalidIdentifier);
74        }
75        if steps_slice.is_empty() || steps_slice.len() > MAX_LEAP_SECOND_ENTRIES {
76            return Err(ClockDisciplineError::InvalidLeapSecondTable);
77        }
78        if valid_from_utc_sec >= valid_until_utc_sec
79            || !table_uncertainty_seconds.is_finite()
80            || table_uncertainty_seconds < 0.0
81        {
82            return Err(ClockDisciplineError::InvalidLeapSecondTable);
83        }
84        let mut steps = [LeapSecondStep {
85            effective_utc_second: 0,
86            tai_minus_utc_seconds: 0,
87        }; MAX_LEAP_SECOND_ENTRIES];
88        let mut prev_effective: Option<i64> = None;
89        for (idx, step) in steps_slice.iter().copied().enumerate() {
90            if let Some(prev) = prev_effective {
91                if step.effective_utc_second <= prev {
92                    return Err(ClockDisciplineError::InvalidLeapSecondTable);
93                }
94            }
95            prev_effective = Some(step.effective_utc_second);
96            steps[idx] = step;
97        }
98        if steps[0].effective_utc_second > valid_from_utc_sec {
99            return Err(ClockDisciplineError::InvalidLeapSecondTable);
100        }
101
102        let mut hasher = blake3::Hasher::new();
103        hasher.update(LEAP_SECOND_TABLE_DOMAIN);
104        hasher.update(&table_id.value().unwrap_or(0).to_le_bytes());
105        hasher.update(&valid_from_utc_sec.to_le_bytes());
106        hasher.update(&valid_until_utc_sec.to_le_bytes());
107        hasher.update(&table_uncertainty_seconds.to_bits().to_le_bytes());
108        hasher.update(&(steps_slice.len() as u32).to_le_bytes());
109        for step in steps_slice {
110            hasher.update(&step.effective_utc_second.to_le_bytes());
111            hasher.update(&step.tai_minus_utc_seconds.to_le_bytes());
112        }
113        let table_digest = *hasher.finalize().as_bytes();
114
115        Ok(Self {
116            table_id,
117            steps,
118            step_count: steps_slice.len(),
119            valid_from_utc_sec,
120            valid_until_utc_sec,
121            table_uncertainty_seconds,
122            table_digest,
123        })
124    }
125
126    pub const fn table_id(&self) -> SemanticId {
127        self.table_id
128    }
129
130    pub const fn table_digest(&self) -> &[u8; 32] {
131        &self.table_digest
132    }
133
134    pub const fn table_uncertainty_seconds(&self) -> f64 {
135        self.table_uncertainty_seconds
136    }
137
138    /// Look up `(TAI - UTC)` in integer seconds at `utc_second` within `[valid_from_utc_sec, valid_until_utc_sec)`.
139    pub fn tai_minus_utc_at(&self, utc_second: i64) -> Result<i32, ClockDisciplineError> {
140        if utc_second < self.valid_from_utc_sec || utc_second >= self.valid_until_utc_sec {
141            return Err(ClockDisciplineError::LeapTableExpiredOrOutOfRange);
142        }
143        let mut active = self.steps[0].tai_minus_utc_seconds;
144        for step in self.steps.iter().take(self.step_count) {
145            if utc_second >= step.effective_utc_second {
146                active = step.tai_minus_utc_seconds;
147            } else {
148                break;
149            }
150        }
151        Ok(active)
152    }
153
154    /// Convert a UTC `RationalInstant` (`scale == 1`) into a TAI `RationalInstant` (`scale == 0`),
155    /// returning the converted instant and combined time uncertainty $u_t$ in seconds.
156    pub fn convert_utc_instant_to_tai(
157        &self,
158        utc_instant: RationalInstant,
159        tai_origin: SemanticId,
160        source_time_uncertainty_seconds: Option<f64>,
161    ) -> Result<(RationalInstant, f64), ClockDisciplineError> {
162        if ClockScale::from_code(utc_instant.scale())? != ClockScale::Utc {
163            return Err(ClockDisciplineError::InvalidClockScale);
164        }
165        let u_src = validate_known_time_uncertainty(source_time_uncertainty_seconds)?;
166        let floor_utc_sec = rational_floor_seconds(utc_instant);
167        let floor_i64 = i64::try_from(floor_utc_sec)
168            .map_err(|_| ClockDisciplineError::LeapTableExpiredOrOutOfRange)?;
169        let delta_tai = self.tai_minus_utc_at(floor_i64)?;
170        let shifted = utc_instant
171            .add_rational_seconds(i128::from(delta_tai), 1)
172            .map_err(|_| ClockDisciplineError::RationalOverflow)?;
173        let tai_instant = RationalInstant::new(
174            tai_origin,
175            utc_instant.restart_epoch(),
176            ClockScale::Tai as u32,
177            shifted.numerator(),
178            shifted.denominator(),
179        )
180        .map_err(|_| ClockDisciplineError::InvalidIdentifier)?;
181        let total_u_t = u_src + self.table_uncertainty_seconds;
182        if !total_u_t.is_finite() {
183            return Err(ClockDisciplineError::UnknownOrInvalidTimeUncertainty);
184        }
185        Ok((tai_instant, total_u_t))
186    }
187}
188
189/// Explicit cross-clock mapping between two distinct clock origins (`source_origin -> target_origin`)
190/// over a half-open source validity interval `[valid_from, valid_until)`.
191#[derive(Clone, Copy, Debug, PartialEq)]
192pub struct CrossClockMapping {
193    pub mapping_id: SemanticId,
194    pub source_origin: SemanticId,
195    pub source_restart: u64,
196    pub source_scale: u32,
197    pub target_origin: SemanticId,
198    pub target_restart: u64,
199    pub target_scale: u32,
200    pub source_validity: CalibrationValidityWindow,
201    pub offset_seconds_num: i128,
202    pub offset_seconds_den: i128,
203    pub mapping_time_uncertainty_seconds: f64,
204}
205
206impl CrossClockMapping {
207    pub fn validate(&self) -> Result<(), ClockDisciplineError> {
208        if self.mapping_id.value().is_none()
209            || self.source_origin.value().is_none()
210            || self.target_origin.value().is_none()
211        {
212            return Err(ClockDisciplineError::InvalidIdentifier);
213        }
214        ClockScale::from_code(self.source_scale)?;
215        ClockScale::from_code(self.target_scale)?;
216        if self.offset_seconds_den <= 0 {
217            return Err(ClockDisciplineError::RationalOverflow);
218        }
219        if !self.mapping_time_uncertainty_seconds.is_finite()
220            || self.mapping_time_uncertainty_seconds < 0.0
221        {
222            return Err(ClockDisciplineError::UnknownOrInvalidTimeUncertainty);
223        }
224        if self.source_validity.valid_from().clock_origin() != self.source_origin
225            || self.source_validity.valid_from().restart_epoch() != self.source_restart
226            || self.source_validity.valid_from().scale() != self.source_scale
227        {
228            return Err(ClockDisciplineError::CrossClockOriginRejected);
229        }
230        Ok(())
231    }
232
233    /// Map `source_instant` into the target clock domain, returning the mapped `RationalInstant`
234    /// and the propagated time uncertainty $u_t = u_{t,\text{source}} + u_{t,\text{mapping}}$.
235    pub fn map_instant(
236        &self,
237        source_instant: RationalInstant,
238        source_time_uncertainty_seconds: Option<f64>,
239    ) -> Result<(RationalInstant, f64), ClockDisciplineError> {
240        self.validate()?;
241        let u_src = validate_known_time_uncertainty(source_time_uncertainty_seconds)?;
242        self.source_validity
243            .verify_contains(source_instant)
244            .map_err(|_| ClockDisciplineError::MappingOutsideValidityWindow)?;
245        let shifted = source_instant
246            .add_rational_seconds(self.offset_seconds_num, self.offset_seconds_den)
247            .map_err(|_| ClockDisciplineError::RationalOverflow)?;
248        let mapped = RationalInstant::new(
249            self.target_origin,
250            self.target_restart,
251            self.target_scale,
252            shifted.numerator(),
253            shifted.denominator(),
254        )
255        .map_err(|_| ClockDisciplineError::InvalidIdentifier)?;
256        let total_u = u_src + self.mapping_time_uncertainty_seconds;
257        if !total_u.is_finite() {
258            return Err(ClockDisciplineError::UnknownOrInvalidTimeUncertainty);
259        }
260        Ok((mapped, total_u))
261    }
262}
263
264/// Verify that two `acquisition::Clock` instances share the exact same origin, restart epoch,
265/// scale, epoch, and tick rate before admitting an unmapped same-clock join (C02-C03).
266///
267/// Relative clocks with different origins or restart epochs are strictly rejected even when
268/// `epoch_seconds`, `epoch_nanoseconds`, `ticks`, and `samples` are numerically identical.
269pub fn verify_same_clock_join(clock_a: Clock, clock_b: Clock) -> Result<(), ClockDisciplineError> {
270    if clock_a.origin() != clock_b.origin() || clock_a.restart() != clock_b.restart() {
271        return Err(ClockDisciplineError::CrossClockOriginRejected);
272    }
273    clock_a
274        .require_same_domain(clock_b)
275        .map_err(|_| ClockDisciplineError::ClockParametersMismatch)
276}
277
278/// Compute the sinusoidal phase uncertainty bound $\Delta\phi_{\max} = 2\pi f u_t$ in radians
279/// (C02-C03) for a carrier or analysis frequency $f > 0$ Hz and time uncertainty $u_t \ge 0$ s.
280///
281/// Fails closed if $u_t$ is `None` (unknown), negative, or non-finite, or if $f \le 0$ or non-finite.
282pub fn compute_phase_uncertainty_rad(
283    frequency_hz: f64,
284    time_uncertainty_seconds: Option<f64>,
285) -> Result<f64, ClockDisciplineError> {
286    if !frequency_hz.is_finite() || frequency_hz <= 0.0 {
287        return Err(ClockDisciplineError::InvalidCarrierFrequency);
288    }
289    let u_t = validate_known_time_uncertainty(time_uncertainty_seconds)?;
290    let delta_phi = TAU * frequency_hz * u_t;
291    if !delta_phi.is_finite() {
292        return Err(ClockDisciplineError::PhaseUncertaintyOverflow);
293    }
294    Ok(delta_phi)
295}
296
297/// Admit a phase-coherent join across RF I/Q (EMF Mode 0x0105) or ultrasound/acoustic array
298/// streams (QAC Mode 0x0107) only when the clock domain matches (or is explicitly mapped),
299/// time uncertainty $u_t$ is known, and $\Delta\phi_{\max} = 2\pi f u_t \le \Delta\phi_{\text{budget}}$.
300pub fn verify_phase_coherent_join(
301    instant_a: RationalInstant,
302    instant_b: RationalInstant,
303    frequency_hz: f64,
304    time_uncertainty_seconds: Option<f64>,
305    max_allowed_phase_uncertainty_rad: f64,
306) -> Result<f64, ClockDisciplineError> {
307    if !instant_a.same_clock_domain(instant_b) {
308        return Err(ClockDisciplineError::CrossClockOriginRejected);
309    }
310    if instant_a
311        .checked_cmp(instant_b)
312        .map_err(|_| ClockDisciplineError::CrossClockOriginRejected)?
313        != Ordering::Equal
314    {
315        return Err(ClockDisciplineError::InstantNotSimultaneous);
316    }
317    if !max_allowed_phase_uncertainty_rad.is_finite() || max_allowed_phase_uncertainty_rad < 0.0 {
318        return Err(ClockDisciplineError::InvalidPhaseCoherenceBudget);
319    }
320    let delta_phi = compute_phase_uncertainty_rad(frequency_hz, time_uncertainty_seconds)?;
321    if delta_phi > max_allowed_phase_uncertainty_rad {
322        return Err(ClockDisciplineError::PhaseUncertaintyExceedsBudget);
323    }
324    Ok(delta_phi)
325}
326
327/// Explicit I/Q complex carrier reconstruction conventions (C02-C08, CROSS-A04).
328#[derive(Clone, Copy, Debug, PartialEq, Eq)]
329pub enum IqCarrierConvention {
330    /// EMF Schema 136 / Mode 0x0105 (`"I_plus_iQ_exp_minus_iwt"`):
331    /// $x_{\text{RF}}(t) = \operatorname{Re}\{(I + iQ) e^{-i(2\pi f_c(t - t_{\text{LO}}) + \phi_{\text{LO}})}\}$
332    /// $= I \cos(\theta) + Q \sin(\theta)$.
333    EmfNegativeCarrier,
334    /// QAC Schema 208 / Mode 0x0107 (`"I_plus_iQ_exp_plus_iwt"`):
335    /// $p(t) = \operatorname{Re}\{(I + iQ) e^{+i(2\pi f_c(t - t_0) + \phi_0)}\}$
336    /// $= I \cos(\theta) - Q \sin(\theta)$.
337    QacPositiveCarrier,
338}
339
340impl IqCarrierConvention {
341    pub fn from_wire_str(s: &str) -> Result<Self, ClockDisciplineError> {
342        match s {
343            "I_plus_iQ_exp_minus_iwt" => Ok(Self::EmfNegativeCarrier),
344            "I_plus_iQ_exp_plus_iwt" => Ok(Self::QacPositiveCarrier),
345            _ => Err(ClockDisciplineError::UnknownIqCarrierConvention),
346        }
347    }
348
349    pub const fn as_wire_str(self) -> &'static str {
350        match self {
351            Self::EmfNegativeCarrier => "I_plus_iQ_exp_minus_iwt",
352            Self::QacPositiveCarrier => "I_plus_iQ_exp_plus_iwt",
353        }
354    }
355
356    pub const fn from_acquisition_convention(conv: ComplexConvention) -> Self {
357        match conv {
358            ComplexConvention::RealPlusIImagNegativeExponent => Self::EmfNegativeCarrier,
359            ComplexConvention::RealPlusIImagPositiveExponent => Self::QacPositiveCarrier,
360        }
361    }
362}
363
364/// Complex baseband sample with explicit carrier convention, carrier frequency, reference phase,
365/// and signed baseband frequency offset.
366#[derive(Clone, Copy, Debug, PartialEq)]
367pub struct QualifiedIqSample {
368    pub i: f64,
369    pub q: f64,
370    pub convention: IqCarrierConvention,
371    pub carrier_hz: f64,
372    pub reference_phase_rad: f64,
373    pub signed_baseband_offset_hz: f64,
374}
375
376impl QualifiedIqSample {
377    pub fn validate(&self) -> Result<(), ClockDisciplineError> {
378        if !self.i.is_finite()
379            || !self.q.is_finite()
380            || !self.carrier_hz.is_finite()
381            || self.carrier_hz <= 0.0
382            || !self.reference_phase_rad.is_finite()
383            || !self.signed_baseband_offset_hz.is_finite()
384        {
385            return Err(ClockDisciplineError::NonFiniteIqParameter);
386        }
387        Ok(())
388    }
389
390    /// Reconstruct the instantaneous real physical waveform value at elapsed time `dt_seconds`
391    /// from the sample's phase origin (`theta = 2 * pi * carrier_hz * dt_seconds + reference_phase_rad`):
392    /// - `EmfNegativeCarrier`: $\operatorname{Re}((I + iQ) e^{-i\theta}) = I \cos\theta + Q \sin\theta$.
393    /// - `QacPositiveCarrier`: $\operatorname{Re}((I + iQ) e^{+i\theta}) = I \cos\theta - Q \sin\theta$.
394    pub fn reconstruct_real_at(&self, dt_seconds: f64) -> Result<f64, ClockDisciplineError> {
395        self.validate()?;
396        if !dt_seconds.is_finite() {
397            return Err(ClockDisciplineError::NonFiniteIqParameter);
398        }
399        let theta = TAU * self.carrier_hz * dt_seconds + self.reference_phase_rad;
400        let (sin_t, cos_t) = theta.sin_cos();
401        let real = match self.convention {
402            IqCarrierConvention::EmfNegativeCarrier => self.i * cos_t + self.q * sin_t,
403            IqCarrierConvention::QacPositiveCarrier => self.i * cos_t - self.q * sin_t,
404        };
405        Ok(real)
406    }
407}
408
409/// Guard against direct raw `memcpy` / re-labeling of I/Q samples across conventions (C02-C08).
410///
411/// Attempting to treat an `EmfNegativeCarrier` `(I, Q)` sample as `QacPositiveCarrier` (or vice
412/// versa) without conjugation is rejected with `ClockDisciplineError::UnconjugatedCarrierMemcpyRejected`.
413pub fn reject_unconjugated_iq_memcpy(
414    source_convention: IqCarrierConvention,
415    target_convention: IqCarrierConvention,
416) -> Result<(), ClockDisciplineError> {
417    if source_convention != target_convention {
418        return Err(ClockDisciplineError::UnconjugatedCarrierMemcpyRejected);
419    }
420    Ok(())
421}
422
423/// Explicitly convert a `QualifiedIqSample` to `target_convention` and optional `target_phase_origin_shift_seconds`
424/// ($\Delta t_0 = t_{0,\text{target}} - t_{0,\text{source}}$) per C02-C08:
425///
426/// When `source.convention != target_convention`:
427/// 1. Conjugates the complex phasor: $z_{\text{conj}} = \overline{z_{\text{src}}} = (I, -Q)$.
428/// 2. Negates the reference phase and signed baseband offset so that the physical RF/acoustic
429///    frequency $f_{\text{phys}}$ and real reconstructed waveform remain invariant:
430///    - With $\phi_{\text{ref}} = 0$ and $\Delta t_0 = 0$: `z_QAC = conj(z_EMF) = (I, -Q)` and
431///      `signed_baseband_offset_qac = -signed_baseband_offset_emf`.
432/// 3. If `target_phase_origin_shift_seconds != 0.0`, folds the phase-origin shift $\Delta\theta = 2\pi f_c \Delta t_0$
433///    into the converted complex phasor so that evaluating at $t - t_{0,\text{target}}$ matches
434///    evaluating the source at $t - t_{0,\text{source}}$.
435pub fn convert_iq_sample_between_conventions(
436    source: QualifiedIqSample,
437    target_convention: IqCarrierConvention,
438    target_phase_origin_shift_seconds: f64,
439) -> Result<QualifiedIqSample, ClockDisciplineError> {
440    source.validate()?;
441    if !target_phase_origin_shift_seconds.is_finite() {
442        return Err(ClockDisciplineError::NonFiniteIqParameter);
443    }
444
445    let (mut i_out, mut q_out, mut offset_out) = if source.convention == target_convention {
446        (source.i, source.q, source.signed_baseband_offset_hz)
447    } else {
448        (source.i, -source.q, -source.signed_baseband_offset_hz)
449    };
450
451    // Fold source reference_phase_rad and any phase-origin shift into the phasor so the returned
452    // sample has reference_phase_rad == 0.0 in the target frame if desired, or preserve reference_phase_rad
453    // when target_phase_origin_shift_seconds == 0.0 and reference_phase_rad == 0.0.
454    let origin_delta_theta = TAU * source.carrier_hz * target_phase_origin_shift_seconds;
455    if origin_delta_theta != 0.0 || (source.convention != target_convention && source.reference_phase_rad != 0.0) {
456        // Under target_convention, rotate phasor so Re(z_out * exp(s_target * i * 2pi f_c (t - t_target)))
457        // equals Re(z_src * exp(s_src * i * (2pi f_c (t - t_src) + phi_src))).
458        let total_phase = match target_convention {
459            IqCarrierConvention::EmfNegativeCarrier => {
460                // Re((I' + iQ') exp(-i 2pi f_c (t - t_target))) = I' cos(psi) + Q' sin(psi)
461                // Equals I_out cos(psi + delta) + Q_out sin(psi + delta) when (I' + iQ') = (I_out + iQ_out) exp(-i delta).
462                let phi_eff = if source.convention == target_convention {
463                    source.reference_phase_rad
464                } else {
465                    -source.reference_phase_rad
466                };
467                -(origin_delta_theta + phi_eff)
468            }
469            IqCarrierConvention::QacPositiveCarrier => {
470                // Re((I' + iQ') exp(+i 2pi f_c (t - t_target))) = I' cos(psi) - Q' sin(psi)
471                // Equals I_out cos(psi + delta) - Q_out sin(psi + delta) when (I' + iQ') = (I_out + iQ_out) exp(+i delta).
472                let phi_eff = if source.convention == target_convention {
473                    source.reference_phase_rad
474                } else {
475                    source.reference_phase_rad
476                };
477                origin_delta_theta + phi_eff
478            }
479        };
480        let (sin_p, cos_p) = total_phase.sin_cos();
481        let i_rot = i_out * cos_p - q_out * sin_p;
482        let q_rot = i_out * sin_p + q_out * cos_p;
483        i_out = i_rot;
484        q_out = q_rot;
485        if offset_out == -0.0 {
486            offset_out = 0.0;
487        }
488        return Ok(QualifiedIqSample {
489            i: i_out,
490            q: q_out,
491            convention: target_convention,
492            carrier_hz: source.carrier_hz,
493            reference_phase_rad: 0.0,
494            signed_baseband_offset_hz: offset_out,
495        });
496    }
497
498    Ok(QualifiedIqSample {
499        i: i_out,
500        q: q_out,
501        convention: target_convention,
502        carrier_hz: source.carrier_hz,
503        reference_phase_rad: source.reference_phase_rad,
504        signed_baseband_offset_hz: offset_out,
505    })
506}
507
508fn validate_known_time_uncertainty(u_t: Option<f64>) -> Result<f64, ClockDisciplineError> {
509    match u_t {
510        Some(v) if v.is_finite() && v >= 0.0 => Ok(v),
511        _ => Err(ClockDisciplineError::UnknownOrInvalidTimeUncertainty),
512    }
513}
514
515fn rational_floor_seconds(instant: RationalInstant) -> i128 {
516    let n = instant.numerator();
517    let d = instant.denominator();
518    if n >= 0 {
519        n / d
520    } else {
521        (n - d + 1) / d
522    }
523}
524
525#[derive(Clone, Copy, Debug, PartialEq, Eq)]
526pub enum ClockDisciplineError {
527    InvalidIdentifier,
528    InvalidClockScale,
529    InvalidLeapSecondTable,
530    LeapTableExpiredOrOutOfRange,
531    RationalOverflow,
532    UnknownOrInvalidTimeUncertainty,
533    CrossClockOriginRejected,
534    ClockParametersMismatch,
535    MappingOutsideValidityWindow,
536    InstantNotSimultaneous,
537    InvalidCarrierFrequency,
538    InvalidPhaseCoherenceBudget,
539    PhaseUncertaintyOverflow,
540    PhaseUncertaintyExceedsBudget,
541    UnknownIqCarrierConvention,
542    NonFiniteIqParameter,
543    UnconjugatedCarrierMemcpyRejected,
544}