dependency-injector 2.1.0

High-performance, lock-free dependency injection container for Rust
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
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
//! FFI (Foreign Function Interface) bindings for dependency-injector.
//!
//! This module provides a C-compatible API for using the dependency injection
//! container from other languages like Go, Python, C, etc.
//!
//! # Design
//!
//! Since Rust generics cannot cross FFI boundaries, services are registered
//! and resolved by string type names. Service data is passed as raw bytes
//! that can be serialized/deserialized on the foreign language side.
//!
//! # Memory Management
//!
//! - `di_container_new()` allocates a container - must be freed with `di_container_free()`
//! - `di_service_*` functions return service handles - must be freed with `di_service_free()`
//! - `di_error_message()` returns a string - must be freed with `di_string_free()`
//!
//! # Thread Safety
//!
//! The container is thread-safe. All FFI functions can be called from multiple threads.
//! Panics are caught at the FFI boundary (never unwinding into the caller) and surfaced
//! via `di_error_message()`.

use crate::error::DiError;
use std::any::Any;
use std::collections::{HashMap, hash_map::Entry};
use std::ffi::{CStr, CString, c_char};
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::ptr;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, PoisonError, RwLock};

/// Opaque container handle for FFI
pub struct DiContainer {
    /// Map of type names to their registered services (as raw bytes)
    services: RwLock<HashMap<String, Arc<dyn Any + Send + Sync>>>,
    /// Lock state - when set, registration is blocked (removal is not),
    /// matching the core container's locking semantics. Both the store (in
    /// `di_lock`) and the load (in `di_register_singleton`) happen while
    /// holding the `services` write guard, which is what makes locking a
    /// total barrier rather than a check-then-act race.
    locked: AtomicBool,
}

/// Opaque service handle for FFI
pub struct DiService {
    type_name: String,
    data: Vec<u8>,
}

/// Error codes returned by FFI functions
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiErrorCode {
    /// Operation succeeded
    Ok = 0,
    /// Service not found
    NotFound = 1,
    /// Invalid argument (null pointer, invalid UTF-8, etc.)
    InvalidArgument = 2,
    /// Service already registered
    AlreadyRegistered = 3,
    /// Internal error
    InternalError = 4,
    /// Serialization/deserialization error
    SerializationError = 5,
    /// Container is locked - registration is not allowed
    Locked = 6,
}

/// Maps core [`DiError`] values to ABI error codes.
///
/// `CircularDependency`, `CreationFailed`, `ParentDropped`, and `Internal`
/// currently collapse to [`DiErrorCode::InternalError`]; dedicated codes for
/// them can be added to the ABI in a future major version.
impl From<&DiError> for DiErrorCode {
    fn from(err: &DiError) -> Self {
        match err {
            DiError::NotFound { .. } => Self::NotFound,
            DiError::AlreadyRegistered { .. } => Self::AlreadyRegistered,
            DiError::Locked => Self::Locked,
            DiError::CircularDependency { .. }
            | DiError::CreationFailed { .. }
            | DiError::ParentDropped
            | DiError::Internal(_) => Self::InternalError,
        }
    }
}

/// Result type for FFI operations
#[repr(C)]
pub struct DiResult {
    pub code: DiErrorCode,
    pub service: *mut DiService,
}

// Thread-local storage for the last error message
thread_local! {
    static LAST_ERROR: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
}

/// Record `msg` as the thread-local last error.
///
/// Must stay allocation-only and non-reentrant (no logging, callbacks, or
/// re-entry into FFI functions): the `Err` arm of [`ffi_guard`] calls this
/// OUTSIDE `catch_unwind`, so a panic raised here would unwind straight
/// across the FFI boundary. The one failure mode that is not under this
/// module's control - the thread-local having already been destroyed during
/// TLS teardown - is handled explicitly: `try_with` reports it as an error
/// that is dropped, where `with` would panic.
fn set_last_error(msg: impl Into<String>) {
    // Replace control characters (incl. newlines) with spaces: type names
    // are caller-supplied and error strings flow into host application
    // logs verbatim, so this blocks log-forging via crafted names.
    let sanitized: String = msg
        .into()
        .chars()
        .map(|c| if c.is_control() { ' ' } else { c })
        .collect();
    // Deliberately `try_with`: during TLS teardown the thread-local is gone
    // and `with` would panic - here, outside `catch_unwind`.
    let _ = LAST_ERROR.try_with(|e| {
        *e.borrow_mut() = Some(sanitized);
    });
}

/// Run `f`, catching any panic so it cannot unwind across the FFI boundary.
///
/// On panic, records "internal panic: <message>" as the thread-local last
/// error (via [`set_last_error`]) and returns `default` instead. Raw-pointer
/// arguments captured by `f` are not `UnwindSafe`, hence [`AssertUnwindSafe`];
/// the pointers themselves are plain values that cannot be observed in a
/// broken state, so this is sound.
fn ffi_guard<T>(default: T, f: impl FnOnce() -> T) -> T {
    match catch_unwind(AssertUnwindSafe(f)) {
        Ok(value) => value,
        Err(payload) => {
            let msg = if let Some(s) = payload.downcast_ref::<&str>() {
                format!("internal panic: {s}")
            } else if let Some(s) = payload.downcast_ref::<String>() {
                format!("internal panic: {s}")
            } else {
                String::from("internal panic")
            };
            set_last_error(msg);
            default
        }
    }
}

/// Test-only entry point that routes an explicit `&str` panic through
/// [`ffi_guard`]: recovering from lock poisoning removed the last internal
/// panic source, so this keeps the catch-unwind path directly exercised.
#[cfg(test)]
fn panicking_entry_str() -> DiErrorCode {
    ffi_guard(DiErrorCode::InternalError, || panic!("test panic: boom"))
}

/// Companion to [`panicking_entry_str`] covering the `String` payload branch
/// of [`ffi_guard`]'s downcast (format arguments produce a `String` payload).
#[cfg(test)]
fn panicking_entry_string() -> DiErrorCode {
    ffi_guard(DiErrorCode::InternalError, || {
        let detail = String::from("boom-string");
        panic!("test panic: {detail}")
    })
}

// ============================================================================
// Container Lifecycle
// ============================================================================

