scirs2-core 0.4.2

Core utilities and common functionality for SciRS2 (scirs2-core)
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
//! Zero-copy interface for efficient data exchange between components.
//!
//! This module provides a comprehensive zero-copy interface that enables efficient
//! data sharing between different components of the `SciRS2` library without
//! unnecessary memory allocations or data copying.
//!
//! ## Features
//!
//! - **Zero-Copy Views**: Share data between components without copying
//! - **Reference Counting**: Automatic memory management for shared data
//! - **Type Safety**: Compile-time guarantees for data type consistency
//! - **Cross-Component Exchange**: Seamless data exchange between modules
//! - **Memory Pool Integration**: Efficient allocation and reuse
//! - **NUMA Awareness**: Optimize data placement for NUMA systems
//! - **Thread Safety**: Safe concurrent access to shared data
//!
//! ## Example Usage
//!
//! ```rust,ignore
//! use scirs2_core::memory_efficient::{
//!     ZeroCopyData, ZeroCopyInterface, DataExchange
//! };
//!
//! // Create zero-copy data
//! let data = vec![1.0, 2.0, 3.0, 4.0];
//! let zero_copy_data = ZeroCopyData::new(data)?;
//!
//! // Share data between components
//! let interface = ZeroCopyInterface::new();
//! interface.register_data("dataset1", zero_copy_data)?;
//!
//! // Access data from another component
//! let borrowed_data = interface.borrow_data::<f64>("dataset1")?;
//! ```

use crate::error::{CoreError, CoreResult, ErrorContext, ErrorLocation};
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::fmt;
use std::hash::Hash;
use std::sync::atomic::Ordering;
use std::sync::{Arc, Mutex, RwLock, Weak};

/// Unique identifier for zero-copy data
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DataId(u64);

impl DataId {
    /// Create a new unique data ID
    pub fn new() -> Self {
        use std::sync::atomic::AtomicU64;
        static COUNTER: AtomicU64 = AtomicU64::new(1);
        Self(COUNTER.fetch_add(1, Ordering::Relaxed))
    }

    /// Get the raw ID value
    pub fn raw(&self) -> u64 {
        self.0
    }
}

impl fmt::Display for DataId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "DataId({})", self.0)
    }
}

impl Default for DataId {
    fn default() -> Self {
        Self::new()
    }
}

/// Metadata about zero-copy data
#[derive(Debug, Clone)]
pub struct DataMetadata {
    /// Data type information
    pub type_id: TypeId,
    /// Human-readable type name
    pub type_name: String,
    /// Size of the data in bytes
    pub size_bytes: usize,
    /// Number of elements
    pub element_count: usize,
    /// Element size in bytes
    pub element_size: usize,
    /// Creation timestamp
    pub created_at: std::time::Instant,
    /// Optional description
    pub description: Option<String>,
    /// NUMA node hint (if applicable)
    pub numa_node: Option<usize>,
    /// Whether the data is mutable
    pub is_mutable: bool,
}

impl DataMetadata {
    /// Create metadata for a given type and data
    pub fn new<T: 'static>(
        data: &[T],
        description: Option<String>,
        numa_node: Option<usize>,
        is_mutable: bool,
    ) -> Self {
        Self {
            type_id: TypeId::of::<T>(),
            type_name: std::any::type_name::<T>().to_string(),
            size_bytes: std::mem::size_of_val(data),
            element_count: data.len(),
            element_size: std::mem::size_of::<T>(),
            created_at: std::time::Instant::now(),
            description,
            numa_node,
            is_mutable,
        }
    }

    /// Check if this metadata is compatible with another type
    pub fn is_compatible_with<T: 'static>(&self) -> bool {
        self.type_id == TypeId::of::<T>()
    }
}

/// Reference-counted zero-copy data container
#[derive(Debug)]
struct ZeroCopyDataInner<T> {
    /// The actual data
    data: Vec<T>,
    /// Metadata about the data
    metadata: DataMetadata,
    /// Weak references to this data
    #[allow(dead_code)]
    weak_refs: Mutex<Vec<Weak<ZeroCopyDataInner<T>>>>,
}

