hdds-c 1.0.11

High-performance DDS (Data Distribution Service) implementation in pure Rust
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
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright (c) 2025-2026 naskel.com

//! QoS C FFI bindings for HDDS.
//!
//! Provides C-compatible functions to create, configure, and load QoS profiles.

use std::ffi::CStr;
use std::os::raw::c_char;
use std::ptr;

use hdds::api::QoS;

use crate::HddsError;

/// Opaque handle to a QoS profile.
#[repr(C)]
pub struct HddsQoS {
    _private: [u8; 0],
}

// =============================================================================
// QoS Creation
// =============================================================================

/// Create a default QoS profile (best-effort, volatile).
///
/// # Safety
/// The returned pointer must be freed with `hdds_qos_destroy`.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_default() -> *mut HddsQoS {
    let qos = Box::new(QoS::default());
    Box::into_raw(qos).cast::<HddsQoS>()
}

/// Create a best-effort QoS profile.
///
/// Best-effort QoS does not guarantee delivery but has lower overhead.
///
/// # Safety
/// The returned pointer must be freed with `hdds_qos_destroy`.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_best_effort() -> *mut HddsQoS {
    let qos = Box::new(QoS::best_effort());
    Box::into_raw(qos).cast::<HddsQoS>()
}

/// Create a reliable QoS profile.
///
/// Reliable QoS guarantees delivery with NACK-driven retransmission.
///
/// # Safety
/// The returned pointer must be freed with `hdds_qos_destroy`.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_reliable() -> *mut HddsQoS {
    let qos = Box::new(QoS::reliable());
    Box::into_raw(qos).cast::<HddsQoS>()
}

/// Create an RTI Connext-compatible QoS profile.
///
/// Uses RTI Connext DDS 6.x defaults for interoperability.
///
/// # Safety
/// The returned pointer must be freed with `hdds_qos_destroy`.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_rti_defaults() -> *mut HddsQoS {
    let qos = Box::new(QoS::rti_defaults());
    Box::into_raw(qos).cast::<HddsQoS>()
}

/// Destroy a QoS profile.
///
/// # Safety
/// - `qos` must be a valid pointer returned from a `hdds_qos_*` creation function.
/// - Must not be called more than once with the same pointer.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_destroy(qos: *mut HddsQoS) {
    if !qos.is_null() {
        let _ = Box::from_raw(qos.cast::<QoS>());
    }
}

// =============================================================================
// QoS Loading from XML
// =============================================================================

/// Load QoS from a FastDDS XML profile file.
///
/// Parses the XML file and extracts the default profile's QoS settings.
/// Supports all 22 DDS QoS policies.
///
/// # Arguments
/// - `path`: Path to the FastDDS XML profile file (null-terminated C string).
///
/// # Returns
/// - Valid pointer on success.
/// - NULL if the file cannot be read or parsed.
///
/// # Safety
/// - `path` must be a valid null-terminated C string.
/// - The returned pointer must be freed with `hdds_qos_destroy`.
#[cfg(feature = "qos-loaders")]
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_load_fastdds_xml(path: *const c_char) -> *mut HddsQoS {
    if path.is_null() {
        return ptr::null_mut();
    }

    let Ok(path_str) = CStr::from_ptr(path).to_str() else {
        return ptr::null_mut();
    };

    match QoS::load_fastdds(path_str) {
        Ok(qos) => Box::into_raw(Box::new(qos)).cast::<HddsQoS>(),
        Err(err) => {
            eprintln!("[hdds_c] Failed to load FastDDS XML: {}", err);
            ptr::null_mut()
        }
    }
}

/// Load QoS from a vendor XML file (auto-detect vendor).
///
/// Automatically detects the vendor format and parses accordingly.
/// Currently supports: FastDDS (eProsima).
///
/// # Arguments
/// - `path`: Path to the XML profile file (null-terminated C string).
///
/// # Returns
/// - Valid pointer on success.
/// - NULL if the file cannot be read or parsed.
///
/// # Safety
/// - `path` must be a valid null-terminated C string.
/// - The returned pointer must be freed with `hdds_qos_destroy`.
#[cfg(feature = "qos-loaders")]
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_from_xml(path: *const c_char) -> *mut HddsQoS {
    if path.is_null() {
        return ptr::null_mut();
    }

    let Ok(path_str) = CStr::from_ptr(path).to_str() else {
        return ptr::null_mut();
    };

    match QoS::from_xml(path_str) {
        Ok(qos) => Box::into_raw(Box::new(qos)).cast::<HddsQoS>(),
        Err(err) => {
            eprintln!("[hdds_c] Failed to load QoS from XML: {}", err);
            ptr::null_mut()
        }
    }
}

