fluxdi 1.1.0

FluxDI - Semi-Automatic Dependency Injector
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
//! Instance wrapper for dependency injection values.
//!
//! This module provides the [`Instance`] type, which wraps a [`Shared`] reference
//! to provide convenient access to dependency-injected values. It serves as the
//! primary interface for consuming resolved dependencies.
//!
//! # Core Responsibilities
//!
//! - **Value Access**: Provides ergonomic access to the underlying value via references
//! - **Shared Ownership**: Maintains shared ownership through reference counting
//! - **Type Safety**: Preserves type information including support for trait objects
//!
//! # Design Philosophy
//!
//! The `Instance` type is a thin wrapper around `Shared<T>` that provides a clear
//! semantic distinction between "a resolved dependency" and "a shared reference".
//! This makes the DI container's API more intuitive and self-documenting.
//!
//! # Thread Safety
//!
//! When compiled with the `thread-safe` feature, `Instance<T>` can be safely shared
//! across threads (assuming `T: Send + Sync`). The underlying `Shared` type will be
//! `Arc<T>`, providing atomic reference counting.
//!
//! # Examples
//!
//! Creating and using an instance:
//!
//! ```
//! use fluxdi::{Instance, Shared};
//!
//! struct Config {
//!     debug: bool,
//!     port: u16,
//! }
//!
//! let shared_config = Shared::new(Config { debug: true, port: 8080 });
//! let instance = Instance::new(shared_config);
//!
//! // Access via reference
//! assert_eq!(instance.get().port, 8080);
//!
//! // Get a cloned Shared reference
//! let shared = instance.value();
//! assert_eq!(shared.port, 8080);
//! ```
//!
//! With trait objects:
//!
//! ```
//! use fluxdi::{Instance, Shared};
//!
//! trait Logger {
//!     fn log(&self, message: &str);
//! }
//!
//! struct ConsoleLogger;
//! impl Logger for ConsoleLogger {
//!     fn log(&self, message: &str) {
//!         println!("{}", message);
//!     }
//! }
//!
//! let logger: Shared<dyn Logger> = Shared::new(ConsoleLogger);
//! let instance = Instance::<dyn Logger>::new(logger);
//!
//! instance.get().log("Hello, world!");
//! ```

use crate::Shared;

/// A wrapper around a shared reference to a dependency-injected value.
///
/// `Instance<T>` provides a convenient interface for accessing values resolved
/// by the dependency injection container. It maintains shared ownership of the
/// underlying value through reference counting.
///
/// # Type Parameters
///
/// - `T`: The type of the wrapped value. Can be `?Sized` to support trait objects.
///
/// # Invariants
///
/// - Always contains a valid `Shared<T>` reference
/// - The wrapped value is immutable (interior mutability requires explicit use
///   of `Mutex`, `RwLock`, `RefCell`, etc.)
///
/// # Memory Management
///
/// The instance holds a strong reference to the underlying value. The value will
/// be deallocated when all `Instance` wrappers and `Shared` references are dropped.
///
/// # Examples
///
/// Basic usage with a concrete type:
///
/// ```
/// use fluxdi::{Instance, Shared};
///
/// #[derive(Debug, PartialEq)]
/// struct User {
///     id: u32,
///     name: String,
/// }
///
/// let user = Shared::new(User {
///     id: 1,
///     name: "Alice".to_string(),
/// });
///
/// let instance = Instance::new(user);
/// assert_eq!(instance.get().id, 1);
/// assert_eq!(instance.get().name, "Alice");
/// ```
///
/// Multiple instances sharing the same value:
///
/// ```
/// use fluxdi::{Instance, Shared};
///
/// let shared = Shared::new(vec![1, 2, 3]);
/// let instance1 = Instance::new(shared.clone());
/// let instance2 = Instance::new(shared.clone());
///
/// // Both instances point to the same allocation
/// assert!(Shared::ptr_eq(&instance1.value(), &instance2.value()));
/// ```
#[derive(Clone)]
#[cfg_attr(feature = "debug", derive(Debug))]
pub struct Instance<T: ?Sized + 'static> {
    /// The shared reference to the actual value
    value: Shared<T>,
}