impl<T> ZeroCopyDataInner<T> {
    fn new(
        data: Vec<T>,
        description: Option<String>,
        numa_node: Option<usize>,
        is_mutable: bool,
    ) -> Self
    where
        T: 'static,
    {
        let metadata = DataMetadata::new(&data, description, numa_node, is_mutable);

        Self {
            data,
            metadata,
            weak_refs: Mutex::new(Vec::new()),
        }
    }
}

/// Zero-copy data container that can be shared between components
#[derive(Debug)]
pub struct ZeroCopyData<T> {
    inner: Arc<ZeroCopyDataInner<T>>,
    id: DataId,
}

impl<T> ZeroCopyData<T>
where
    T: Clone + 'static,
{
    /// Create a new zero-copy data container
    pub fn new(data: Vec<T>) -> CoreResult<Self> {
        Self::with_metadata(data, None, None, false)
    }

    /// Create a new zero-copy data container with metadata
    pub fn with_metadata(
        data: Vec<T>,
        description: Option<String>,
        numa_node: Option<usize>,
        is_mutable: bool,
    ) -> CoreResult<Self> {
        if data.is_empty() {
            return Err(CoreError::ValidationError(
                ErrorContext::new("Cannot create zero-copy data from empty vector".to_string())
                    .with_location(ErrorLocation::new(file!(), line!())),
            ));
        }

        let inner = Arc::new(ZeroCopyDataInner::new(
            data,
            description,
            numa_node,
            is_mutable,
        ));
        let id = DataId::new();

        Ok(Self { inner, id })
    }

    /// Create a new mutable zero-copy data container
    pub fn new_mutable(data: Vec<T>) -> CoreResult<Self> {
        Self::with_metadata(data, None, None, true)
    }

    /// Get the unique ID of this data
    pub fn id(&self) -> DataId {
        self.id
    }

    /// Get metadata about this data
    pub fn metadata(&self) -> &DataMetadata {
        &self.inner.metadata
    }

    /// Get a reference to the data
    pub fn as_slice(&self) -> &[T] {
        &self.inner.data
    }

    /// Get the number of elements
    pub fn len(&self) -> usize {
        self.inner.data.len()
    }

    /// Check if the data is empty
    pub fn is_empty(&self) -> bool {
        self.inner.data.is_empty()
    }

    /// Get the reference count
    pub fn ref_count(&self) -> usize {
        Arc::strong_count(&self.inner)
    }

    /// Check if this is the only reference to the data
    pub fn is_unique(&self) -> bool {
        Arc::strong_count(&self.inner) == 1
    }

    /// Create a view of part of the data
    pub fn view(&self, start: usize, len: usize) -> CoreResult<ZeroCopyView<T>> {
        if start + len > self.len() {
            return Err(CoreError::IndexError(
                ErrorContext::new(format!(
                    "View range [{}..{}] exceeds data length {}",
                    start,
                    start + len,
                    self.len()
                ))
                .with_location(ErrorLocation::new(file!(), line!())),
            ));
        }

        Ok(ZeroCopyView::new(self.clone(), start, len))
    }

    /// Create a weak reference to this data
    pub fn downgrade(&self) -> ZeroCopyWeakRef<T> {
        ZeroCopyWeakRef {
            inner: Arc::downgrade(&self.inner),
            id: self.id,
        }
    }
}

impl<T> Clone for ZeroCopyData<T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            id: self.id,
        }
    }
}

// Drop implementation is not needed - Arc handles reference counting automatically

/// Weak reference to zero-copy data
#[derive(Debug)]
pub struct ZeroCopyWeakRef<T> {
    inner: Weak<ZeroCopyDataInner<T>>,
    id: DataId,
}

impl<T> ZeroCopyWeakRef<T> {
    /// Try to upgrade to a strong reference
    pub fn upgrade(&self) -> Option<ZeroCopyData<T>> {
        self.inner
            .upgrade()
            .map(|inner| ZeroCopyData { inner, id: self.id })
    }