// =============================================================================
// QoS Builder Methods (Fluent API via mutation)
// =============================================================================

/// Set history depth (KEEP_LAST) on a QoS profile.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_set_history_depth(qos: *mut HddsQoS, depth: u32) -> HddsError {
    if qos.is_null() {
        return HddsError::HddsInvalidArgument;
    }

    let qos_ref = &mut *qos.cast::<QoS>();
    qos_ref.history = hdds::dds::qos::History::KeepLast(depth);
    HddsError::HddsOk
}

/// Set history policy to KEEP_ALL.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_set_history_keep_all(qos: *mut HddsQoS) -> HddsError {
    if qos.is_null() {
        return HddsError::HddsInvalidArgument;
    }

    let qos_ref = &mut *qos.cast::<QoS>();
    qos_ref.history = hdds::dds::qos::History::KeepAll;
    HddsError::HddsOk
}

/// Set durability to VOLATILE.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_set_volatile(qos: *mut HddsQoS) -> HddsError {
    if qos.is_null() {
        return HddsError::HddsInvalidArgument;
    }

    let qos_ref = &mut *qos.cast::<QoS>();
    qos_ref.durability = hdds::dds::qos::Durability::Volatile;
    HddsError::HddsOk
}

/// Set durability to TRANSIENT_LOCAL.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_set_transient_local(qos: *mut HddsQoS) -> HddsError {
    if qos.is_null() {
        return HddsError::HddsInvalidArgument;
    }

    let qos_ref = &mut *qos.cast::<QoS>();
    qos_ref.durability = hdds::dds::qos::Durability::TransientLocal;
    HddsError::HddsOk
}

/// Set durability to PERSISTENT.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_set_persistent(qos: *mut HddsQoS) -> HddsError {
    if qos.is_null() {
        return HddsError::HddsInvalidArgument;
    }

    let qos_ref = &mut *qos.cast::<QoS>();
    qos_ref.durability = hdds::dds::qos::Durability::Persistent;
    HddsError::HddsOk
}

/// Set reliability to RELIABLE.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_set_reliable(qos: *mut HddsQoS) -> HddsError {
    if qos.is_null() {
        return HddsError::HddsInvalidArgument;
    }

    let qos_ref = &mut *qos.cast::<QoS>();
    qos_ref.reliability = hdds::dds::qos::Reliability::Reliable;
    HddsError::HddsOk
}

/// Set reliability to BEST_EFFORT.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_set_best_effort(qos: *mut HddsQoS) -> HddsError {
    if qos.is_null() {
        return HddsError::HddsInvalidArgument;
    }

    let qos_ref = &mut *qos.cast::<QoS>();
    qos_ref.reliability = hdds::dds::qos::Reliability::BestEffort;
    HddsError::HddsOk
}

/// Set deadline period in nanoseconds.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_set_deadline_ns(qos: *mut HddsQoS, period_ns: u64) -> HddsError {
    if qos.is_null() {
        return HddsError::HddsInvalidArgument;
    }

    let qos_ref = &mut *qos.cast::<QoS>();
    qos_ref.deadline = hdds::dds::qos::Deadline::new(std::time::Duration::from_nanos(period_ns));
    HddsError::HddsOk
}

/// Set lifespan duration in nanoseconds.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_set_lifespan_ns(
    qos: *mut HddsQoS,
    duration_ns: u64,
) -> HddsError {
    if qos.is_null() {
        return HddsError::HddsInvalidArgument;
    }

    let qos_ref = &mut *qos.cast::<QoS>();
    qos_ref.lifespan = hdds::dds::qos::Lifespan::new(std::time::Duration::from_nanos(duration_ns));
    HddsError::HddsOk
}

/// Set ownership to SHARED.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_set_ownership_shared(qos: *mut HddsQoS) -> HddsError {
    if qos.is_null() {
        return HddsError::HddsInvalidArgument;
    }

    let qos_ref = &mut *qos.cast::<QoS>();
    qos_ref.ownership = hdds::dds::qos::Ownership::shared();
    HddsError::HddsOk
}