/// Create a new dependency injection container.
///
/// # Returns
/// A pointer to the new container, or NULL on failure.
///
/// # Safety
/// The returned pointer must be freed with `di_container_free()`.
#[unsafe(no_mangle)]
pub extern "C" fn di_container_new() -> *mut DiContainer {
    ffi_guard(ptr::null_mut(), || {
        let container = Box::new(DiContainer {
            services: RwLock::new(HashMap::new()),
            locked: AtomicBool::new(false),
        });
        Box::into_raw(container)
    })
}

/// Free a container and all its resources.
///
/// # Safety
/// - `container` must be a valid pointer returned by `di_container_new()`
/// - After calling this function, the pointer is invalid
#[unsafe(no_mangle)]
pub unsafe extern "C" fn di_container_free(container: *mut DiContainer) {
    ffi_guard((), || {
        if !container.is_null() {
            // SAFETY: Caller guarantees container is valid
            drop(unsafe { Box::from_raw(container) });
        }
    });
}

/// Create a child scope from a container.
///
/// Inheritance is a snapshot taken at creation time: the child receives a
/// copy of the parent's services as they exist when the scope is created.
/// Services registered in the parent afterwards are not visible to existing
/// child scopes. The child starts unlocked regardless of the parent's lock
/// state, matching the core container's scoping semantics.
///
/// # Returns
/// A pointer to the new scoped container, or NULL on failure.
///
/// # Safety
/// - `container` must be a valid container pointer
/// - The returned pointer must be freed with `di_container_free()`
#[unsafe(no_mangle)]
pub unsafe extern "C" fn di_container_scope(container: *mut DiContainer) -> *mut DiContainer {
    ffi_guard(ptr::null_mut(), || {
        if container.is_null() {
            set_last_error("Container pointer is null");
            return ptr::null_mut();
        }

        // SAFETY: Caller guarantees container is valid
        let parent = unsafe { &*container };

        // Clone the services map for the child scope. Recover from lock
        // poisoning here (and at every lock site below): poisoning cannot
        // leave the map in a torn state because keys are plain Strings and no
        // user code runs under the lock, so every critical section either
        // completes or leaves the map untouched. Recovering prevents one
        // caught panic from permanently bricking the container.
        let services = parent
            .services
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .clone();

        let child = Box::new(DiContainer {
            services: RwLock::new(services),
            locked: AtomicBool::new(false),
        });
        Box::into_raw(child)
    })
}

// ============================================================================
// Service Registration
// ============================================================================

/// Register a singleton service with raw byte data.
///
/// # Arguments
/// - `container` - The container to register in
/// - `type_name` - A unique string identifier for this service type (null-terminated)
/// - `data` - Pointer to the service data bytes
/// - `data_len` - Length of the data in bytes
///
/// # Returns
/// Error code indicating success or failure. Returns `Locked` if the
/// container has been locked with `di_lock()`.
///
/// # Safety
/// - `container` must be a valid container pointer
/// - `type_name` must be a valid null-terminated UTF-8 string
/// - `data` must point to at least `data_len` bytes
#[unsafe(no_mangle)]
pub unsafe extern "C" fn di_register_singleton(
    container: *mut DiContainer,
    type_name: *const c_char,
    data: *const u8,
    data_len: usize,
) -> DiErrorCode {
    ffi_guard(DiErrorCode::InternalError, || {
        // Validate container
        if container.is_null() {
            set_last_error("Container pointer is null");
            return DiErrorCode::InvalidArgument;
        }

        // Validate type_name
        if type_name.is_null() {
            set_last_error("Type name is null");
            return DiErrorCode::InvalidArgument;
        }

        // SAFETY: Caller guarantees type_name is valid
        let type_name_str = if let Ok(s) = unsafe { CStr::from_ptr(type_name) }.to_str() {
            s.to_string()
        } else {
            set_last_error("Type name is not valid UTF-8");
            return DiErrorCode::InvalidArgument;
        };

        // Validate data
        if data.is_null() && data_len > 0 {
            set_last_error("Data pointer is null but length is non-zero");
            return DiErrorCode::InvalidArgument;
        }

        // Copy the data
        let data_vec = if data_len > 0 {
            // SAFETY: Caller guarantees data points to data_len bytes
            unsafe { std::slice::from_raw_parts(data, data_len) }.to_vec()
        } else {
            Vec::new()
        };

        // SAFETY: Caller guarantees container is valid
        let container = unsafe { &*container };

        // Check and insert atomically under a single write lock so two threads
        // cannot both pass the existence check and silently overwrite each other.
        let mut services = container
            .services
            .write()
            .unwrap_or_else(PoisonError::into_inner);

        // Match core semantics: locking blocks registration only. The check
        // lives INSIDE the write-guard critical section, and `di_lock()` takes
        // the same guard before setting the flag, which makes the lock a total
        // barrier: once `di_lock()` returns, no in-flight registration can
        // still land. It also stays ahead of the occupancy check below, so a
        // duplicate name on a locked container still reports `Locked`.
        if container.locked.load(Ordering::Acquire) {
            set_last_error("Container is locked - cannot register new services");
            return DiErrorCode::Locked;
        }

        match services.entry(type_name_str) {
            Entry::Occupied(entry) => {
                set_last_error(format!("Service '{}' is already registered", entry.key()));
                DiErrorCode::AlreadyRegistered
            }
            Entry::Vacant(entry) => {
                let service_data: Arc<dyn Any + Send + Sync> = Arc::new(data_vec);
                entry.insert(service_data);
                DiErrorCode::Ok
            }
        }
    })
}

/// Register a singleton service with a JSON string.
///
/// This is a convenience function for languages that prefer JSON serialization.
///
/// # Arguments
/// - `container` - The container to register in
/// - `type_name` - A unique string identifier for this service type
/// - `json_data` - JSON-serialized service data (null-terminated)
///
/// # Returns
/// Error code indicating success or failure. Returns `Locked` if the
/// container has been locked with `di_lock()`.
///
/// # Safety
/// - `container` must be a valid pointer to a `DiContainer` returned from `di_container_create`
/// - `type_name` must be a valid null-terminated C string
/// - `json_data` must be a valid null-terminated C string
#[unsafe(no_mangle)]
pub unsafe extern "C" fn di_register_singleton_json(
    container: *mut DiContainer,
    type_name: *const c_char,
    json_data: *const c_char,
) -> DiErrorCode {
    ffi_guard(DiErrorCode::InternalError, || {
        if json_data.is_null() {
            set_last_error("JSON data is null");
            return DiErrorCode::InvalidArgument;
        }

        // SAFETY: Caller guarantees json_data is valid
        let json_str = match unsafe { CStr::from_ptr(json_data) }.to_str() {
            Ok(s) => s,
            Err(_) => {
                set_last_error("JSON data is not valid UTF-8");
                return DiErrorCode::InvalidArgument;
            }
        };

        let json_bytes = json_str.as_bytes();

        // SAFETY: We just validated all pointers
        unsafe {
            di_register_singleton(container, type_name, json_bytes.as_ptr(), json_bytes.len())
        }
    })
}