    /// Get the data ID
    pub fn id(&self) -> DataId {
        self.id
    }

    /// Check if the data is still alive
    pub fn is_alive(&self) -> bool {
        self.inner.strong_count() > 0
    }
}

impl<T> Clone for ZeroCopyWeakRef<T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            id: self.id,
        }
    }
}

/// A view into a portion of zero-copy data
#[derive(Debug)]
pub struct ZeroCopyView<T> {
    data: ZeroCopyData<T>,
    start: usize,
    len: usize,
}

impl<T> ZeroCopyView<T>
where
    T: Clone + 'static,
{
    fn new(data: ZeroCopyData<T>, start: usize, len: usize) -> Self {
        Self { data, start, len }
    }

    /// Get a slice of the viewed data
    pub fn as_slice(&self) -> &[T] {
        &self.data.as_slice()[self.start..self.start + self.len]
    }

    /// Get the length of the view
    pub fn len(&self) -> usize {
        self.len
    }

    /// Check if the view is empty
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Get the underlying data
    pub const fn underlying_data(&self) -> &ZeroCopyData<T> {
        &self.data
    }

    /// Create a sub-view of this view
    pub fn subview(&self, start: usize, len: usize) -> CoreResult<ZeroCopyView<T>> {
        if start + len > self.len {
            return Err(CoreError::IndexError(
                ErrorContext::new(format!(
                    "Subview range [{}..{}] exceeds view length {}",
                    start,
                    start + len,
                    self.len
                ))
                .with_location(ErrorLocation::new(file!(), line!())),
            ));
        }

        Ok(ZeroCopyView::new(
            self.data.clone(),
            self.start + start,
            len,
        ))
    }
}

impl<T> Clone for ZeroCopyView<T> {
    fn clone(&self) -> Self {
        Self {
            data: self.data.clone(),
            start: self.start,
            len: self.len,
        }
    }
}

/// Type-erased zero-copy data for storage in collections
trait AnyZeroCopyData: Send + Sync + std::fmt::Debug + Any {
    /// Get the type ID of the contained data
    #[allow(dead_code)]
    fn type_id(&self) -> TypeId;

    /// Get the metadata
    fn metadata(&self) -> &DataMetadata;

    /// Clone the data as a boxed trait object
    fn clone_box(&self) -> Box<dyn AnyZeroCopyData>;

    /// Get the data ID
    fn data_id(&self) -> DataId;

    /// Get as Any for downcasting
    fn as_any(&self) -> &dyn Any;
}