/// Set ownership to EXCLUSIVE with given strength.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_set_ownership_exclusive(
    qos: *mut HddsQoS,
    strength: i32,
) -> HddsError {
    if qos.is_null() {
        return HddsError::HddsInvalidArgument;
    }

    let qos_ref = &mut *qos.cast::<QoS>();
    qos_ref.ownership = hdds::dds::qos::Ownership::exclusive();
    qos_ref.ownership_strength = hdds::dds::qos::OwnershipStrength::new(strength);
    HddsError::HddsOk
}

/// Add a partition name to the QoS.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
/// - `partition` must be a valid null-terminated C string.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_add_partition(
    qos: *mut HddsQoS,
    partition: *const c_char,
) -> HddsError {
    if qos.is_null() || partition.is_null() {
        return HddsError::HddsInvalidArgument;
    }

    let Ok(part_str) = CStr::from_ptr(partition).to_str() else {
        return HddsError::HddsInvalidArgument;
    };

    let qos_ref = &mut *qos.cast::<QoS>();

    // Add new partition using the add() method
    qos_ref.partition.add(part_str);

    HddsError::HddsOk
}

// =============================================================================
// QoS Getters (for inspection/debugging)
// =============================================================================

/// Check if QoS is reliable.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_is_reliable(qos: *const HddsQoS) -> bool {
    if qos.is_null() {
        return false;
    }

    let qos_ref = &*qos.cast::<QoS>();
    matches!(qos_ref.reliability, hdds::dds::qos::Reliability::Reliable)
}

/// Check if QoS is transient-local.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_is_transient_local(qos: *const HddsQoS) -> bool {
    if qos.is_null() {
        return false;
    }

    let qos_ref = &*qos.cast::<QoS>();
    matches!(
        qos_ref.durability,
        hdds::dds::qos::Durability::TransientLocal
    )
}

/// Get history depth.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_get_history_depth(qos: *const HddsQoS) -> u32 {
    if qos.is_null() {
        return 0;
    }

    let qos_ref = &*qos.cast::<QoS>();
    match qos_ref.history {
        hdds::dds::qos::History::KeepLast(depth) => depth,
        hdds::dds::qos::History::KeepAll => 0,
    }
}

/// Get deadline period in nanoseconds.
///
/// Returns `u64::MAX` if infinite.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_get_deadline_ns(qos: *const HddsQoS) -> u64 {
    if qos.is_null() {
        return u64::MAX;
    }

    let qos_ref = &*qos.cast::<QoS>();
    qos_ref.deadline.period.as_nanos() as u64
}

/// Get lifespan duration in nanoseconds.
///
/// Returns `u64::MAX` if infinite.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_get_lifespan_ns(qos: *const HddsQoS) -> u64 {
    if qos.is_null() {
        return u64::MAX;
    }

    let qos_ref = &*qos.cast::<QoS>();
    qos_ref.lifespan.duration.as_nanos() as u64
}

/// Check if ownership is exclusive.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_is_ownership_exclusive(qos: *const HddsQoS) -> bool {
    if qos.is_null() {
        return false;
    }

    let qos_ref = &*qos.cast::<QoS>();
    matches!(
        qos_ref.ownership.kind,
        hdds::dds::qos::OwnershipKind::Exclusive
    )
}

/// Get ownership strength value.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_get_ownership_strength(qos: *const HddsQoS) -> i32 {
    if qos.is_null() {
        return 0;
    }

    let qos_ref = &*qos.cast::<QoS>();
    qos_ref.ownership_strength.value
}

/// Liveliness kind enumeration for C FFI.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(clippy::enum_variant_names)] // C FFI: prefix required (no namespaces in C)
pub enum HddsLivelinessKind {
    /// DDS infrastructure automatically asserts liveliness.
    HddsLivelinessAutomatic = 0,
    /// Application must assert per participant.
    HddsLivelinessManualByParticipant = 1,
    /// Application must assert per writer/topic.
    HddsLivelinessManualByTopic = 2,
}

/// Get liveliness kind.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_get_liveliness_kind(qos: *const HddsQoS) -> HddsLivelinessKind {
    if qos.is_null() {
        return HddsLivelinessKind::HddsLivelinessAutomatic;
    }

    let qos_ref = &*qos.cast::<QoS>();
    match qos_ref.liveliness.kind {
        hdds::dds::qos::LivelinessKind::Automatic => HddsLivelinessKind::HddsLivelinessAutomatic,
        hdds::dds::qos::LivelinessKind::ManualByParticipant => {
            HddsLivelinessKind::HddsLivelinessManualByParticipant
        }
        hdds::dds::qos::LivelinessKind::ManualByTopic => {
            HddsLivelinessKind::HddsLivelinessManualByTopic
        }
    }
}