// ============================================================================
// Service Removal and Locking
// ============================================================================

/// Remove a registered service by type name.
///
/// Matching the core container's semantics, removal is permitted on a locked
/// container: locking prevents new registrations only.
///
/// # Returns
/// `Ok` if the service was removed, `NotFound` if no service with that name
/// is registered (with the last error set), or `InvalidArgument` for a null
/// container, null type name, or a type name that is not valid UTF-8.
///
/// # Safety
/// - `container` must be a valid pointer to a `DiContainer`
/// - `type_name` must be a valid null-terminated C string
#[unsafe(no_mangle)]
pub unsafe extern "C" fn di_remove(
    container: *mut DiContainer,
    type_name: *const c_char,
) -> DiErrorCode {
    ffi_guard(DiErrorCode::InternalError, || {
        // Validate container
        if container.is_null() {
            set_last_error("Container pointer is null");
            return DiErrorCode::InvalidArgument;
        }

        // Validate type_name
        if type_name.is_null() {
            set_last_error("Type name is null");
            return DiErrorCode::InvalidArgument;
        }

        // SAFETY: Caller guarantees type_name is valid
        let type_name_str = match unsafe { CStr::from_ptr(type_name) }.to_str() {
            Ok(s) => s,
            Err(_) => {
                set_last_error("Type name is not valid UTF-8");
                return DiErrorCode::InvalidArgument;
            }
        };

        // SAFETY: Caller guarantees container is valid
        let container = unsafe { &*container };

        let removed = container
            .services
            .write()
            .unwrap_or_else(PoisonError::into_inner)
            .remove(type_name_str);
        if removed.is_some() {
            DiErrorCode::Ok
        } else {
            set_last_error(format!("Service '{type_name_str}' not found"));
            DiErrorCode::NotFound
        }
    })
}

/// Remove all registered services from a container.
///
/// Matching the core container's semantics, clearing is permitted on a locked
/// container: locking prevents new registrations only.
///
/// # Returns
/// `Ok` on success, or `InvalidArgument` if the container is null.
///
/// # Safety
/// - `container` must be a valid pointer to a `DiContainer`
#[unsafe(no_mangle)]
pub unsafe extern "C" fn di_clear(container: *mut DiContainer) -> DiErrorCode {
    ffi_guard(DiErrorCode::InternalError, || {
        if container.is_null() {
            set_last_error("Container pointer is null");
            return DiErrorCode::InvalidArgument;
        }

        // SAFETY: Caller guarantees container is valid
        let container = unsafe { &*container };
        container
            .services
            .write()
            .unwrap_or_else(PoisonError::into_inner)
            .clear();
        DiErrorCode::Ok
    })
}

/// Lock a container to prevent further registrations.
///
/// Once locked, `di_register_singleton()` and `di_register_singleton_json()`
/// return `Locked`. Removal (`di_remove()`) and clearing (`di_clear()`)
/// remain permitted, matching the core container's semantics. There is no
/// unlock. Child scopes created with `di_container_scope()` start unlocked.
///
/// The lock is a total barrier: the state change is published while holding
/// the container's write lock, which registration also takes before reading
/// the state, so once this function returns no concurrent registration can
/// still land.
///
/// A null container is recorded as an error (see `di_error_message()`) and
/// otherwise ignored.
///
/// # Safety
/// - `container` must be a valid pointer to a `DiContainer`
#[unsafe(no_mangle)]
pub unsafe extern "C" fn di_lock(container: *mut DiContainer) {
    ffi_guard((), || {
        if container.is_null() {
            set_last_error("Container pointer is null");
            return;
        }

        // SAFETY: Caller guarantees container is valid
        let container = unsafe { &*container };

        // Hold the services write guard across the store so the barrier is
        // total. `di_register_singleton()` reads `locked` while holding this
        // same guard, so a registration either observed the container as
        // unlocked and already completed before this guard was acquired, or it
        // observes `true` and is refused - none can slip in behind us.
        let guard = container
            .services
            .write()
            .unwrap_or_else(PoisonError::into_inner);
        container.locked.store(true, Ordering::Release);
        drop(guard);
    });
}

/// Check whether a container is locked.
///
/// # Returns
/// 1 if the container is locked, 0 if it is not, -1 on error.
///
/// # Safety
/// - `container` must be a valid pointer to a `DiContainer`
#[unsafe(no_mangle)]
pub unsafe extern "C" fn di_is_locked(container: *const DiContainer) -> i32 {
    ffi_guard(-1, || {
        if container.is_null() {
            return -1;
        }

        // SAFETY: Caller guarantees container is valid
        i32::from(unsafe { &*container }.locked.load(Ordering::Acquire))
    })
}

// ============================================================================
// Service Resolution
// ============================================================================

/// Resolve a service by type name.
///
/// # Arguments
/// - `container` - The container to resolve from
/// - `type_name` - The service type name to resolve
///
/// # Returns
/// A DiResult with the service handle on success, or an error code on failure.
///
/// # Safety
/// - `container` must be a valid container pointer
/// - `type_name` must be a valid null-terminated UTF-8 string
/// - On success, the returned service must be freed with `di_service_free()`
#[unsafe(no_mangle)]
pub unsafe extern "C" fn di_resolve(
    container: *mut DiContainer,
    type_name: *const c_char,
) -> DiResult {
    let internal_error = DiResult {
        code: DiErrorCode::InternalError,
        service: ptr::null_mut(),
    };
    ffi_guard(internal_error, || {
        // Validate container
        if container.is_null() {
            set_last_error("Container pointer is null");
            return DiResult {
                code: DiErrorCode::InvalidArgument,
                service: ptr::null_mut(),
            };
        }

        // Validate type_name
        if type_name.is_null() {
            set_last_error("Type name is null");
            return DiResult {
                code: DiErrorCode::InvalidArgument,
                service: ptr::null_mut(),
            };
        }

        // SAFETY: Caller guarantees type_name is valid
        let type_name_str = match unsafe { CStr::from_ptr(type_name) }.to_str() {
            Ok(s) => s.to_string(),
            Err(_) => {
                set_last_error("Type name is not valid UTF-8");
                return DiResult {
                    code: DiErrorCode::InvalidArgument,
                    service: ptr::null_mut(),
                };
            }
        };

        // SAFETY: Caller guarantees container is valid
        let container = unsafe { &*container };

        // Look up the service
        let services = container
            .services
            .read()
            .unwrap_or_else(PoisonError::into_inner);
        match services.get(&type_name_str) {
            Some(service_arc) => {
                // Downcast to Vec<u8>
                if let Some(data) = service_arc.downcast_ref::<Vec<u8>>() {
                    let service = Box::new(DiService {
                        type_name: type_name_str,
                        data: data.clone(),
                    });
                    DiResult {
                        code: DiErrorCode::Ok,
                        service: Box::into_raw(service),
                    }
                } else {
                    set_last_error("Internal error: service data type mismatch");
                    DiResult {
                        code: DiErrorCode::InternalError,
                        service: ptr::null_mut(),
                    }
                }
            }
            None => {
                set_last_error(format!("Service '{}' not found", type_name_str));
                DiResult {
                    code: DiErrorCode::NotFound,
                    service: ptr::null_mut(),
                }
            }
        }
    })
}