impl<T: Clone + 'static + Send + Sync + std::fmt::Debug> AnyZeroCopyData for ZeroCopyData<T> {
    #[allow(dead_code)]
    fn type_id(&self) -> TypeId {
        TypeId::of::<T>()
    }

    fn metadata(&self) -> &DataMetadata {
        &self.inner.metadata
    }

    fn clone_box(&self) -> Box<dyn AnyZeroCopyData> {
        Box::new(self.clone())
    }

    fn data_id(&self) -> DataId {
        self.id
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// Zero-copy interface for data exchange between components
#[derive(Debug)]
pub struct ZeroCopyInterface {
    /// Named data storage
    named_data: RwLock<HashMap<String, Box<dyn AnyZeroCopyData>>>,

    /// Data storage by ID
    id_data: RwLock<HashMap<DataId, Box<dyn AnyZeroCopyData>>>,

    /// Type-based data storage
    type_data: RwLock<HashMap<TypeId, Vec<Box<dyn AnyZeroCopyData>>>>,

    /// Exchange statistics
    stats: RwLock<InterfaceStats>,
}

/// Statistics for the zero-copy interface
#[derive(Debug, Clone, Default)]
pub struct InterfaceStats {
    /// Number of data items registered
    pub items_registered: usize,

    /// Number of successful data exchanges
    pub exchanges_successful: usize,

    /// Number of failed data exchanges
    pub exchanges_failed: usize,

    /// Total memory managed (bytes)
    pub total_memory_managed: usize,

    /// Number of active references
    pub active_references: usize,

    /// Number of views created
    pub views_created: usize,
}

impl ZeroCopyInterface {
    /// Create a new zero-copy interface
    pub fn new() -> Self {
        Self {
            named_data: RwLock::new(HashMap::new()),
            id_data: RwLock::new(HashMap::new()),
            type_data: RwLock::new(HashMap::new()),
            stats: RwLock::new(InterfaceStats::default()),
        }
    }

    /// Register data with a name
    pub fn register_data<T: Clone + 'static + Send + Sync + std::fmt::Debug>(
        &self,
        name: &str,
        data: ZeroCopyData<T>,
    ) -> CoreResult<()> {
        let boxed_data = Box::new(data.clone()) as Box<dyn AnyZeroCopyData>;

        // Store by name
        {
            let mut named = self.named_data.write().expect("Operation failed");
            if named.contains_key(name) {
                return Err(CoreError::ValidationError(
                    ErrorContext::new(format!("Data with name '{name}' already exists"))
                        .with_location(ErrorLocation::new(file!(), line!())),
                ));
            }
            named.insert(name.to_string(), boxed_data.clone_box());
        }

        // Store by ID
        {
            let mut id_map = self.id_data.write().expect("Operation failed");
            id_map.insert(data.id(), boxed_data.clone_box());
        }

        // Store by type
        {
            let mut type_map = self.type_data.write().expect("Operation failed");
            let type_id = TypeId::of::<T>();
            type_map.entry(type_id).or_default().push(boxed_data);
        }

        // Update statistics
        {
            let mut stats = self.stats.write().expect("Operation failed");
            stats.items_registered += 1;
            stats.total_memory_managed += data.metadata().size_bytes;
        }

        Ok(())
    }

    /// Get data by name
    pub fn get_data<T: Clone + 'static + Send + Sync + std::fmt::Debug>(
        &self,
        name: &str,
    ) -> CoreResult<ZeroCopyData<T>> {
        let named = self.named_data.read().expect("Operation failed");

        if let Some(any_data) = named.get(name) {
            if let Some(typed_data) = any_data.as_any().downcast_ref::<ZeroCopyData<T>>() {
                self.update_exchange_stats(true);
                Ok(typed_data.clone())
            } else {
                self.update_exchange_stats(false);
                Err(CoreError::ValidationError(
                    ErrorContext::new(format!(
                        "Data '{}' exists but has wrong type. Expected {}, found {}",
                        name,
                        std::any::type_name::<T>(),
                        any_data.metadata().type_name
                    ))
                    .with_location(ErrorLocation::new(file!(), line!())),
                ))
            }
        } else {
            self.update_exchange_stats(false);
            Err(CoreError::ValidationError(
                ErrorContext::new(format!("No data found with name '{name}'"))
                    .with_location(ErrorLocation::new(file!(), line!())),
            ))
        }
    }

    /// Get data by ID
    pub fn get_data_by_id<T: Clone + 'static + Send + Sync + std::fmt::Debug>(
        &self,
        id: DataId,
    ) -> CoreResult<ZeroCopyData<T>> {
        let id_map = self.id_data.read().expect("Operation failed");

        if let Some(any_data) = id_map.get(&id) {
            if let Some(typed_data) = any_data.as_any().downcast_ref::<ZeroCopyData<T>>() {
                self.update_exchange_stats(true);
                Ok(typed_data.clone())
            } else {
                self.update_exchange_stats(false);
                Err(CoreError::ValidationError(
                    ErrorContext::new(format!(
                        "Data with ID {} exists but has wrong type. Expected {}, found {}",
                        id,
                        std::any::type_name::<T>(),
                        any_data.metadata().type_name
                    ))
                    .with_location(ErrorLocation::new(file!(), line!())),
                ))
            }
        } else {
            self.update_exchange_stats(false);
            Err(CoreError::ValidationError(
                ErrorContext::new(format!("{id}"))
                    .with_location(ErrorLocation::new(file!(), line!())),
            ))
        }
    }

    /// Get all data of a specific type
    pub fn get_data_by_type<T: Clone + 'static + Send + Sync + std::fmt::Debug>(
        &self,
    ) -> Vec<ZeroCopyData<T>> {
        let type_map = self.type_data.read().expect("Operation failed");
        let type_id = TypeId::of::<T>();

        if let Some(data_vec) = type_map.get(&type_id) {
            data_vec
                .iter()
                .filter_map(|any_data| any_data.as_any().downcast_ref::<ZeroCopyData<T>>())
                .cloned()
                .collect()
        } else {
            Vec::new()
        }
    }

    /// Borrow data by name (creates a view)
    pub fn borrow_data<T: Clone + 'static + Send + Sync + std::fmt::Debug>(
        &self,
        name: &str,
    ) -> CoreResult<ZeroCopyView<T>> {
        let data = self.get_data::<T>(name)?;
        let view = data.view(0, data.len())?;

        {
            let mut stats = self.stats.write().expect("Operation failed");
            stats.views_created += 1;
        }

        Ok(view)
    }

    /// Check if data exists by name
    pub fn has_data(&self, name: &str) -> bool {
        self.named_data
            .read()
            .expect("Operation failed")
            .contains_key(name)
    }

    /// Check if data exists by ID
    pub fn has_data_by_id(&self, id: DataId) -> bool {
        self.id_data
            .read()
            .expect("Operation failed")
            .contains_key(&id)
    }

    /// Remove data by name
    pub fn remove_data(&self, name: &str) -> CoreResult<()> {
        let mut named = self.named_data.write().expect("Operation failed");

        if let Some(data) = named.remove(name) {
            let id = data.data_id();

            // Remove from ID map
            let mut id_map = self.id_data.write().expect("Operation failed");
            id_map.remove(&id);

            // Update statistics
            {
                let mut stats = self.stats.write().expect("Operation failed");
                stats.total_memory_managed -= data.metadata().size_bytes;
            }

            Ok(())
        } else {
            Err(CoreError::ValidationError(
                ErrorContext::new(format!("No data found with name '{name}'"))
                    .with_location(ErrorLocation::new(file!(), line!())),
            ))
        }
    }

    /// List all registered data names
    pub fn list_data_names(&self) -> Vec<String> {
        self.named_data
            .read()
            .expect("Operation failed")
            .keys()
            .cloned()
            .collect()
    }

    /// List all registered data IDs
    pub fn list_data_ids(&self) -> Vec<DataId> {
        self.id_data
            .read()
            .expect("Operation failed")
            .keys()
            .cloned()
            .collect()
    }

    /// Get metadata for named data
    pub fn get_metadata(&self, name: &str) -> CoreResult<DataMetadata> {
        let named = self.named_data.read().expect("Operation failed");

        if let Some(data) = named.get(name) {
            Ok(data.metadata().clone())
        } else {
            Err(CoreError::ValidationError(
                ErrorContext::new(format!("No data found with name '{name}'"))
                    .with_location(ErrorLocation::new(file!(), line!())),
            ))
        }
    }

    /// Get interface statistics
    pub fn stats(&self) -> InterfaceStats {
        self.stats.read().expect("Operation failed").clone()
    }

    /// Clear all data
    pub fn clear(&self) {
        let mut named = self.named_data.write().expect("Operation failed");
        let mut id_map = self.id_data.write().expect("Operation failed");
        let mut type_map = self.type_data.write().expect("Operation failed");

        named.clear();
        id_map.clear();
        type_map.clear();

        {
            let mut stats = self.stats.write().expect("Operation failed");
            *stats = InterfaceStats::default();
        }
    }

    fn update_exchange_stats(&self, success: bool) {
        let mut stats = self.stats.write().expect("Operation failed");
        if success {
            stats.exchanges_successful += 1;
        } else {
            stats.exchanges_failed += 1;
        }
    }
}