/// Get liveliness lease duration in nanoseconds.
///
/// Returns `u64::MAX` if infinite.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_get_liveliness_lease_ns(qos: *const HddsQoS) -> u64 {
    if qos.is_null() {
        return u64::MAX;
    }

    let qos_ref = &*qos.cast::<QoS>();
    qos_ref.liveliness.lease_duration.as_nanos() as u64
}

/// Get time-based filter minimum separation in nanoseconds.
///
/// Returns 0 if no filtering (all samples delivered).
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_get_time_based_filter_ns(qos: *const HddsQoS) -> u64 {
    if qos.is_null() {
        return 0;
    }

    let qos_ref = &*qos.cast::<QoS>();
    qos_ref.time_based_filter.minimum_separation.as_nanos() as u64
}

/// Get latency budget in nanoseconds.
///
/// Returns 0 if no latency budget (best effort delivery).
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_get_latency_budget_ns(qos: *const HddsQoS) -> u64 {
    if qos.is_null() {
        return 0;
    }

    let qos_ref = &*qos.cast::<QoS>();
    qos_ref.latency_budget.duration.as_nanos() as u64
}

/// Get transport priority.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_get_transport_priority(qos: *const HddsQoS) -> i32 {
    if qos.is_null() {
        return 0;
    }

    let qos_ref = &*qos.cast::<QoS>();
    qos_ref.transport_priority.value
}

/// Get max samples resource limit.
///
/// Returns `usize::MAX` for unlimited.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_get_max_samples(qos: *const HddsQoS) -> usize {
    if qos.is_null() {
        return usize::MAX;
    }

    let qos_ref = &*qos.cast::<QoS>();
    qos_ref.resource_limits.max_samples
}

/// Get max instances resource limit.
///
/// Returns `usize::MAX` for unlimited.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_get_max_instances(qos: *const HddsQoS) -> usize {
    if qos.is_null() {
        return usize::MAX;
    }

    let qos_ref = &*qos.cast::<QoS>();
    qos_ref.resource_limits.max_instances
}

/// Get max samples per instance resource limit.
///
/// Returns `usize::MAX` for unlimited.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_get_max_samples_per_instance(qos: *const HddsQoS) -> usize {
    if qos.is_null() {
        return usize::MAX;
    }

    let qos_ref = &*qos.cast::<QoS>();
    qos_ref.resource_limits.max_samples_per_instance
}

// =============================================================================
// QoS Setters (additional)
// =============================================================================

/// Set liveliness to automatic with given lease duration in nanoseconds.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_set_liveliness_automatic_ns(
    qos: *mut HddsQoS,
    lease_ns: u64,
) -> HddsError {
    if qos.is_null() {
        return HddsError::HddsInvalidArgument;
    }

    let qos_ref = &mut *qos.cast::<QoS>();
    qos_ref.liveliness =
        hdds::dds::qos::Liveliness::automatic(std::time::Duration::from_nanos(lease_ns));
    HddsError::HddsOk
}

/// Set liveliness to manual-by-participant with given lease duration in nanoseconds.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_set_liveliness_manual_participant_ns(
    qos: *mut HddsQoS,
    lease_ns: u64,
) -> HddsError {
    if qos.is_null() {
        return HddsError::HddsInvalidArgument;
    }

    let qos_ref = &mut *qos.cast::<QoS>();
    qos_ref.liveliness = hdds::dds::qos::Liveliness::manual_by_participant(
        std::time::Duration::from_nanos(lease_ns),
    );
    HddsError::HddsOk
}

/// Set liveliness to manual-by-topic with given lease duration in nanoseconds.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_set_liveliness_manual_topic_ns(
    qos: *mut HddsQoS,
    lease_ns: u64,
) -> HddsError {
    if qos.is_null() {
        return HddsError::HddsInvalidArgument;
    }

    let qos_ref = &mut *qos.cast::<QoS>();
    qos_ref.liveliness =
        hdds::dds::qos::Liveliness::manual_by_topic(std::time::Duration::from_nanos(lease_ns));
    HddsError::HddsOk
}

/// Set time-based filter minimum separation in nanoseconds.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_set_time_based_filter_ns(
    qos: *mut HddsQoS,
    min_separation_ns: u64,
) -> HddsError {
    if qos.is_null() {
        return HddsError::HddsInvalidArgument;
    }

    let qos_ref = &mut *qos.cast::<QoS>();
    qos_ref.time_based_filter =
        hdds::dds::qos::TimeBasedFilter::new(std::time::Duration::from_nanos(min_separation_ns));
    HddsError::HddsOk
}