/// Resolve a service and return its data as a JSON string.
///
/// This is a convenience function for languages that use JSON serialization.
///
/// # Arguments
/// - `container` - The container to resolve from
/// - `type_name` - The service type name to resolve
///
/// # Returns
/// A pointer to the null-terminated JSON string, or NULL on any failure
/// (service not found, invalid arguments, non-UTF-8 service data, data
/// containing null bytes, or an internal error). Call `di_error_message()`
/// to distinguish causes. The pointer must be freed with `di_string_free()`.
///
/// # Safety
/// - `container` must be a valid container pointer
/// - `type_name` must be a valid null-terminated UTF-8 string
#[unsafe(no_mangle)]
pub unsafe extern "C" fn di_resolve_json(
    container: *mut DiContainer,
    type_name: *const c_char,
) -> *mut c_char {
    ffi_guard(ptr::null_mut(), || {
        // Validate container
        if container.is_null() {
            set_last_error("Container pointer is null");
            return ptr::null_mut();
        }

        // Validate type_name
        if type_name.is_null() {
            set_last_error("Type name is null");
            return ptr::null_mut();
        }

        // SAFETY: Caller guarantees type_name is valid
        let type_name_str = match unsafe { CStr::from_ptr(type_name) }.to_str() {
            Ok(s) => s.to_string(),
            Err(_) => {
                set_last_error("Type name is not valid UTF-8");
                return ptr::null_mut();
            }
        };

        // SAFETY: Caller guarantees container is valid
        let container = unsafe { &*container };

        // Look up the service
        let services = container
            .services
            .read()
            .unwrap_or_else(PoisonError::into_inner);
        match services.get(&type_name_str) {
            Some(service_arc) => {
                // Downcast to Vec<u8>
                if let Some(data) = service_arc.downcast_ref::<Vec<u8>>() {
                    // Convert bytes to string (assuming UTF-8 JSON)
                    match std::str::from_utf8(data) {
                        Ok(json_str) => match CString::new(json_str) {
                            Ok(cstr) => cstr.into_raw(),
                            Err(_) => {
                                set_last_error("JSON string contains null bytes");
                                ptr::null_mut()
                            }
                        },
                        Err(_) => {
                            set_last_error("Service data is not valid UTF-8");
                            ptr::null_mut()
                        }
                    }
                } else {
                    set_last_error("Internal error: service data type mismatch");
                    ptr::null_mut()
                }
            }
            None => {
                set_last_error(format!("Service '{}' not found", type_name_str));
                ptr::null_mut()
            }
        }
    })
}

/// Check if a service is registered.
///
/// # Returns
/// 1 if the service is registered, 0 if not, -1 on error.
///
/// # Safety
/// - `container` must be a valid pointer to a `DiContainer`
/// - `type_name` must be a valid null-terminated C string
#[unsafe(no_mangle)]
pub unsafe extern "C" fn di_contains(container: *mut DiContainer, type_name: *const c_char) -> i32 {
    ffi_guard(-1, || {
        if container.is_null() || type_name.is_null() {
            return -1;
        }

        // SAFETY: Caller guarantees type_name is valid
        let type_name_str = match unsafe { CStr::from_ptr(type_name) }.to_str() {
            Ok(s) => s,
            Err(_) => return -1,
        };

        // SAFETY: Caller guarantees container is valid
        let container = unsafe { &*container };
        let services = container
            .services
            .read()
            .unwrap_or_else(PoisonError::into_inner);

        if services.contains_key(type_name_str) {
            1
        } else {
            0
        }
    })
}

// ============================================================================
// Service Data Access
// ============================================================================

/// Get the data pointer from a service handle.
///
/// # Returns
/// Pointer to the service data, or NULL on error.
/// The pointer is valid until the service is freed.
///
/// # Safety
/// - `service` must be a valid pointer to a `DiService` returned from `di_resolve`
#[unsafe(no_mangle)]
pub unsafe extern "C" fn di_service_data(service: *const DiService) -> *const u8 {
    ffi_guard(ptr::null(), || {
        if service.is_null() {
            return ptr::null();
        }
        // SAFETY: Caller guarantees service is valid
        unsafe { &*service }.data.as_ptr()
    })
}

/// Get the data length from a service handle.
///
/// # Returns
/// Length of the service data in bytes, or 0 on error.
///
/// # Safety
/// - `service` must be a valid pointer to a `DiService` returned from `di_resolve`
#[unsafe(no_mangle)]
pub unsafe extern "C" fn di_service_data_len(service: *const DiService) -> usize {
    ffi_guard(0, || {
        if service.is_null() {
            return 0;
        }
        // SAFETY: Caller guarantees service is valid
        unsafe { &*service }.data.len()
    })
}

/// Get the type name from a service handle.
///
/// # Returns
/// Pointer to the null-terminated type name, or NULL on error.
/// The returned string is a fresh allocation owned by the caller and must be
/// freed with `di_string_free()`.
///
/// # Safety
/// - `service` must be a valid pointer to a `DiService` returned from `di_resolve`
#[unsafe(no_mangle)]
pub unsafe extern "C" fn di_service_type_name(service: *const DiService) -> *const c_char {
    ffi_guard(ptr::null(), || {
        if service.is_null() {
            return ptr::null();
        }
        // SAFETY: Caller guarantees service is valid
        let service = unsafe { &*service };

        // Create a CString and leak it - caller must free with di_string_free
        match CString::new(service.type_name.clone()) {
            Ok(cstr) => cstr.into_raw(),
            Err(_) => ptr::null(),
        }
    })
}