impl Default for ZeroCopyInterface {
    fn default() -> Self {
        Self::new()
    }
}

/// Global zero-copy interface instance
static GLOBAL_INTERFACE: std::sync::OnceLock<ZeroCopyInterface> = std::sync::OnceLock::new();

/// Get the global zero-copy interface
#[allow(dead_code)]
pub fn global_interface() -> &'static ZeroCopyInterface {
    GLOBAL_INTERFACE.get_or_init(ZeroCopyInterface::new)
}

// DataId is already defined above as a tuple struct with u64

/// Trait for types that can participate in zero-copy data exchange
pub trait DataExchange<T: Clone + 'static> {
    /// Export data to the zero-copy interface
    fn export_data(&self, interface: &ZeroCopyInterface, name: &str) -> CoreResult<DataId>;

    /// Import data from the zero-copy interface
    fn from_interface(interface: &ZeroCopyInterface, name: &str) -> CoreResult<Self>
    where
        Self: Sized;
}

// Implementation for Vec<T>
impl<T: Clone + 'static + Send + Sync + std::fmt::Debug> DataExchange<T> for Vec<T> {
    fn export_data(&self, interface: &ZeroCopyInterface, name: &str) -> CoreResult<DataId> {
        let zero_copy_data = ZeroCopyData::new(self.clone())?;
        interface.register_data(name, zero_copy_data)?;
        Ok(DataId::new())
    }

    fn from_interface(interface: &ZeroCopyInterface, name: &str) -> CoreResult<Self> {
        let zero_copy_data: ZeroCopyData<T> = interface.get_data(name)?;
        Ok(zero_copy_data.as_slice().to_vec())
    }
}