impl<T: ?Sized + 'static> Instance<T> {
    /// Creates a new `Instance` wrapping the given shared value.
    ///
    /// This is typically called by the dependency injection container after
    /// resolving a dependency, but can also be used directly for testing or
    /// manual dependency management.
    ///
    /// # Arguments
    ///
    /// * `value` - A `Shared<T>` reference to wrap
    ///
    /// # Examples
    ///
    /// Creating an instance with a concrete type:
    ///
    /// ```
    /// use fluxdi::{Instance, Shared};
    ///
    /// struct Database {
    ///     url: String,
    /// }
    ///
    /// let db = Shared::new(Database {
    ///     url: "postgresql://localhost".to_string(),
    /// });
    ///
    /// let instance = Instance::new(db);
    /// ```
    ///
    /// Creating an instance with a trait object:
    ///
    /// ```
    /// use fluxdi::{Instance, Shared};
    ///
    /// trait Repository {}
    /// struct UserRepository;
    /// impl Repository for UserRepository {}
    ///
    /// let repo: Shared<dyn Repository> = Shared::new(UserRepository);
    /// let instance = Instance::<dyn Repository>::new(repo);
    /// ```
    pub fn new(value: Shared<T>) -> Self {
        Self { value }
    }

    /// Returns a reference to the wrapped value.
    ///
    /// This provides direct, immutable access to the underlying value without
    /// requiring an additional clone of the `Shared` wrapper. The reference
    /// is valid for as long as the `Instance` exists.
    ///
    /// # Returns
    ///
    /// An immutable reference to the wrapped value of type `&T`.
    ///
    /// # Performance
    ///
    /// This is a zero-cost operation that simply dereferences the `Shared`
    /// pointer. No cloning or additional allocations occur.
    ///
    /// # Examples
    ///
    /// Accessing fields:
    ///
    /// ```
    /// use fluxdi::{Instance, Shared};
    ///
    /// struct Config {
    ///     debug: bool,
    ///     timeout_ms: u64,
    /// }
    ///
    /// let instance = Instance::new(Shared::new(Config {
    ///     debug: true,
    ///     timeout_ms: 5000,
    /// }));
    ///
    /// assert!(instance.get().debug);
    /// assert_eq!(instance.get().timeout_ms, 5000);
    /// ```
    ///
    /// Calling methods:
    ///
    /// ```
    /// use fluxdi::{Instance, Shared};
    ///
    /// struct Calculator {
    ///     base: i32,
    /// }
    ///
    /// impl Calculator {
    ///     fn add(&self, x: i32) -> i32 {
    ///         self.base + x
    ///     }
    /// }
    ///
    /// let instance = Instance::new(Shared::new(Calculator { base: 10 }));
    /// assert_eq!(instance.get().add(5), 15);
    /// ```
    ///
    /// Using with trait objects:
    ///
    /// ```
    /// use fluxdi::{Instance, Shared};
    ///
    /// trait Greeter {
    ///     fn greet(&self) -> String;
    /// }
    ///
    /// struct EnglishGreeter;
    /// impl Greeter for EnglishGreeter {
    ///     fn greet(&self) -> String {
    ///         "Hello!".to_string()
    ///     }
    /// }
    ///
    /// let greeter: Shared<dyn Greeter> = Shared::new(EnglishGreeter);
    /// let instance = Instance::<dyn Greeter>::new(greeter);
    ///
    /// assert_eq!(instance.get().greet(), "Hello!");
    /// ```
    pub fn get(&self) -> &T {
        &self.value
    }

    /// Returns a clone of the underlying `Shared<T>` reference.
    ///
    /// This creates a new strong reference to the same underlying value,
    /// incrementing the reference count. The cloned `Shared` can be stored,
    /// passed to other functions, or used to create additional `Instance`
    /// wrappers.
    ///
    /// # Returns
    ///
    /// A `Shared<T>` that points to the same allocation as this instance.
    ///
    /// # Performance
    ///
    /// This operation performs a reference count increment, which is:
    /// - Atomic (when using `thread-safe` feature with `Arc`)
    /// - Non-atomic but very fast (when using `Rc` without `thread-safe`)
    ///
    /// No deep cloning of the actual value occurs.
    ///
    /// # Use Cases
    ///
    /// - **Sharing dependencies**: Pass the value to multiple components
    /// - **Storing references**: Keep a reference in a struct or collection
    /// - **Background tasks**: Send the value to async tasks or threads (with `thread-safe`)
    /// - **Testing**: Create test instances that share the same mock
    ///
    /// # Examples
    ///
    /// Storing multiple references:
    ///
    /// ```
    /// use fluxdi::{Instance, Shared};
    ///
    /// struct Config {
    ///     max_connections: u32,
    /// }
    ///
    /// let instance = Instance::new(Shared::new(Config { max_connections: 100 }));
    ///
    /// let shared1 = instance.value();
    /// let shared2 = instance.value();
    ///
    /// // All point to the same allocation
    /// assert!(Shared::ptr_eq(&shared1, &shared2));
    /// assert!(Shared::ptr_eq(&shared1, &instance.value()));
    /// ```
    ///
    /// Passing to multiple services:
    ///
    /// ```
    /// use fluxdi::{Instance, Shared};
    ///
    /// struct Database {
    ///     url: String,
    /// }
    ///
    /// struct UserService {
    ///     db: Shared<Database>,
    /// }
    ///
    /// struct OrderService {
    ///     db: Shared<Database>,
    /// }
    ///
    /// let db_instance = Instance::new(Shared::new(Database {
    ///     url: "postgresql://localhost".to_string(),
    /// }));
    ///
    /// let user_service = UserService {
    ///     db: db_instance.value(),
    /// };
    ///
    /// let order_service = OrderService {
    ///     db: db_instance.value(),
    /// };
    ///
    /// // Both services share the same database connection
    /// assert!(Shared::ptr_eq(&user_service.db, &order_service.db));
    /// ```
    ///
    /// # Thread Safety
    ///
    /// When the `thread-safe` feature is enabled, the returned `Shared<T>`
    /// (which is `Arc<T>`) can be safely sent to other threads:
    ///
    /// ```no_run
    /// # #[cfg(feature = "thread-safe")]
    /// # {
    /// use fluxdi::{Instance, Shared};
    /// use std::thread;
    ///
    /// struct Counter {
    ///     value: std::sync::atomic::AtomicU32,
    /// }
    ///
    /// let instance = Instance::new(Shared::new(Counter {
    ///     value: std::sync::atomic::AtomicU32::new(0),
    /// }));
    ///
    /// let shared = instance.value();
    /// let handle = thread::spawn(move || {
    ///     shared.value.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
    /// });
    ///
    /// handle.join().unwrap();
    /// # }
    /// ```
    pub fn value(&self) -> Shared<T> {
        self.value.clone()
    }
}

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

    #[derive(Debug, Clone, PartialEq, Eq)]
    struct TestData {
        id: u32,
        name: String,
    }

    #[derive(Debug, PartialEq)]
    struct Counter {
        value: u32,
    }

    trait Service: std::fmt::Debug {
        fn name(&self) -> &str;
        fn execute(&self) -> String;
    }

    #[derive(Debug)]
    struct DatabaseService {
        connection_string: String,
    }

    impl Service for DatabaseService {
        fn name(&self) -> &str {
            "DatabaseService"
        }

        fn execute(&self) -> String {
            format!("Connected to: {}", self.connection_string)
        }
    }

    #[derive(Debug)]
    struct CacheService {
        max_size: usize,
    }

    impl Service for CacheService {
        fn name(&self) -> &str {
            "CacheService"
        }

        fn execute(&self) -> String {
            format!("Cache with max size: {}", self.max_size)
        }
    }

    #[test]
    fn test_instance_new_creates_instance() {
        let data = Shared::new(TestData {
            id: 1,
            name: "test".to_string(),
        });

        let instance = Instance::new(data);

        assert_eq!(instance.get().id, 1);
        assert_eq!(instance.get().name, "test");
    }

    #[test]
    fn test_instance_new_with_primitive() {
        let value = Shared::new(42);
        let instance = Instance::new(value);

        assert_eq!(*instance.get(), 42);
    }

    #[test]
    fn test_instance_new_with_string() {
        let text = Shared::new(String::from("Hello, world!"));
        let instance = Instance::new(text);

        assert_eq!(instance.get().as_str(), "Hello, world!");
    }

    #[test]
    fn test_instance_new_with_vec() {
        let numbers = Shared::new(vec![1, 2, 3, 4, 5]);
        let instance = Instance::new(numbers);

        assert_eq!(instance.get().len(), 5);
        assert_eq!(instance.get()[2], 3);
    }

    #[test]
    fn test_instance_new_with_complex_struct() {
        #[derive(Debug, PartialEq)]
        struct ComplexData {
            values: Vec<i32>,
            metadata: std::collections::HashMap<String, String>,
        }

        let mut map = std::collections::HashMap::new();
        map.insert("key1".to_string(), "value1".to_string());

        let complex = Shared::new(ComplexData {
            values: vec![10, 20, 30],
            metadata: map,
        });

        let instance = Instance::new(complex);

        assert_eq!(instance.get().values.len(), 3);
        assert_eq!(instance.get().metadata.get("key1").unwrap(), "value1");
    }

    #[test]
    fn test_get_returns_reference() {
        let data = Shared::new(TestData {
            id: 42,
            name: "reference-test".to_string(),
        });

        let instance = Instance::new(data);
        let reference = instance.get();

        assert_eq!(reference.id, 42);
        assert_eq!(reference.name, "reference-test");
    }

    #[test]
    fn test_get_multiple_times_returns_same_data() {
        let data = Shared::new(Counter { value: 100 });
        let instance = Instance::new(data);

        let ref1 = instance.get();
        let ref2 = instance.get();

        // Both references point to the same data
        assert_eq!(ref1.value, ref2.value);
        assert_eq!(ref1.value, 100);
    }

    #[test]
    fn test_get_allows_field_access() {
        let data = Shared::new(TestData {
            id: 5,
            name: "field-test".to_string(),
        });

        let instance = Instance::new(data);

        // Direct field access
        assert_eq!(instance.get().id, 5);
        assert_eq!(instance.get().name, "field-test");
    }

    #[test]
    fn test_get_allows_method_calls() {
        #[derive(Debug)]
        struct Calculator {
            base: i32,
        }

        impl Calculator {
            fn add(&self, x: i32) -> i32 {
                self.base + x
            }

            fn multiply(&self, x: i32) -> i32 {
                self.base * x
            }
        }

        let calc = Shared::new(Calculator { base: 10 });
        let instance = Instance::new(calc);

        assert_eq!(instance.get().add(5), 15);
        assert_eq!(instance.get().multiply(3), 30);
    }

    #[test]
    fn test_get_with_nested_access() {
        #[derive(Debug)]
        struct Inner {
            value: String,
        }

        #[derive(Debug)]
        struct Outer {
            inner: Inner,
            count: usize,
        }

        let outer = Shared::new(Outer {
            inner: Inner {
                value: "nested".to_string(),
            },
            count: 5,
        });

        let instance = Instance::new(outer);

        assert_eq!(instance.get().inner.value, "nested");
        assert_eq!(instance.get().count, 5);
    }

    #[test]
    fn test_value_returns_cloned_shared() {
        let data = Shared::new(TestData {
            id: 99,
            name: "clone-test".to_string(),
        });

        let instance = Instance::new(data);
        let shared1 = instance.value();
        let shared2 = instance.value();

        // Both point to the same allocation
        assert!(Shared::ptr_eq(&shared1, &shared2));
    }

    #[test]
    fn test_value_increments_reference_count() {
        let data = Shared::new(TestData {
            id: 1,
            name: "refcount".to_string(),
        });

        let instance = Instance::new(data.clone());

        // Initial count: 2 (data + instance)
        #[cfg(feature = "thread-safe")]
        let initial_count = std::sync::Arc::strong_count(&data);
        #[cfg(not(feature = "thread-safe"))]
        let initial_count = std::rc::Rc::strong_count(&data);

        let _shared1 = instance.value();

        #[cfg(feature = "thread-safe")]
        let after_one = std::sync::Arc::strong_count(&data);
        #[cfg(not(feature = "thread-safe"))]
        let after_one = std::rc::Rc::strong_count(&data);

        assert_eq!(after_one, initial_count + 1);

        let _shared2 = instance.value();

        #[cfg(feature = "thread-safe")]
        let after_two = std::sync::Arc::strong_count(&data);
        #[cfg(not(feature = "thread-safe"))]
        let after_two = std::rc::Rc::strong_count(&data);

        assert_eq!(after_two, initial_count + 2);
    }

    #[test]
    fn test_value_can_be_stored() {
        let data = Shared::new(TestData {
            id: 10,
            name: "storage-test".to_string(),
        });

        let instance = Instance::new(data);

        // Store in a vector
        let storage: Vec<Shared<TestData>> =
            vec![instance.value(), instance.value(), instance.value()];

        // All stored references point to the same data
        assert!(Shared::ptr_eq(&storage[0], &storage[1]));
        assert!(Shared::ptr_eq(&storage[1], &storage[2]));

        // Data is accessible through stored references
        assert_eq!(storage[0].id, 10);
        assert_eq!(storage[2].name, "storage-test");
    }

    #[test]
    fn test_value_enables_sharing_across_components() {
        struct ServiceA {
            data: Shared<TestData>,
        }

        struct ServiceB {
            data: Shared<TestData>,
        }

        let data = Shared::new(TestData {
            id: 50,
            name: "shared".to_string(),
        });

        let instance = Instance::new(data);

        let service_a = ServiceA {
            data: instance.value(),
        };

        let service_b = ServiceB {
            data: instance.value(),
        };

        // Both services share the same data
        assert!(Shared::ptr_eq(&service_a.data, &service_b.data));
        assert_eq!(service_a.data.id, 50);
        assert_eq!(service_b.data.id, 50);
    }

    #[test]
    fn test_instance_with_trait_object() {
        let service: Shared<dyn Service> = Shared::new(DatabaseService {
            connection_string: "postgresql://localhost".to_string(),
        });

        let instance = Instance::<dyn Service>::new(service);

        assert_eq!(instance.get().name(), "DatabaseService");
        assert!(instance.get().execute().contains("postgresql"));
    }

    #[test]
    fn test_instance_trait_object_polymorphism() {
        let db_service: Shared<dyn Service> = Shared::new(DatabaseService {
            connection_string: "postgresql://localhost".to_string(),
        });

        let cache_service: Shared<dyn Service> = Shared::new(CacheService { max_size: 1000 });

        let instance1 = Instance::<dyn Service>::new(db_service);
        let instance2 = Instance::<dyn Service>::new(cache_service);

        assert_eq!(instance1.get().name(), "DatabaseService");
        assert_eq!(instance2.get().name(), "CacheService");
    }

    #[test]
    fn test_trait_object_value_cloning() {
        let service: Shared<dyn Service> = Shared::new(CacheService { max_size: 500 });

        let instance = Instance::<dyn Service>::new(service);

        let shared1 = instance.value();
        let shared2 = instance.value();

        assert!(Shared::ptr_eq(&shared1, &shared2));
        assert_eq!(shared1.name(), "CacheService");
    }

    #[test]
    fn test_instance_with_empty_struct() {
        #[derive(Debug, PartialEq)]
        struct Empty;

        let empty = Shared::new(Empty);
        let instance = Instance::new(empty);

        assert_eq!(*instance.get(), Empty);
    }

    #[test]
    fn test_instance_with_large_struct() {
        #[derive(Debug)]
        struct LargeStruct {
            data: [u8; 1024],
        }

        let large = Shared::new(LargeStruct { data: [42; 1024] });

        let instance = Instance::new(large);

        assert_eq!(instance.get().data[0], 42);
        assert_eq!(instance.get().data[1023], 42);
    }

    #[test]
    fn test_multiple_instances_same_shared() {
        let data = Shared::new(TestData {
            id: 777,
            name: "multi-instance".to_string(),
        });

        let instance1 = Instance::new(data.clone());
        let instance2 = Instance::new(data.clone());
        let instance3 = Instance::new(data.clone());

        // All instances point to the same allocation
        assert!(Shared::ptr_eq(&instance1.value(), &instance2.value()));
        assert!(Shared::ptr_eq(&instance2.value(), &instance3.value()));

        // Data is consistent across all instances
        assert_eq!(instance1.get().id, 777);
        assert_eq!(instance2.get().id, 777);
        assert_eq!(instance3.get().id, 777);
    }

    #[test]
    fn test_instance_outlives_original_shared() {
        let instance = {
            let data = Shared::new(TestData {
                id: 888,
                name: "lifetime-test".to_string(),
            });
            Instance::new(data)
        }; // data is dropped here

        // Instance still holds valid reference
        assert_eq!(instance.get().id, 888);
        assert_eq!(instance.get().name, "lifetime-test");
    }

    #[test]
    fn test_nested_instances() {
        #[derive(Debug)]
        struct Inner {
            value: u32,
        }

        #[derive(Debug)]
        struct Outer {
            inner_instance: Instance<Inner>,
        }

        let inner = Instance::new(Shared::new(Inner { value: 42 }));
        let outer = Instance::new(Shared::new(Outer {
            inner_instance: inner,
        }));

        assert_eq!(outer.get().inner_instance.get().value, 42);
    }

    #[cfg(feature = "debug")]
    #[test]
    fn test_instance_debug_format() {
        let data = Shared::new(TestData {
            id: 1,
            name: "debug-test".to_string(),
        });

        let instance = Instance::new(data);
        let debug_str = format!("{:?}", instance);

        // Should contain Instance in the debug output
        assert!(debug_str.contains("Instance"));
    }

    #[cfg(feature = "thread-safe")]
    #[test]
    fn test_instance_is_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}

        // Instance should be Send + Sync when T is Send + Sync
        assert_send_sync::<Instance<TestData>>();
    }

    #[cfg(feature = "thread-safe")]
    #[test]
    fn test_instance_can_be_shared_across_threads() {
        use std::sync::Arc;
        use std::thread;

        let instance = Arc::new(Instance::new(Shared::new(TestData {
            id: 123,
            name: "thread-test".to_string(),
        })));

        let handles: Vec<_> = (0..4)
            .map(|_| {
                let instance_clone = Arc::clone(&instance);
                thread::spawn(move || instance_clone.get().id)
            })
            .collect();

        for handle in handles {
            let result = handle.join().unwrap();
            assert_eq!(result, 123);
        }
    }

    #[cfg(feature = "thread-safe")]
    #[test]
    fn test_instance_value_can_be_sent_to_thread() {
        use std::thread;

        let instance = Instance::new(Shared::new(TestData {
            id: 456,
            name: "send-test".to_string(),
        }));

        let shared = instance.value();

        let handle = thread::spawn(move || shared.id);

        let result = handle.join().unwrap();
        assert_eq!(result, 456);
    }

    #[cfg(feature = "thread-safe")]
    #[test]
    fn test_multiple_threads_accessing_same_instance() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicU32, Ordering};
        use std::thread;

        #[derive(Debug)]
        struct SharedCounter {
            value: AtomicU32,
        }

        let instance = Arc::new(Instance::new(Shared::new(SharedCounter {
            value: AtomicU32::new(0),
        })));

        let handles: Vec<_> = (0..10)
            .map(|_| {
                let instance_clone = Arc::clone(&instance);
                thread::spawn(move || {
                    for _ in 0..100 {
                        instance_clone.get().value.fetch_add(1, Ordering::SeqCst);
                    }
                })
            })
            .collect();

        for handle in handles {
            handle.join().unwrap();
        }

        let final_value = instance.get().value.load(Ordering::SeqCst);
        assert_eq!(final_value, 1000); // 10 threads * 100 increments
    }

    #[test]
    fn test_realistic_dependency_injection_scenario() {
        #[derive(Debug)]
        struct Config {
            database_url: String,
            cache_ttl: u64,
        }

        #[derive(Debug)]
        struct Application {
            config: Shared<Config>,
        }

        impl Application {
            fn new(config: Shared<Config>) -> Self {
                Self { config }
            }

            fn get_database_url(&self) -> &str {
                &self.config.database_url
            }
        }

        // Simulate DI container resolving a config
        let config_instance = Instance::new(Shared::new(Config {
            database_url: "postgresql://prod".to_string(),
            cache_ttl: 3600,
        }));

        // Application uses the resolved config
        let app = Application::new(config_instance.value());

        assert_eq!(app.get_database_url(), "postgresql://prod");
        assert_eq!(app.config.cache_ttl, 3600);
    }

    #[test]
    fn test_instance_in_collection() {
        let instances: Vec<Instance<TestData>> = vec![
            Instance::new(Shared::new(TestData {
                id: 1,
                name: "one".to_string(),
            })),
            Instance::new(Shared::new(TestData {
                id: 2,
                name: "two".to_string(),
            })),
            Instance::new(Shared::new(TestData {
                id: 3,
                name: "three".to_string(),
            })),
        ];

        assert_eq!(instances.len(), 3);
        assert_eq!(instances[0].get().id, 1);
        assert_eq!(instances[1].get().name, "two");
        assert_eq!(instances[2].get().id, 3);
    }

    #[test]
    fn test_instance_with_option() {
        let some_instance = Some(Instance::new(Shared::new(TestData {
            id: 100,
            name: "optional".to_string(),
        })));

        let none_instance: Option<Instance<TestData>> = None;

        assert!(some_instance.is_some());
        assert!(none_instance.is_none());

        if let Some(instance) = some_instance {
            assert_eq!(instance.get().id, 100);
        }
    }
}