/// Free a service handle.
///
/// # Safety
/// - `service` must be a valid pointer returned by `di_resolve()`
/// - After calling this function, the pointer is invalid
#[unsafe(no_mangle)]
pub unsafe extern "C" fn di_service_free(service: *mut DiService) {
    ffi_guard((), || {
        if !service.is_null() {
            // SAFETY: Caller guarantees service is valid
            drop(unsafe { Box::from_raw(service) });
        }
    });
}

// ============================================================================
// Error Handling
// ============================================================================

/// Get the last error message.
///
/// # Returns
/// A pointer to the null-terminated error message, or NULL if no error.
/// The pointer must be freed with `di_string_free()`.
#[unsafe(no_mangle)]
pub extern "C" fn di_error_message() -> *mut c_char {
    ffi_guard(ptr::null_mut(), || {
        LAST_ERROR.with(|e| {
            let error = e.borrow();
            match &*error {
                Some(msg) => match CString::new(msg.as_str()) {
                    Ok(cstr) => cstr.into_raw(),
                    Err(_) => ptr::null_mut(),
                },
                None => ptr::null_mut(),
            }
        })
    })
}

/// Clear the last error message.
#[unsafe(no_mangle)]
pub extern "C" fn di_error_clear() {
    ffi_guard((), || {
        LAST_ERROR.with(|e| {
            *e.borrow_mut() = None;
        });
    });
}

/// Free a string returned by the library.
///
/// # Safety
/// - `s` must be a string returned by this library (e.g., from `di_error_message()`)
/// - After calling this function, the pointer is invalid
#[unsafe(no_mangle)]
pub unsafe extern "C" fn di_string_free(s: *mut c_char) {
    ffi_guard((), || {
        if !s.is_null() {
            // SAFETY: Caller guarantees s was allocated by CString::into_raw
            drop(unsafe { CString::from_raw(s) });
        }
    });
}

// ============================================================================
// Utility Functions
// ============================================================================

/// Get the library version.
///
/// # Returns
/// A pointer to the null-terminated version string.
/// This string is statically allocated and must NOT be freed.
#[unsafe(no_mangle)]
pub extern "C" fn di_version() -> *const c_char {
    ffi_guard(ptr::null(), || {
        static VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes();
        VERSION.as_ptr() as *const c_char
    })
}