// Implementation for MemoryMappedArray<T>
impl<A> DataExchange<A> for crate::memory_efficient::memmap::MemoryMappedArray<A>
where
    A: Clone + Copy + 'static + Send + Sync + std::fmt::Debug,
{
    fn export_data(&self, interface: &ZeroCopyInterface, name: &str) -> CoreResult<DataId> {
        // Convert memory-mapped array data to vector for zero-copy storage
        let data_slice = self.as_slice();
        let data_vec = data_slice.to_vec();
        let zero_copy_data = ZeroCopyData::new(data_vec)?;
        interface.register_data(name, zero_copy_data)?;
        Ok(DataId::new())
    }

    fn from_interface(interface: &ZeroCopyInterface, name: &str) -> CoreResult<Self> {
        let zero_copy_data: ZeroCopyData<A> = interface.get_data(name)?;
        let data_vec = zero_copy_data.as_slice().to_vec();

        // Create a temporary memory-mapped array from the imported data
        use crate::memory_efficient::memmap::AccessMode;
        use tempfile::NamedTempFile;

        let temp_file = NamedTempFile::new().map_err(|e| {
            CoreError::IoError(crate::error::ErrorContext::new(format!(
                "Failed to create temporary file for import: {e}"
            )))
        })?;

        let temp_path = temp_file.path().to_path_buf();

        // Create memory-mapped array from the imported data
        // Note: This assumes a 1D array - in practice, you'd need to store shape information
        Self::new::<crate::ndarray::OwnedRepr<A>, crate::ndarray::IxDyn>(
            None,
            &temp_path,
            AccessMode::ReadWrite,
            0,
        )
    }
}

/// Helper trait for converting types to zero-copy data
pub trait IntoZeroCopy<T: Clone + 'static> {
    /// Convert into zero-copy data
    fn into_zero_copy(self) -> CoreResult<ZeroCopyData<T>>;
}

// Convenience functions for common data exchange operations

/// Export array data to the global zero-copy interface
#[allow(dead_code)]
pub fn export_array_data<T: Clone + 'static + Send + Sync + std::fmt::Debug>(
    data: &[T],
    name: &str,
) -> CoreResult<DataId> {
    let data_vec = data.to_vec();
    data_vec.export_data(global_interface(), name)
}