/// Set latency budget in nanoseconds.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_set_latency_budget_ns(
    qos: *mut HddsQoS,
    budget_ns: u64,
) -> HddsError {
    if qos.is_null() {
        return HddsError::HddsInvalidArgument;
    }

    let qos_ref = &mut *qos.cast::<QoS>();
    qos_ref.latency_budget =
        hdds::dds::qos::LatencyBudget::new(std::time::Duration::from_nanos(budget_ns));
    HddsError::HddsOk
}

/// Set transport priority.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_set_transport_priority(
    qos: *mut HddsQoS,
    priority: i32,
) -> HddsError {
    if qos.is_null() {
        return HddsError::HddsInvalidArgument;
    }

    let qos_ref = &mut *qos.cast::<QoS>();
    qos_ref.transport_priority.value = priority;
    HddsError::HddsOk
}

/// Set resource limits.
///
/// Use `usize::MAX` for any value to indicate unlimited.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_set_resource_limits(
    qos: *mut HddsQoS,
    max_samples: usize,
    max_instances: usize,
    max_samples_per_instance: usize,
) -> HddsError {
    if qos.is_null() {
        return HddsError::HddsInvalidArgument;
    }

    let qos_ref = &mut *qos.cast::<QoS>();
    qos_ref.resource_limits.max_samples = max_samples;
    qos_ref.resource_limits.max_instances = max_instances;
    qos_ref.resource_limits.max_samples_per_instance = max_samples_per_instance;
    HddsError::HddsOk
}

// =============================================================================
// Clone QoS
// =============================================================================

/// Clone a QoS profile.
///
/// # Safety
/// - `qos` must be a valid pointer from `hdds_qos_*` functions.
/// - The returned pointer must be freed with `hdds_qos_destroy`.
#[no_mangle]
pub unsafe extern "C" fn hdds_qos_clone(qos: *const HddsQoS) -> *mut HddsQoS {
    if qos.is_null() {
        return ptr::null_mut();
    }

    let qos_ref = &*qos.cast::<QoS>();
    let cloned = Box::new(qos_ref.clone());
    Box::into_raw(cloned).cast::<HddsQoS>()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::ffi::CString;

    #[test]
    fn test_qos_creation_and_destroy() {
        unsafe {
            let qos = hdds_qos_default();
            assert!(!qos.is_null());
            hdds_qos_destroy(qos);

            let qos = hdds_qos_reliable();
            assert!(!qos.is_null());
            assert!(hdds_qos_is_reliable(qos));
            hdds_qos_destroy(qos);

            let qos = hdds_qos_best_effort();
            assert!(!qos.is_null());
            assert!(!hdds_qos_is_reliable(qos));
            hdds_qos_destroy(qos);
        }
    }

    #[test]
    fn test_qos_setters() {
        unsafe {
            let qos = hdds_qos_default();

            // Test history depth
            assert_eq!(hdds_qos_set_history_depth(qos, 50), HddsError::HddsOk);
            assert_eq!(hdds_qos_get_history_depth(qos), 50);

            // Test transient local
            assert_eq!(hdds_qos_set_transient_local(qos), HddsError::HddsOk);
            assert!(hdds_qos_is_transient_local(qos));

            // Test reliable
            assert_eq!(hdds_qos_set_reliable(qos), HddsError::HddsOk);
            assert!(hdds_qos_is_reliable(qos));

            // Test partition
            let part = CString::new("test_partition").unwrap();
            assert_eq!(
                hdds_qos_add_partition(qos, part.as_ptr()),
                HddsError::HddsOk
            );

            hdds_qos_destroy(qos);
        }
    }

    #[test]
    fn test_qos_clone() {
        unsafe {
            let qos = hdds_qos_reliable();
            hdds_qos_set_history_depth(qos, 42);
            hdds_qos_set_transient_local(qos);

            let cloned = hdds_qos_clone(qos);
            assert!(!cloned.is_null());
            assert!(hdds_qos_is_reliable(cloned));
            assert!(hdds_qos_is_transient_local(cloned));
            assert_eq!(hdds_qos_get_history_depth(cloned), 42);

            hdds_qos_destroy(qos);
            hdds_qos_destroy(cloned);
        }
    }
}