Skip to main content

nautilus_architect_ax/common/
parse.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Conversion functions that translate AX API schemas into Nautilus types.
17
18use std::{
19    io::{Cursor, Write},
20    sync::LazyLock,
21};
22
23use ahash::RandomState;
24use anyhow::Context;
25use nautilus_core::nanos::UnixNanos;
26pub use nautilus_core::serialization::{
27    deserialize_decimal_or_zero, deserialize_optional_decimal,
28    deserialize_optional_decimal_from_str, deserialize_optional_decimal_or_zero,
29    deserialize_optional_decimal_str, parse_decimal, parse_optional_decimal,
30    serialize_decimal_as_str, serialize_optional_decimal_as_str,
31};
32use nautilus_model::{
33    data::BarSpecification,
34    enums::AggressorSide,
35    identifiers::{ClientOrderId, TradeId},
36    types::{Price, Quantity, fixed::FIXED_PRECISION, quantity::QuantityRaw},
37};
38
39use super::enums::AxCandleWidth;
40
41const NANOSECONDS_IN_SECOND: u64 = 1_000_000_000;
42
43/// Converts an AX epoch-seconds timestamp to [`UnixNanos`].
44///
45/// # Errors
46///
47/// Returns an error if `seconds` is negative (malformed data from AX).
48pub fn ax_timestamp_s_to_unix_nanos(seconds: i64) -> anyhow::Result<UnixNanos> {
49    anyhow::ensure!(
50        seconds >= 0,
51        "AX timestamp must be non-negative, was {seconds}"
52    );
53    Ok(UnixNanos::from(seconds as u64 * NANOSECONDS_IN_SECOND))
54}
55
56/// Converts AX `ts` (seconds) + `tn` (nanoseconds) fields to [`UnixNanos`].
57///
58/// # Errors
59///
60/// Returns an error if `seconds` is negative (malformed data from AX).
61pub fn ax_timestamp_stn_to_unix_nanos(seconds: i64, nanos: i64) -> anyhow::Result<UnixNanos> {
62    anyhow::ensure!(
63        seconds >= 0,
64        "AX timestamp must be non-negative, was {seconds}"
65    );
66    let nanos_part = nanos.max(0) as u64;
67    Ok(UnixNanos::from(
68        seconds as u64 * NANOSECONDS_IN_SECOND + nanos_part,
69    ))
70}
71
72/// Converts an AX nanosecond timestamp to [`UnixNanos`].
73///
74/// # Errors
75///
76/// Returns an error if `nanos` is negative (malformed data from AX).
77pub fn ax_timestamp_ns_to_unix_nanos(nanos: i64) -> anyhow::Result<UnixNanos> {
78    anyhow::ensure!(
79        nanos >= 0,
80        "AX timestamp_ns must be non-negative, was {nanos}"
81    );
82    Ok(UnixNanos::from(nanos as u64))
83}
84
85/// Domain separator for the market-data trade identity digest.
86///
87/// Changing this invalidates every AX `TradeId` already published or persisted, so bump the
88/// version suffix only as a deliberate decision.
89const TRADE_ID_DOMAIN: &[u8] = b"nautilus-architect-ax/trade-id/v1";
90
91/// Creates a [`TradeId`] for an AX market-data trade.
92///
93/// AX publishes no trade identifier for market data: `GET /trades` and the market-data WebSocket
94/// both carry only `ts`, `tn`, `s`, `p`, `q`, and `d`, and `tn` is the nanosecond component of the
95/// timestamp rather than a sequence number. The composed timestamp alone is not unique either,
96/// because one aggressor sweeping several levels reports multiple prints at an identical `ts` and
97/// `tn`. Across 100 sandbox trades on 2026-07-25, `GBPUSD-PERP` yielded only 64 distinct
98/// timestamps.
99///
100/// The identity is therefore the composed timestamp plus a digest over the price, quantity, and
101/// aggressor side, which separated 99 of those 100 prints. Two prints identical in all five
102/// fields remain indistinguishable; nothing the venue publishes separates them. A sandbox run on
103/// 2026-07-25 observed exactly that, two `JPYUSD-PERP` prints agreeing on timestamp, price,
104/// quantity, and side, so the residual is real rather than theoretical at roughly 1 to 4 percent
105/// of prints.
106///
107/// That residual is accepted because a duplicate here cannot reach an execution. Live fills carry
108/// the venue's own identifiers, `fill.trade_id` on REST and `execution.tid` on the orders
109/// WebSocket, and the backtest matching engine mints its own trade IDs with a per-timestamp
110/// counter. This function is called only from the two market-data `parse_trade_tick` functions, so
111/// a duplicate is a market-data fidelity limit and never an execution or position-accounting risk.
112/// Only a consumer that itself deduplicates on [`TradeId`] is affected; nothing in the Nautilus
113/// data path compares them.
114///
115/// Both transports must call this so the same trade fetched historically and received live gets
116/// one identity. The digest covers the parsed [`Price`] and [`Quantity`] rather than the wire
117/// text, because AX sends the same price as `"1.339700000000"` over REST and in a shorter form
118/// over the WebSocket.
119///
120/// Both REST and WebSocket trade models require the aggressor side, preserving identity across
121/// transports for the same print.
122///
123/// The decimal timestamp and 16-digit hexadecimal digest are separated by a hyphen. A timestamp
124/// beyond 19 digits exceeds [`TradeId`]'s 36-character maximum and returns an error rather than
125/// silently truncating.
126///
127/// # Errors
128///
129/// Returns an error if the composed identity is not a valid [`TradeId`].
130pub fn create_architect_trade_id(
131    ts_event: UnixNanos,
132    price: Price,
133    quantity: Quantity,
134    aggressor_side: AggressorSide,
135) -> anyhow::Result<TradeId> {
136    const FAILED: &str = "Failed to create TradeId";
137
138    // Normalized decimals, not raw fixed-point, so the identity survives a precision change
139    let price = price.as_decimal().normalize();
140    let quantity = quantity.as_decimal().normalize();
141
142    let side = match aggressor_side {
143        AggressorSide::NoAggressor => b'N',
144        AggressorSide::Buy => b'B',
145        AggressorSide::Sell => b'S',
146    };
147
148    // One-shot hashing avoids streaming setup for this fixed-size trade identity
149    let mut input = [0u8; TRADE_ID_DOMAIN.len() + 8 + 16 + 4 + 16 + 4 + 1];
150    let mut offset = 0;
151    for part in [
152        TRADE_ID_DOMAIN,
153        &ts_event.as_u64().to_be_bytes(),
154        &price.mantissa().to_be_bytes(),
155        &price.scale().to_be_bytes(),
156        &quantity.mantissa().to_be_bytes(),
157        &quantity.scale().to_be_bytes(),
158        &[side],
159    ] {
160        let end = offset + part.len();
161        input[offset..end].copy_from_slice(part);
162        offset = end;
163    }
164
165    let hash = blake3::hash(&input);
166
167    let mut digest = [0u8; 8];
168    digest.copy_from_slice(&hash.as_bytes()[..8]);
169    let suffix = u64::from_be_bytes(digest);
170
171    // Hold even a 20-digit timestamp so TradeId still rejects IDs beyond its capacity
172    let mut buffer = [0u8; 37];
173    let mut cursor = Cursor::new(buffer.as_mut_slice());
174    write!(cursor, "{}-{suffix:016x}", ts_event.as_u64()).context(FAILED)?;
175    let len = cursor.position() as usize;
176
177    TradeId::from_bytes(&buffer[..len]).context(FAILED)
178}
179
180/// Cached hasher state for deterministic client order ID to cid conversion
181static CID_HASHER: LazyLock<RandomState> = LazyLock::new(|| {
182    RandomState::with_seeds(
183        0x517cc1b727220a95,
184        0x9b5c18c90c3c314d,
185        0x5851f42d4c957f2d,
186        0x14057b7ef767814f,
187    )
188});
189
190/// Maps a Nautilus [`BarSpecification`] to an [`AxCandleWidth`].
191///
192/// # Errors
193///
194/// Returns an error if the bar specification is not supported by Ax.
195pub fn map_bar_spec_to_candle_width(spec: &BarSpecification) -> anyhow::Result<AxCandleWidth> {
196    AxCandleWidth::try_from(spec)
197}
198
199/// Converts a [`Quantity`] to an i64 contract count for AX orders.
200///
201/// AX uses integer contracts only. Uses integer arithmetic to avoid
202/// floating-point precision issues.
203///
204/// # Errors
205///
206/// Returns an error if:
207/// - The quantity represents a fractional number of contracts.
208/// - The quantity is zero.
209pub fn quantity_to_contracts(quantity: Quantity) -> anyhow::Result<u64> {
210    let raw = quantity.raw();
211    let scale = 10_u64.pow(FIXED_PRECISION as u32) as QuantityRaw;
212
213    // AX requires whole contract quantities
214    if !raw.is_multiple_of(scale) {
215        anyhow::bail!(
216            "AX requires whole contract quantities, was {}",
217            quantity.as_f64()
218        );
219    }
220
221    // QuantityRaw is u128 under the `high-precision` feature and u64 otherwise,
222    // so the narrowing cast is conditional on the active feature set.
223    #[allow(clippy::unnecessary_cast)]
224    let contracts = (raw / scale) as u64;
225    if contracts == 0 {
226        anyhow::bail!("Order quantity must be at least 1 contract");
227    }
228    Ok(contracts)
229}
230
231/// Converts a [`ClientOrderId`] to a deterministic AX `cid` in the non-negative `int64` range.
232///
233/// Inbound WebSocket `cid` values remain `u64` because venue messages can exceed `int64`.
234#[must_use]
235pub fn client_order_id_to_cid(client_order_id: &ClientOrderId) -> u64 {
236    CID_HASHER.hash_one(client_order_id.inner()) & i64::MAX as u64
237}
238
239/// Creates a [`ClientOrderId`] from a cid value.
240///
241/// Used when we receive an order with a cid but cannot resolve it to the
242/// original ClientOrderId (e.g., after restart when in-memory mapping is lost).
243#[must_use]
244pub fn cid_to_client_order_id(cid: u64) -> ClientOrderId {
245    ClientOrderId::new(format!("CID-{cid}"))
246}
247
248#[cfg(test)]
249mod tests {
250    use nautilus_model::{
251        enums::{BarAggregation, PriceType},
252        identifiers::ClientOrderId,
253        types::Quantity,
254    };
255    use rstest::rstest;
256    use rust_decimal::Decimal;
257    use rust_decimal_macros::dec;
258
259    use super::*;
260
261    /// The composed timestamp of the captured `EURUSD-PERP` trade shared by the REST and
262    /// WebSocket fixtures.
263    const CAPTURED_TS_EVENT: u64 = 1_766_193_240_334_589_144;
264
265    fn captured_trade_id() -> TradeId {
266        create_architect_trade_id(
267            UnixNanos::from(CAPTURED_TS_EVENT),
268            Price::from_decimal_dp(dec!(1.1719), 4).unwrap(),
269            Quantity::from_decimal_dp(dec!(400), 0).unwrap(),
270            AggressorSide::Buy,
271        )
272        .unwrap()
273    }
274
275    #[rstest]
276    fn test_create_architect_trade_id_format() {
277        let trade_id = captured_trade_id().to_string();
278
279        let (timestamp, digest) = trade_id.split_once('-').unwrap();
280
281        assert_eq!(trade_id.len(), 36);
282        assert_eq!(timestamp, CAPTURED_TS_EVENT.to_string());
283        assert_eq!(digest.len(), 16);
284        assert!(digest.chars().all(|c| c.is_ascii_hexdigit()));
285    }
286
287    #[rstest]
288    #[case(0, AggressorSide::Buy, "0-d66565de305e3202")]
289    #[case(9, AggressorSide::Buy, "9-234d0e8a3df3ae3a")]
290    #[case(10, AggressorSide::Buy, "10-530bf8286ba92b03")]
291    #[case(11, AggressorSide::Buy, "11-011253287c67070e")]
292    #[case(
293        CAPTURED_TS_EVENT,
294        AggressorSide::Buy,
295        "1766193240334589144-38b4fe5a94a253d0"
296    )]
297    #[case(
298        CAPTURED_TS_EVENT,
299        AggressorSide::Sell,
300        "1766193240334589144-5e683093e85c0d45"
301    )]
302    #[case(
303        CAPTURED_TS_EVENT,
304        AggressorSide::NoAggressor,
305        "1766193240334589144-925e31984d86a444"
306    )]
307    #[case(
308        9_999_999_999_999_999_999,
309        AggressorSide::Buy,
310        "9999999999999999999-9b3cb6ef2c9195a6"
311    )]
312    fn test_create_architect_trade_id_preserves_bytes(
313        #[case] timestamp: u64,
314        #[case] aggressor_side: AggressorSide,
315        #[case] expected: &str,
316    ) {
317        let trade_id = create_architect_trade_id(
318            UnixNanos::from(timestamp),
319            Price::from_decimal_dp(dec!(1.1719), 4).unwrap(),
320            Quantity::from_decimal_dp(dec!(400), 0).unwrap(),
321            aggressor_side,
322        )
323        .unwrap();
324
325        assert_eq!(trade_id.as_str(), expected);
326    }
327
328    #[rstest]
329    fn test_create_architect_trade_id_is_deterministic() {
330        assert_eq!(captured_trade_id(), captured_trade_id());
331    }
332
333    #[rstest]
334    fn test_create_architect_trade_id_ignores_trailing_wire_zeros() {
335        // AX sends this price as "1.1719" on the WebSocket and "1.171900000000" on REST
336        let padded = create_architect_trade_id(
337            UnixNanos::from(CAPTURED_TS_EVENT),
338            Price::from_decimal_dp(dec!(1.17190000), 4).unwrap(),
339            Quantity::from_decimal_dp(dec!(400.00), 0).unwrap(),
340            AggressorSide::Buy,
341        )
342        .unwrap();
343
344        assert_eq!(padded, captured_trade_id());
345    }
346
347    #[rstest]
348    fn test_create_architect_trade_id_ignores_instrument_precision() {
349        // A venue tick size change between a historical request and the live stream must not
350        // split one trade into two identities.
351        let wider = create_architect_trade_id(
352            UnixNanos::from(CAPTURED_TS_EVENT),
353            Price::from_decimal_dp(dec!(1.1719), 6).unwrap(),
354            Quantity::from_decimal_dp(dec!(400), 2).unwrap(),
355            AggressorSide::Buy,
356        )
357        .unwrap();
358
359        assert_eq!(wider, captured_trade_id());
360    }
361
362    #[rstest]
363    #[case(dec!(1.1720), dec!(400), AggressorSide::Buy)]
364    #[case(dec!(1.1719), dec!(100), AggressorSide::Buy)]
365    #[case(dec!(1.1719), dec!(400), AggressorSide::Sell)]
366    #[case(dec!(1.1719), dec!(400), AggressorSide::NoAggressor)]
367    fn test_create_architect_trade_id_separates_prints_within_one_timestamp(
368        #[case] price: Decimal,
369        #[case] quantity: Decimal,
370        #[case] aggressor_side: AggressorSide,
371    ) {
372        let other = create_architect_trade_id(
373            UnixNanos::from(CAPTURED_TS_EVENT),
374            Price::from_decimal_dp(price, 4).unwrap(),
375            Quantity::from_decimal_dp(quantity, 0).unwrap(),
376            aggressor_side,
377        )
378        .unwrap();
379
380        assert_ne!(other, captured_trade_id());
381    }
382
383    #[rstest]
384    #[case(10_000_000_000_000_000_000)]
385    #[case(u64::MAX)]
386    fn test_create_architect_trade_id_rejects_timestamp_beyond_capacity(#[case] timestamp: u64) {
387        // Twenty-digit timestamps exceed the 36-character format
388        let error = create_architect_trade_id(
389            UnixNanos::from(timestamp),
390            Price::from_decimal_dp(dec!(1.1719), 4).unwrap(),
391            Quantity::from_decimal_dp(dec!(400), 0).unwrap(),
392            AggressorSide::Buy,
393        )
394        .unwrap_err();
395
396        assert_eq!(error.to_string(), "Failed to create TradeId");
397    }
398
399    #[rstest]
400    fn test_client_order_id_to_cid_deterministic() {
401        let coid = ClientOrderId::new("O-20240101-000001");
402
403        // Must produce same result across multiple calls
404        let cid1 = client_order_id_to_cid(&coid);
405        let cid2 = client_order_id_to_cid(&coid);
406        let cid3 = client_order_id_to_cid(&coid);
407
408        assert_eq!(cid1, cid2);
409        assert_eq!(cid2, cid3);
410    }
411
412    #[rstest]
413    fn test_client_order_id_to_cid_different_ids() {
414        let coid1 = ClientOrderId::new("O-20240101-000001");
415        let coid2 = ClientOrderId::new("O-20240101-000002");
416
417        let cid1 = client_order_id_to_cid(&coid1);
418        let cid2 = client_order_id_to_cid(&coid2);
419
420        assert_ne!(cid1, cid2);
421    }
422
423    #[rstest]
424    fn test_client_order_id_to_cid_fits_signed_64_bit_range() {
425        let coid = ClientOrderId::new("O-20260720-055815-001-001-1");
426
427        let cid = client_order_id_to_cid(&coid);
428
429        assert!(i64::try_from(cid).is_ok());
430    }
431
432    #[rstest]
433    #[case("O-1")]
434    #[case("O-SHORT")]
435    #[case("O-20240101-000001")]
436    #[case("Order-with-dashes-and-digits-12345")]
437    #[case("SINGLE")]
438    #[case("a")]
439    #[case("X")]
440    #[case("LONG-ABCDEFGHIJKLMNOPQRSTUVWXYZ-0123456789")]
441    fn test_client_order_id_to_cid_stable_across_varied_inputs(#[case] value: &str) {
442        // The hash must be deterministic for any valid ClientOrderId, and the
443        // recovered ClientOrderId via cid_to_client_order_id must match the
444        // "CID-{cid}" format so reconciliation can resolve lost mappings.
445        let coid = ClientOrderId::new(value);
446        let cid_a = client_order_id_to_cid(&coid);
447        let cid_b = client_order_id_to_cid(&coid);
448        assert_eq!(cid_a, cid_b, "hash must be deterministic");
449
450        let recovered = cid_to_client_order_id(cid_a);
451        assert!(
452            recovered.inner().starts_with("CID-"),
453            "recovered id should have CID prefix: {recovered}",
454        );
455        assert!(
456            !recovered.inner().is_empty(),
457            "recovered id should not be empty",
458        );
459    }
460
461    #[rstest]
462    fn test_client_order_id_to_cid_collision_resistance_small_corpus() {
463        // Collision-free over a handful of distinct client order IDs.
464        let values = [
465            "O-1",
466            "O-2",
467            "O-10",
468            "O-11",
469            "O-20240101-000001",
470            "O-20240101-000002",
471            "strategy-a/1",
472            "strategy-a/2",
473            "strategy-b/1",
474        ];
475
476        let mut seen = std::collections::HashSet::new();
477        for v in values {
478            let coid = ClientOrderId::new(v);
479            let cid = client_order_id_to_cid(&coid);
480            assert!(seen.insert(cid), "cid collision for {v}");
481        }
482    }
483
484    #[rstest]
485    fn test_quantity_to_contracts_valid_precision_zero() {
486        let qty = Quantity::new(10.0, 0);
487        let result = quantity_to_contracts(qty);
488        assert!(result.is_ok());
489        assert_eq!(result.unwrap(), 10);
490    }
491
492    #[rstest]
493    fn test_quantity_to_contracts_valid_with_precision() {
494        // Whole number with non-zero precision should work
495        let qty = Quantity::new(10.0, 2);
496        let result = quantity_to_contracts(qty);
497        assert!(result.is_ok());
498        assert_eq!(result.unwrap(), 10);
499    }
500
501    #[rstest]
502    fn test_quantity_to_contracts_fractional_rejects() {
503        let qty = Quantity::new(10.5, 1);
504        let result = quantity_to_contracts(qty);
505        assert!(result.is_err());
506    }
507
508    #[rstest]
509    fn test_quantity_to_contracts_zero_rejects() {
510        let qty = Quantity::new(0.0, 0);
511        let result = quantity_to_contracts(qty);
512        assert!(result.is_err());
513    }
514
515    #[rstest]
516    fn test_map_bar_spec_1_second() {
517        let spec = BarSpecification::new(1, BarAggregation::Second, PriceType::Last);
518        let result = map_bar_spec_to_candle_width(&spec);
519        assert!(result.is_ok());
520        assert!(matches!(result.unwrap(), AxCandleWidth::Seconds1));
521    }
522
523    #[rstest]
524    fn test_map_bar_spec_5_second() {
525        let spec = BarSpecification::new(5, BarAggregation::Second, PriceType::Last);
526        let result = map_bar_spec_to_candle_width(&spec);
527        assert!(result.is_ok());
528        assert!(matches!(result.unwrap(), AxCandleWidth::Seconds5));
529    }
530
531    #[rstest]
532    fn test_map_bar_spec_1_minute() {
533        let spec = BarSpecification::new(1, BarAggregation::Minute, PriceType::Last);
534        let result = map_bar_spec_to_candle_width(&spec);
535        assert!(result.is_ok());
536        assert!(matches!(result.unwrap(), AxCandleWidth::Minutes1));
537    }
538
539    #[rstest]
540    fn test_map_bar_spec_5_minute() {
541        let spec = BarSpecification::new(5, BarAggregation::Minute, PriceType::Last);
542        let result = map_bar_spec_to_candle_width(&spec);
543        assert!(result.is_ok());
544        assert!(matches!(result.unwrap(), AxCandleWidth::Minutes5));
545    }
546
547    #[rstest]
548    fn test_map_bar_spec_15_minute() {
549        let spec = BarSpecification::new(15, BarAggregation::Minute, PriceType::Last);
550        let result = map_bar_spec_to_candle_width(&spec);
551        assert!(result.is_ok());
552        assert!(matches!(result.unwrap(), AxCandleWidth::Minutes15));
553    }
554
555    #[rstest]
556    fn test_map_bar_spec_1_hour() {
557        let spec = BarSpecification::new(1, BarAggregation::Hour, PriceType::Last);
558        let result = map_bar_spec_to_candle_width(&spec);
559        assert!(result.is_ok());
560        assert!(matches!(result.unwrap(), AxCandleWidth::Hours1));
561    }
562
563    #[rstest]
564    fn test_map_bar_spec_1_day() {
565        let spec = BarSpecification::new(1, BarAggregation::Day, PriceType::Last);
566        let result = map_bar_spec_to_candle_width(&spec);
567        assert!(result.is_ok());
568        assert!(matches!(result.unwrap(), AxCandleWidth::Days1));
569    }
570
571    #[rstest]
572    fn test_map_bar_spec_unsupported_step() {
573        let spec = BarSpecification::new(3, BarAggregation::Minute, PriceType::Last);
574        let result = map_bar_spec_to_candle_width(&spec);
575        assert!(result.is_err());
576    }
577
578    #[rstest]
579    fn test_map_bar_spec_unsupported_aggregation() {
580        let spec = BarSpecification::new(1, BarAggregation::Tick, PriceType::Last);
581        let result = map_bar_spec_to_candle_width(&spec);
582        assert!(result.is_err());
583    }
584
585    #[rstest]
586    fn test_ax_timestamp_s_to_unix_nanos_valid() {
587        let result = ax_timestamp_s_to_unix_nanos(1_000).unwrap();
588        assert_eq!(result, UnixNanos::from(1_000_000_000_000u64));
589    }
590
591    #[rstest]
592    fn test_ax_timestamp_s_to_unix_nanos_zero() {
593        let result = ax_timestamp_s_to_unix_nanos(0).unwrap();
594        assert_eq!(result, UnixNanos::from(0u64));
595    }
596
597    #[rstest]
598    fn test_ax_timestamp_s_to_unix_nanos_negative_errors() {
599        assert!(ax_timestamp_s_to_unix_nanos(-1).is_err());
600    }
601
602    #[rstest]
603    fn test_ax_timestamp_ns_to_unix_nanos_valid() {
604        let result = ax_timestamp_ns_to_unix_nanos(1_000_000_000).unwrap();
605        assert_eq!(result, UnixNanos::from(1_000_000_000u64));
606    }
607
608    #[rstest]
609    fn test_ax_timestamp_ns_to_unix_nanos_negative_errors() {
610        assert!(ax_timestamp_ns_to_unix_nanos(-1).is_err());
611    }
612
613    #[rstest]
614    fn test_ax_timestamp_stn_to_unix_nanos_combines_seconds_and_nanos() {
615        let result = ax_timestamp_stn_to_unix_nanos(1_000, 500).unwrap();
616        assert_eq!(result, UnixNanos::from(1_000_000_000_500u64));
617    }
618
619    #[rstest]
620    fn test_ax_timestamp_stn_to_unix_nanos_zero_nanos() {
621        let result = ax_timestamp_stn_to_unix_nanos(1_000, 0).unwrap();
622        assert_eq!(result, UnixNanos::from(1_000_000_000_000u64));
623    }
624
625    #[rstest]
626    fn test_ax_timestamp_stn_to_unix_nanos_negative_seconds_errors() {
627        assert!(ax_timestamp_stn_to_unix_nanos(-1, 0).is_err());
628    }
629
630    #[rstest]
631    fn test_ax_timestamp_stn_to_unix_nanos_negative_nanos_clamps_to_zero() {
632        let result = ax_timestamp_stn_to_unix_nanos(1_000, -1).unwrap();
633        assert_eq!(result, UnixNanos::from(1_000_000_000_000u64));
634    }
635}