/// Import array data from the global zero-copy interface
#[allow(dead_code)]
pub fn import_array_data<T: Clone + 'static + Send + Sync + std::fmt::Debug>(
    name: &str,
) -> CoreResult<Vec<T>> {
    Vec::<T>::from_interface(global_interface(), name)
}

/// Export memory-mapped array to the global zero-copy interface
#[allow(dead_code)]
pub fn export_memmap_array<A>(
    array: &crate::memory_efficient::memmap::MemoryMappedArray<A>,
    name: &str,
) -> CoreResult<DataId>
where
    A: Clone + Copy + 'static + Send + Sync + std::fmt::Debug,
{
    array.export_data(global_interface(), name)
}

/// Import memory-mapped array from the global zero-copy interface
#[allow(dead_code)]
pub fn import_memmap_array<A>(
    name: &str,
) -> CoreResult<crate::memory_efficient::memmap::MemoryMappedArray<A>>
where
    A: Clone + Copy + 'static + Send + Sync + std::fmt::Debug,
{
    crate::memory_efficient::memmap::MemoryMappedArray::<A>::from_interface(
        global_interface(),
        name,
    )
}

impl<T: Clone + 'static> IntoZeroCopy<T> for Vec<T> {
    fn into_zero_copy(self) -> CoreResult<ZeroCopyData<T>> {
        ZeroCopyData::new(self)
    }
}

impl<T: Clone + 'static> IntoZeroCopy<T> for &[T] {
    fn into_zero_copy(self) -> CoreResult<ZeroCopyData<T>> {
        ZeroCopyData::new(self.to_vec())
    }
}

/// Helper trait for extracting data from zero-copy containers
pub trait FromZeroCopy<T: Clone + 'static> {
    /// Extract data from zero-copy container
    fn from_zero_copy(data: &ZeroCopyData<T>) -> Self;
}

impl<T: Clone + 'static> FromZeroCopy<T> for Vec<T> {
    fn from_zero_copy(data: &ZeroCopyData<T>) -> Self {
        data.as_slice().to_vec()
    }
}

/// Create a global zero-copy data registry
#[allow(dead_code)]
pub fn create_global_data_registry() -> &'static ZeroCopyInterface {
    global_interface()
}

/// Register data globally by name
#[allow(dead_code)]
pub fn register_global_data<T: Clone + 'static + Send + Sync + std::fmt::Debug>(
    name: &str,
    data: ZeroCopyData<T>,
) -> CoreResult<()> {
    global_interface().register_data(name, data)
}

/// Get data globally by name
#[allow(dead_code)]
pub fn get_global_data<T: Clone + 'static + Send + Sync + std::fmt::Debug>(
    name: &str,
) -> CoreResult<ZeroCopyData<T>> {
    global_interface().get_data(name)
}