/// Get the number of registered services in a container.
///
/// # Returns
/// The number of services, or -1 on error.
///
/// # Safety
/// - `container` must be a valid pointer to a `DiContainer`
#[unsafe(no_mangle)]
pub unsafe extern "C" fn di_service_count(container: *const DiContainer) -> i64 {
    ffi_guard(-1, || {
        if container.is_null() {
            return -1;
        }
        // SAFETY: Caller guarantees container is valid
        let container = unsafe { &*container };
        let services = container
            .services
            .read()
            .unwrap_or_else(PoisonError::into_inner);
        services.len() as i64
    })
}

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

    /// Run `f` against a fresh container, always freeing it afterwards.
    fn with_container(f: impl FnOnce(*mut DiContainer)) {
        let container = di_container_new();
        assert!(!container.is_null());
        f(container);
        // SAFETY: `container` came from `di_container_new` and is freed
        // exactly once, after `f` has finished using it.
        unsafe { di_container_free(container) };
    }

    /// Fetch the last error message as an owned `String`, asserting one is
    /// present and freeing the FFI allocation per the ABI contract.
    fn last_error_string() -> String {
        let error = di_error_message();
        assert!(!error.is_null(), "expected a last error message");
        // SAFETY: `error` is a valid, non-null string allocated by
        // `di_error_message`; it is freed exactly once below.
        let message = unsafe { CStr::from_ptr(error) }
            .to_str()
            .unwrap()
            .to_owned();
        // SAFETY: `error` came from `di_error_message` and is freed once.
        unsafe { di_string_free(error) };
        message
    }

    /// Run `f` with the panic hook silenced, then restore the previous hook.
    ///
    /// The tests below panic on purpose; without this the default hook prints
    /// the panic and (CI sets `RUST_BACKTRACE=1`) a backtrace on every green
    /// run. The hook is process-global, so `f` must be kept to just the
    /// deliberate panic - assertions belong outside the window.
    fn with_silent_panic_hook<T>(f: impl FnOnce() -> T) -> T {
        let previous = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {}));
        let result = f();
        std::panic::set_hook(previous);
        result
    }

    #[test]
    fn test_ffi_guard_catches_str_panic() {
        di_error_clear();
        let code = with_silent_panic_hook(panicking_entry_str);
        assert_eq!(code, DiErrorCode::InternalError);
        let msg = last_error_string();
        assert!(msg.contains("internal panic"), "got: {msg}");
        assert!(msg.contains("boom"), "got: {msg}");
    }

    #[test]
    fn test_ffi_guard_catches_string_panic() {
        di_error_clear();
        let code = with_silent_panic_hook(panicking_entry_string);
        assert_eq!(code, DiErrorCode::InternalError);
        let msg = last_error_string();
        assert!(msg.contains("internal panic"), "got: {msg}");
        assert!(msg.contains("boom-string"), "got: {msg}");
    }

    /// Every exported entry point must route through [`ffi_guard`]: a panic
    /// that escapes one would unwind across the ABI boundary, which is
    /// undefined behaviour. The `#[cfg(test)]` panic helpers call `ffi_guard`
    /// explicitly, so they pin the guard's own behaviour but not its use -
    /// deleting the wrapper from a real entry point would otherwise fail no
    /// test. Close that gap by scanning this module's own source.
    ///
    /// Parsing heuristic, matched to this file's actual layout (which rustfmt
    /// keeps stable): an entry point begins on the line carrying the C ABI
    /// marker and ends at the next line that is exactly a closing brace at
    /// column zero, which rustfmt guarantees for top-level items and never
    /// produces inside one. A multi-line signature is covered automatically
    /// because the scanned span simply runs on to that brace. Entry points
    /// preceded by a `#[cfg(test)]` attribute are skipped as non-ABI.
    #[test]
    fn test_every_entry_point_routes_through_ffi_guard() {
        // Number of exported entry points at the time of writing; a lower
        // bound, so adding one does not fail here - it gets scanned instead.
        const KNOWN_ENTRY_POINTS: usize = 21;
        let source = include_str!("ffi.rs");
        let lines: Vec<&str> = source.lines().collect();
        let marker = concat!("extern ", '"', "C", '"', " fn ");
        let mut scanned = 0_usize;

        for (start, line) in lines.iter().enumerate() {
            let Some(after_marker) = line.split(marker).nth(1) else {
                continue;
            };
            // Attributes and doc comments sit directly above the signature.
            let is_test_only = lines[..start]
                .iter()
                .rev()
                .take_while(|l| l.starts_with('#') || l.starts_with("//"))
                .any(|l| l.contains("#[cfg(test)]"));
            if is_test_only {
                continue;
            }

            let name = after_marker.split(['(', '<', ' ']).next().unwrap_or("?");
            let Some(offset) = lines[start + 1..].iter().position(|l| *l == "}") else {
                panic!("{name}: no closing brace at column zero - heuristic broke");
            };
            let body = lines[start..=start + 1 + offset].join("\n");

            assert!(
                body.contains("ffi_guard("),
                "{name} does not route through ffi_guard; a panic inside it \
                 would unwind across the FFI boundary"
            );
            scanned += 1;
        }

        assert!(
            scanned >= KNOWN_ENTRY_POINTS,
            "only {scanned} entry points scanned (expected at least \
             {KNOWN_ENTRY_POINTS}) - the source heuristic has drifted"
        );
    }

    #[test]
    fn test_poisoned_lock_stays_usable() {
        // Every lock site recovers via `PoisonError::into_inner`. A regression
        // to `.unwrap()` at any of them would brick the container after one
        // caught panic, so poison the lock for real and drive the ABI.
        struct SendPtr(*mut DiContainer);
        // SAFETY: DiContainer's internals are RwLock/atomic-protected and all
        // FFI functions are documented as thread-safe.
        unsafe impl Send for SendPtr {}
        unsafe impl Sync for SendPtr {}

        let container = std::sync::Arc::new(SendPtr(di_container_new()));
        assert!(!container.0.is_null());

        let joined = {
            let container = std::sync::Arc::clone(&container);
            with_silent_panic_hook(move || {
                std::thread::spawn(move || {
                    // SAFETY: the container outlives this thread - it is only
                    // freed after the join below.
                    let _guard = unsafe { &*container.0 }.services.write().unwrap();
                    panic!("deliberate panic while holding the write guard");
                })
                .join()
            })
        };
        assert!(joined.is_err(), "the poisoning thread must have panicked");

        // SAFETY: `container.0` came from `di_container_new` above.
        let poisoned = unsafe { &*container.0 }.services.is_poisoned();
        assert!(poisoned, "the services lock must now be poisoned");

        let name = CString::new("Poisoned").unwrap();
        let data = b"data";
        // SAFETY: the container and `name` are live for this whole block; the
        // service handle, JSON string, child scope, and container are each
        // freed exactly once. Every entry point that touches the poisoned lock
        // is driven here, so a `.unwrap()` regression at any lock site fails.
        unsafe {
            assert_eq!(
                di_register_singleton(container.0, name.as_ptr(), data.as_ptr(), data.len()),
                DiErrorCode::Ok,
                "registration must recover from lock poisoning"
            );
            assert_eq!(di_contains(container.0, name.as_ptr()), 1);
            assert_eq!(di_service_count(container.0), 1);

            let resolved = di_resolve(container.0, name.as_ptr());
            assert_eq!(resolved.code, DiErrorCode::Ok);
            di_service_free(resolved.service);

            let json = di_resolve_json(container.0, name.as_ptr());
            assert!(!json.is_null(), "JSON resolve must recover from poisoning");
            di_string_free(json);

            let child = di_container_scope(container.0);
            assert!(!child.is_null(), "scoping must recover from poisoning");
            assert_eq!(di_contains(child, name.as_ptr()), 1);
            di_container_free(child);

            // di_lock also takes the (poisoned) write guard - see its total
            // barrier note - and locking still permits removal and clearing.
            di_lock(container.0);
            assert_eq!(di_is_locked(container.0), 1);
            assert_eq!(di_remove(container.0, name.as_ptr()), DiErrorCode::Ok);
            assert_eq!(di_clear(container.0), DiErrorCode::Ok);
            assert_eq!(di_service_count(container.0), 0);
            di_container_free(container.0);
        }
    }

    #[test]
    fn test_container_lifecycle() {
        unsafe {
            let container = di_container_new();
            assert!(!container.is_null());
            di_container_free(container);
        }
    }

    #[test]
    fn test_register_and_resolve() {
        with_container(|container| unsafe {
            let type_name = CString::new("TestService").unwrap();
            let data = b"hello world";

            let result =
                di_register_singleton(container, type_name.as_ptr(), data.as_ptr(), data.len());
            assert_eq!(result, DiErrorCode::Ok);

            let resolve_result = di_resolve(container, type_name.as_ptr());
            assert_eq!(resolve_result.code, DiErrorCode::Ok);
            assert!(!resolve_result.service.is_null());

            let service = resolve_result.service;
            assert_eq!(di_service_data_len(service), 11);

            let data_ptr = di_service_data(service);
            let resolved_data = std::slice::from_raw_parts(data_ptr, 11);
            assert_eq!(resolved_data, b"hello world");

            di_service_free(service);
        });
    }

    #[test]
    fn test_not_found() {
        with_container(|container| unsafe {
            let type_name = CString::new("NonExistent").unwrap();

            let result = di_resolve(container, type_name.as_ptr());
            assert_eq!(result.code, DiErrorCode::NotFound);
            assert!(result.service.is_null());
        });
    }

    #[test]
    fn test_contains() {
        with_container(|container| unsafe {
            let type_name = CString::new("TestService").unwrap();

            assert_eq!(di_contains(container, type_name.as_ptr()), 0);

            let data = b"test";
            di_register_singleton(container, type_name.as_ptr(), data.as_ptr(), data.len());

            assert_eq!(di_contains(container, type_name.as_ptr()), 1);
        });
    }

    #[test]
    fn test_scope() {
        unsafe {
            let parent = di_container_new();
            let type_name = CString::new("ParentService").unwrap();
            let data = b"parent";

            di_register_singleton(parent, type_name.as_ptr(), data.as_ptr(), data.len());

            let child = di_container_scope(parent);
            assert!(!child.is_null());

            // Child should inherit parent's services
            assert_eq!(di_contains(child, type_name.as_ptr()), 1);

            di_container_free(child);
            di_container_free(parent);
        }
    }

    #[test]
    fn test_duplicate_registration() {
        with_container(|container| unsafe {
            let type_name = CString::new("Duplicate").unwrap();
            let data = b"data";

            let first =
                di_register_singleton(container, type_name.as_ptr(), data.as_ptr(), data.len());
            assert_eq!(first, DiErrorCode::Ok);

            let second =
                di_register_singleton(container, type_name.as_ptr(), data.as_ptr(), data.len());
            assert_eq!(second, DiErrorCode::AlreadyRegistered);
        });
    }

    #[test]
    fn test_concurrent_duplicate_registration() {
        // Regression test for the check-then-insert TOCTOU: registration is
        // atomic under a single write lock, so of N threads racing to
        // register the same name, exactly one must win per round.
        struct SendPtr(*mut DiContainer);
        // SAFETY: DiContainer's internals are RwLock-protected and all FFI
        // functions are documented as thread-safe.
        unsafe impl Send for SendPtr {}
        unsafe impl Sync for SendPtr {}

        const THREADS: usize = 8;
        const ROUNDS: usize = 100;

        let container = SendPtr(di_container_new());
        let container = std::sync::Arc::new(container);

        for round in 0..ROUNDS {
            let barrier = std::sync::Arc::new(std::sync::Barrier::new(THREADS));
            let name = std::sync::Arc::new(CString::new(format!("Svc{round}")).unwrap());

            let handles: Vec<_> = (0..THREADS)
                .map(|_| {
                    let container = std::sync::Arc::clone(&container);
                    let barrier = std::sync::Arc::clone(&barrier);
                    let name = std::sync::Arc::clone(&name);
                    std::thread::spawn(move || {
                        let data = b"race";
                        barrier.wait();
                        unsafe {
                            di_register_singleton(
                                container.0,
                                name.as_ptr(),
                                data.as_ptr(),
                                data.len(),
                            )
                        }
                    })
                })
                .collect();

            let results: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();
            let ok = results.iter().filter(|r| **r == DiErrorCode::Ok).count();
            let dup = results
                .iter()
                .filter(|r| **r == DiErrorCode::AlreadyRegistered)
                .count();
            assert_eq!(ok, 1, "round {round}: exactly one registration must win");
            assert_eq!(
                dup,
                THREADS - 1,
                "round {round}: the rest must see AlreadyRegistered"
            );
        }

        unsafe { di_container_free(container.0) };
    }

    #[test]
    fn test_concurrent_lock_vs_registration() {
        // di_lock racing di_register_singleton: every registration attempt
        // must resolve cleanly to Ok (beat the lock) or Locked (lost to it),
        // and once the lock has landed it must refuse all later attempts.
        // Crucially, the reported outcome must match the container's contents
        // - an Ok whose write was dropped, or a Locked whose write landed
        // anyway, is exactly the corruption a status-only assertion misses.
        struct SendPtr(*mut DiContainer);
        // SAFETY: DiContainer's internals are RwLock/atomic-protected and all
        // FFI functions are documented as thread-safe.
        unsafe impl Send for SendPtr {}
        unsafe impl Sync for SendPtr {}

        const THREADS: usize = 8;

        let container = std::sync::Arc::new(SendPtr(di_container_new()));
        let barrier = std::sync::Arc::new(std::sync::Barrier::new(THREADS + 1));

        let locker = {
            let container = std::sync::Arc::clone(&container);
            let barrier = std::sync::Arc::clone(&barrier);
            std::thread::spawn(move || {
                barrier.wait();
                // SAFETY: the container stays alive until every thread below
                // has been joined.
                unsafe { di_lock(container.0) };
            })
        };

        let handles: Vec<_> = (0..THREADS)
            .map(|i| {
                let container = std::sync::Arc::clone(&container);
                let barrier = std::sync::Arc::clone(&barrier);
                std::thread::spawn(move || {
                    let name = CString::new(format!("Racer{i}")).unwrap();
                    let data = b"race";
                    barrier.wait();
                    // SAFETY: the container outlives every racer thread.
                    let code = unsafe {
                        di_register_singleton(container.0, name.as_ptr(), data.as_ptr(), data.len())
                    };
                    (i, code)
                })
            })
            .collect();

        locker.join().unwrap();
        let results: Vec<(usize, DiErrorCode)> =
            handles.into_iter().map(|h| h.join().unwrap()).collect();

        // Invariant: Ok <=> the name is present. Nothing else registers these
        // names, so a Locked racer must leave no trace and an Ok racer must.
        let mut expected_count = 0_i64;
        for (i, code) in &results {
            let name = CString::new(format!("Racer{i}")).unwrap();
            // SAFETY: the container is alive until it is freed below.
            let present = unsafe { di_contains(container.0, name.as_ptr()) };
            match code {
                DiErrorCode::Ok => {
                    expected_count += 1;
                    assert_eq!(present, 1, "Racer{i}: Ok registration was lost");
                }
                DiErrorCode::Locked => {
                    assert_eq!(present, 0, "Racer{i}: Locked registration landed anyway");
                }
                other => panic!("Racer{i}: must be Ok or Locked, got {other:?}"),
            }
        }
        // SAFETY: the container is alive until it is freed below.
        let count = unsafe { di_service_count(container.0) };
        assert_eq!(count, expected_count, "count must match the Ok results");

        unsafe {
            // The lock has landed: every subsequent registration - raced
            // names and fresh ones alike - must now report Locked.
            assert_eq!(di_is_locked(container.0), 1);
            let data = b"race";
            for i in 0..THREADS {
                let name = CString::new(format!("Racer{i}")).unwrap();
                let result =
                    di_register_singleton(container.0, name.as_ptr(), data.as_ptr(), data.len());
                assert_eq!(result, DiErrorCode::Locked);
            }
            let fresh = CString::new("LateRacer").unwrap();
            let result =
                di_register_singleton(container.0, fresh.as_ptr(), data.as_ptr(), data.len());
            assert_eq!(result, DiErrorCode::Locked);
            di_container_free(container.0);
        }
    }

    #[test]
    fn test_json_register_and_resolve() {
        with_container(|container| unsafe {
            let type_name = CString::new("JsonService").unwrap();
            let json = CString::new("{\"name\":\"test\"}").unwrap();

            let result = di_register_singleton_json(container, type_name.as_ptr(), json.as_ptr());
            assert_eq!(result, DiErrorCode::Ok);

            let resolved = di_resolve_json(container, type_name.as_ptr());
            assert!(!resolved.is_null());
            assert_eq!(
                CStr::from_ptr(resolved).to_str().unwrap(),
                "{\"name\":\"test\"}"
            );
            di_string_free(resolved);
        });
    }

    #[test]
    fn test_resolve_json_not_found() {
        with_container(|container| unsafe {
            let type_name = CString::new("Missing").unwrap();

            di_error_clear();
            let resolved = di_resolve_json(container, type_name.as_ptr());
            assert!(resolved.is_null());

            let error = di_error_message();
            assert!(!error.is_null());
            assert!(
                CStr::from_ptr(error)
                    .to_str()
                    .unwrap()
                    .contains("not found")
            );
            di_string_free(error);
        });
    }

    #[test]
    fn test_service_type_name() {
        with_container(|container| unsafe {
            let type_name = CString::new("NamedService").unwrap();
            let data = b"data";

            di_register_singleton(container, type_name.as_ptr(), data.as_ptr(), data.len());

            let result = di_resolve(container, type_name.as_ptr());
            assert_eq!(result.code, DiErrorCode::Ok);

            let name = di_service_type_name(result.service);
            assert!(!name.is_null());
            assert_eq!(CStr::from_ptr(name).to_str().unwrap(), "NamedService");
            di_string_free(name.cast_mut());

            di_service_free(result.service);
        });
    }

    #[test]
    fn test_error_message_set_and_clear() {
        with_container(|container| unsafe {
            let type_name = CString::new("Missing").unwrap();

            let result = di_resolve(container, type_name.as_ptr());
            assert_eq!(result.code, DiErrorCode::NotFound);

            let error = di_error_message();
            assert!(!error.is_null());
            di_string_free(error);

            di_error_clear();
            assert!(di_error_message().is_null());
        });
    }

    #[test]
    fn test_version() {
        unsafe {
            let version = di_version();
            assert!(!version.is_null());
            assert_eq!(
                CStr::from_ptr(version).to_str().unwrap(),
                env!("CARGO_PKG_VERSION")
            );
        }
    }

    #[test]
    fn test_service_count() {
        with_container(|container| unsafe {
            assert_eq!(di_service_count(container), 0);

            let first = CString::new("First").unwrap();
            let second = CString::new("Second").unwrap();
            let data = b"data";

            di_register_singleton(container, first.as_ptr(), data.as_ptr(), data.len());
            assert_eq!(di_service_count(container), 1);

            di_register_singleton(container, second.as_ptr(), data.as_ptr(), data.len());
            assert_eq!(di_service_count(container), 2);
        });
    }

    #[test]
    fn test_remove_round_trip() {
        with_container(|container| unsafe {
            let type_name = CString::new("Removable").unwrap();
            let data = b"data";

            di_register_singleton(container, type_name.as_ptr(), data.as_ptr(), data.len());
            assert_eq!(di_contains(container, type_name.as_ptr()), 1);

            assert_eq!(di_remove(container, type_name.as_ptr()), DiErrorCode::Ok);
            assert_eq!(di_contains(container, type_name.as_ptr()), 0);

            // Removing again must report NotFound, naming the service.
            assert_eq!(
                di_remove(container, type_name.as_ptr()),
                DiErrorCode::NotFound
            );
            let msg = last_error_string();
            assert!(msg.contains("Removable"), "got: {msg}");
        });
    }

    #[test]
    fn test_clear() {
        with_container(|container| unsafe {
            let first = CString::new("First").unwrap();
            let second = CString::new("Second").unwrap();
            let data = b"data";

            di_register_singleton(container, first.as_ptr(), data.as_ptr(), data.len());
            di_register_singleton(container, second.as_ptr(), data.as_ptr(), data.len());
            assert_eq!(di_service_count(container), 2);

            assert_eq!(di_clear(container), DiErrorCode::Ok);
            assert_eq!(di_service_count(container), 0);
        });
    }

    #[test]
    fn test_lock_blocks_registration_but_allows_remove_and_clear() {
        with_container(|container| unsafe {
            let existing = CString::new("Existing").unwrap();
            let blocked = CString::new("Blocked").unwrap();
            let data = b"data";

            di_register_singleton(container, existing.as_ptr(), data.as_ptr(), data.len());

            di_lock(container);

            let result =
                di_register_singleton(container, blocked.as_ptr(), data.as_ptr(), data.len());
            assert_eq!(result, DiErrorCode::Locked);

            // A Locked failure must surface a message mentioning the lock.
            let msg = last_error_string();
            assert!(msg.contains("locked"), "got: {msg}");

            let json = CString::new("{}").unwrap();
            let json_result =
                di_register_singleton_json(container, blocked.as_ptr(), json.as_ptr());
            assert_eq!(json_result, DiErrorCode::Locked);

            // Locking blocks registration only; removal and clearing still work.
            assert_eq!(di_remove(container, existing.as_ptr()), DiErrorCode::Ok);
            assert_eq!(di_clear(container), DiErrorCode::Ok);
        });
    }

    #[test]
    fn test_is_locked_transitions() {
        with_container(|container| unsafe {
            assert_eq!(di_is_locked(container), 0);
            di_lock(container);
            assert_eq!(di_is_locked(container), 1);
        });
    }

    #[test]
    fn test_null_container_sentinels() {
        unsafe {
            // -1 is the documented error sentinel for both query functions;
            // it must stay distinct from the 0 ("false") result.
            assert_eq!(di_is_locked(std::ptr::null_mut()), -1);
            let name = CString::new("Anything").unwrap();
            assert_eq!(di_contains(std::ptr::null_mut(), name.as_ptr()), -1);
        }
    }

    #[test]
    fn test_error_code_from_core_error() {
        assert_eq!(
            DiErrorCode::from(&DiError::not_found::<u32>()),
            DiErrorCode::NotFound
        );
        assert_eq!(
            DiErrorCode::from(&DiError::already_registered::<u32>()),
            DiErrorCode::AlreadyRegistered
        );
        assert_eq!(DiErrorCode::from(&DiError::Locked), DiErrorCode::Locked);
        assert_eq!(
            DiErrorCode::from(&DiError::circular::<u32>()),
            DiErrorCode::InternalError
        );
        assert_eq!(
            DiErrorCode::from(&DiError::Internal(String::from("boom"))),
            DiErrorCode::InternalError
        );
    }
}