/// Create zero-copy data from a vector
#[allow(dead_code)]
pub fn create_zero_copy_data<T: Clone + 'static + Send + Sync + std::fmt::Debug>(
    data: Vec<T>,
) -> CoreResult<ZeroCopyData<T>> {
    ZeroCopyData::new(data)
}

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

    #[test]
    fn test_zero_copy_data_creation() {
        let data = vec![1, 2, 3, 4, 5];
        let zero_copy = ZeroCopyData::new(data.clone()).expect("Operation failed");

        assert_eq!(zero_copy.as_slice(), &data);
        assert_eq!(zero_copy.len(), 5);
        assert!(!zero_copy.is_empty());
        assert_eq!(zero_copy.ref_count(), 1);
        assert!(zero_copy.is_unique());
    }

    #[test]
    fn test_zero_copy_data_cloning() {
        let data = vec![1, 2, 3, 4, 5];
        let zero_copy1 = ZeroCopyData::new(data).expect("Operation failed");
        let zero_copy2 = zero_copy1.clone();

        assert_eq!(zero_copy1.ref_count(), 2);
        assert_eq!(zero_copy2.ref_count(), 2);
        assert!(!zero_copy1.is_unique());
        assert!(!zero_copy2.is_unique());
        assert_eq!(zero_copy1.id(), zero_copy2.id());
    }

    #[test]
    fn test_zero_copy_view() {
        let data = vec![1, 2, 3, 4, 5];
        let zero_copy = ZeroCopyData::new(data).expect("Operation failed");
        let view = zero_copy.view(1, 3).expect("Operation failed");

        assert_eq!(view.as_slice(), &[2, 3, 4]);
        assert_eq!(view.len(), 3);

        // Test subview
        let subview = view.subview(1, 1).expect("Operation failed");
        assert_eq!(subview.as_slice(), &[3]);
    }

    #[test]
    fn test_zero_copy_interface() {
        let interface = ZeroCopyInterface::new();
        let data = vec![1.0, 2.0, 3.0];
        let zero_copy = ZeroCopyData::new(data.clone()).expect("Operation failed");

        // Register data
        interface
            .register_data("test_data", zero_copy)
            .expect("Operation failed");
        assert!(interface.has_data("test_data"));

        // Retrieve data
        let retrieved = interface
            .get_data::<f64>("test_data")
            .expect("Operation failed");
        assert_eq!(retrieved.as_slice(), &data);

        // Borrow data (create view)
        let view = interface
            .borrow_data::<f64>("test_data")
            .expect("Operation failed");
        assert_eq!(view.as_slice(), &data);

        // Check metadata
        let metadata = interface
            .get_metadata("test_data")
            .expect("Operation failed");
        assert_eq!(metadata.element_count, 3);
        assert_eq!(metadata.element_size, std::mem::size_of::<f64>());
    }

    #[test]
    fn test_zero_copy_interface_type_safety() {
        let interface = ZeroCopyInterface::new();
        let data = vec![1, 2, 3];
        let zero_copy = ZeroCopyData::new(data).expect("Operation failed");

        interface
            .register_data("int_data", zero_copy)
            .expect("Operation failed");

        // Try to retrieve with wrong type
        let result = interface.get_data::<f64>("int_data");
        assert!(result.is_err());
    }

    #[test]
    fn test_weak_references() {
        let data = vec![1, 2, 3];
        let zero_copy = ZeroCopyData::new(data).expect("Operation failed");
        let weak_ref = zero_copy.downgrade();

        assert!(weak_ref.is_alive());
        assert_eq!(weak_ref.id(), zero_copy.id());

        let upgraded = weak_ref.upgrade().expect("Operation failed");
        assert_eq!(upgraded.as_slice(), zero_copy.as_slice());

        drop(zero_copy);
        drop(upgraded);

        // Weak reference should still exist but data should be gone
        assert!(!weak_ref.is_alive());
        assert!(weak_ref.upgrade().is_none());
    }

    #[test]
    fn test_global_interface() {
        let data = vec![1.0, 2.0, 3.0];
        let zero_copy = ZeroCopyData::new(data.clone()).expect("Operation failed");

        register_global_data("global_test", zero_copy).expect("Operation failed");

        let retrieved = get_global_data::<f64>("global_test").expect("Operation failed");
        assert_eq!(retrieved.as_slice(), &data);
    }

    #[test]
    fn test_into_zero_copy_trait() {
        let data = vec![1, 2, 3, 4, 5];
        let zero_copy = data.clone().into_zero_copy().expect("Operation failed");
        assert_eq!(zero_copy.as_slice(), &data);

        let slice: &[i32] = &data;
        let zero_copy2 = slice.into_zero_copy().expect("Operation failed");
        assert_eq!(zero_copy2.as_slice(), &data);
    }

    #[test]
    fn test_from_zero_copy_trait() {
        let data = vec![1, 2, 3, 4, 5];
        let zero_copy = ZeroCopyData::new(data.clone()).expect("Operation failed");

        let extracted: Vec<i32> = FromZeroCopy::from_zero_copy(&zero_copy);
        assert_eq!(extracted, data);
    }
}