crdtosphere/traits/
platform.rs

1//! Platform CRDT trait definition
2//!
3//! This module defines traits for CRDTs that are optimized for specific
4//! embedded platforms and hardware architectures.
5
6use crate::error::CRDTResult;
7use crate::memory::MemoryConfig;
8use crate::traits::CRDT;
9
10/// Trait for CRDTs that are platform-aware
11///
12/// This trait provides platform-specific optimizations and ensures
13/// compatibility with different embedded hardware architectures.
14pub trait PlatformCRDT<C: MemoryConfig>: CRDT<C> {
15    /// The platform this CRDT is optimized for
16    type Platform: Platform;
17
18    /// Returns the target platform
19    fn target_platform() -> Self::Platform;
20
21    /// Performs platform-specific initialization
22    fn platform_init(&mut self) -> CRDTResult<()>;
23
24    /// Performs platform-specific cleanup
25    fn platform_cleanup(&mut self) -> CRDTResult<()>;
26
27    /// Returns platform-specific capabilities
28    fn platform_capabilities(&self) -> PlatformCapabilities;
29
30    /// Checks if the current platform is supported
31    fn is_platform_supported() -> bool;
32
33    /// Returns platform-specific memory alignment requirements
34    fn platform_alignment() -> usize {
35        Self::Platform::memory_alignment()
36    }
37
38    /// Returns platform-specific cache line size
39    fn platform_cache_line_size() -> usize {
40        Self::Platform::cache_line_size()
41    }
42
43    /// Performs platform-optimized merge
44    fn platform_merge(&mut self, other: &Self) -> CRDTResult<()>;
45}
46
47/// Platform trait for different embedded platforms
48pub trait Platform {
49    /// Platform name
50    const NAME: &'static str;
51
52    /// CPU architecture
53    const ARCHITECTURE: Architecture;
54
55    /// Memory alignment requirement
56    fn memory_alignment() -> usize;
57
58    /// Cache line size
59    fn cache_line_size() -> usize;
60
61    /// Maximum interrupt latency in CPU cycles
62    fn max_interrupt_latency() -> u32;
63
64    /// Supports atomic operations
65    fn supports_atomics() -> bool;
66
67    /// Supports floating point operations
68    fn supports_fpu() -> bool;
69
70    /// Supports SIMD operations
71    fn supports_simd() -> bool;
72
73    /// Returns platform-specific features
74    fn features() -> PlatformFeatures;
75}
76
77/// CPU architectures
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub enum Architecture {
80    /// ARM Cortex-M series
81    CortexM,
82    /// ARM Cortex-R series
83    CortexR,
84    /// AURIX TriCore
85    TriCore,
86    /// RISC-V
87    RiscV,
88    /// x86/x64 (for testing)
89    X86,
90}
91
92/// Platform capabilities
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub struct PlatformCapabilities {
95    /// Supports hardware acceleration
96    pub hardware_acceleration: bool,
97    /// Supports DMA operations
98    pub dma_support: bool,
99    /// Supports memory protection
100    pub memory_protection: bool,
101    /// Supports real-time guarantees
102    pub realtime_support: bool,
103    /// Supports multi-core operations
104    pub multicore_support: bool,
105    /// Maximum number of cores
106    pub max_cores: u8,
107}
108
109/// Platform-specific features
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub struct PlatformFeatures {
112    /// Atomic operations support
113    pub atomics: bool,
114    /// Floating point unit
115    pub fpu: bool,
116    /// SIMD instructions
117    pub simd: bool,
118    /// Hardware CRC
119    pub hardware_crc: bool,
120    /// Hardware encryption
121    pub hardware_crypto: bool,
122    /// Memory management unit
123    pub mmu: bool,
124    /// Cache coherency
125    pub cache_coherent: bool,
126}
127
128/// AURIX platform implementation
129pub struct AurixPlatform;
130
131impl Platform for AurixPlatform {
132    const NAME: &'static str = "AURIX";
133    const ARCHITECTURE: Architecture = Architecture::TriCore;
134
135    fn memory_alignment() -> usize {
136        4
137    }
138    fn cache_line_size() -> usize {
139        32
140    }
141    fn max_interrupt_latency() -> u32 {
142        100
143    }
144    fn supports_atomics() -> bool {
145        true
146    }
147    fn supports_fpu() -> bool {
148        true
149    }
150    fn supports_simd() -> bool {
151        false
152    }
153
154    fn features() -> PlatformFeatures {
155        PlatformFeatures {
156            atomics: true,
157            fpu: true,
158            simd: false,
159            hardware_crc: true,
160            hardware_crypto: true,
161            mmu: true,
162            cache_coherent: true,
163        }
164    }
165}
166
167/// STM32 platform implementation
168pub struct STM32Platform;
169
170impl Platform for STM32Platform {
171    const NAME: &'static str = "STM32";
172    const ARCHITECTURE: Architecture = Architecture::CortexM;
173
174    fn memory_alignment() -> usize {
175        4
176    }
177    fn cache_line_size() -> usize {
178        32
179    }
180    fn max_interrupt_latency() -> u32 {
181        50
182    }
183    fn supports_atomics() -> bool {
184        true
185    }
186    fn supports_fpu() -> bool {
187        true
188    }
189    fn supports_simd() -> bool {
190        false
191    }
192
193    fn features() -> PlatformFeatures {
194        PlatformFeatures {
195            atomics: true,
196            fpu: true,
197            simd: false,
198            hardware_crc: true,
199            hardware_crypto: false,
200            mmu: false,
201            cache_coherent: false,
202        }
203    }
204}
205
206/// ARM Cortex-M platform implementation
207pub struct CortexMPlatform;
208
209impl Platform for CortexMPlatform {
210    const NAME: &'static str = "Cortex-M";
211    const ARCHITECTURE: Architecture = Architecture::CortexM;
212
213    fn memory_alignment() -> usize {
214        4
215    }
216    fn cache_line_size() -> usize {
217        32
218    }
219    fn max_interrupt_latency() -> u32 {
220        25
221    }
222    fn supports_atomics() -> bool {
223        true
224    }
225    fn supports_fpu() -> bool {
226        false
227    }
228    fn supports_simd() -> bool {
229        false
230    }
231
232    fn features() -> PlatformFeatures {
233        PlatformFeatures {
234            atomics: true,
235            fpu: false,
236            simd: false,
237            hardware_crc: false,
238            hardware_crypto: false,
239            mmu: false,
240            cache_coherent: false,
241        }
242    }
243}
244
245/// RISC-V platform implementation
246pub struct RiscVPlatform;
247
248impl Platform for RiscVPlatform {
249    const NAME: &'static str = "RISC-V";
250    const ARCHITECTURE: Architecture = Architecture::RiscV;
251
252    fn memory_alignment() -> usize {
253        4
254    }
255    fn cache_line_size() -> usize {
256        64
257    }
258    fn max_interrupt_latency() -> u32 {
259        30
260    }
261    fn supports_atomics() -> bool {
262        true
263    }
264    fn supports_fpu() -> bool {
265        true
266    }
267    fn supports_simd() -> bool {
268        true
269    }
270
271    fn features() -> PlatformFeatures {
272        PlatformFeatures {
273            atomics: true,
274            fpu: true,
275            simd: true,
276            hardware_crc: false,
277            hardware_crypto: false,
278            mmu: true,
279            cache_coherent: true,
280        }
281    }
282}
283
284/// Trait for platform-specific optimizations
285pub trait PlatformOptimized<C: MemoryConfig, P: Platform>: PlatformCRDT<C> {
286    /// Performs platform-optimized serialization
287    fn optimized_serialize(&self, buffer: &mut [u8]) -> CRDTResult<usize>;
288
289    /// Performs platform-optimized deserialization
290    fn optimized_deserialize(buffer: &[u8]) -> CRDTResult<Self>
291    where
292        Self: Sized;
293
294    /// Uses platform-specific instructions for hash computation
295    fn platform_hash(&self) -> u32;
296
297    /// Uses platform-specific memory operations
298    fn platform_memcpy(&mut self, src: &Self) -> CRDTResult<()>;
299
300    /// Returns platform-specific performance metrics
301    fn performance_metrics(&self) -> PerformanceMetrics;
302}
303
304/// Performance metrics for platform optimization
305#[derive(Debug, Clone, Copy, PartialEq, Eq)]
306pub struct PerformanceMetrics {
307    /// Merge operation cycles
308    pub merge_cycles: u32,
309    /// Serialization cycles
310    pub serialize_cycles: u32,
311    /// Hash computation cycles
312    pub hash_cycles: u32,
313    /// Memory copy cycles
314    pub memcpy_cycles: u32,
315    /// Cache misses
316    pub cache_misses: u32,
317}
318
319/// Trait for multi-core platform support
320pub trait MultiCorePlatform<C: MemoryConfig>: PlatformCRDT<C> {
321    /// Number of cores available
322    fn core_count() -> u8;
323
324    /// Current core ID
325    fn current_core_id() -> u8;
326
327    /// Performs inter-core synchronization
328    fn sync_cores(&mut self) -> CRDTResult<()>;
329
330    /// Distributes work across cores
331    fn distribute_work(&mut self, core_mask: u8) -> CRDTResult<()>;
332
333    /// Collects results from other cores
334    fn collect_results(&mut self) -> CRDTResult<()>;
335
336    /// Checks if core-local operations are supported
337    fn supports_core_local_ops() -> bool;
338}
339
340#[cfg(test)]
341mod tests {
342    use super::*;
343    use crate::error::CRDTError;
344    use crate::memory::DefaultConfig;
345
346    // Mock platform CRDT for testing
347    struct MockPlatformCRDT {
348        value: u32,
349        initialized: bool,
350    }
351
352    impl MockPlatformCRDT {
353        fn new() -> Self {
354            Self {
355                value: 0,
356                initialized: false,
357            }
358        }
359    }
360
361    impl CRDT<DefaultConfig> for MockPlatformCRDT {
362        type Error = CRDTError;
363
364        fn merge(&mut self, other: &Self) -> CRDTResult<()> {
365            self.value = self.value.max(other.value);
366            Ok(())
367        }
368
369        fn eq(&self, other: &Self) -> bool {
370            self.value == other.value
371        }
372
373        fn size_bytes(&self) -> usize {
374            core::mem::size_of::<Self>()
375        }
376
377        fn validate(&self) -> CRDTResult<()> {
378            Ok(())
379        }
380
381        fn state_hash(&self) -> u32 {
382            self.value
383        }
384
385        fn can_merge(&self, _other: &Self) -> bool {
386            true
387        }
388    }
389
390    impl PlatformCRDT<DefaultConfig> for MockPlatformCRDT {
391        type Platform = STM32Platform;
392
393        fn target_platform() -> Self::Platform {
394            STM32Platform
395        }
396
397        fn platform_init(&mut self) -> CRDTResult<()> {
398            self.initialized = true;
399            Ok(())
400        }
401
402        fn platform_cleanup(&mut self) -> CRDTResult<()> {
403            self.initialized = false;
404            Ok(())
405        }
406
407        fn platform_capabilities(&self) -> PlatformCapabilities {
408            PlatformCapabilities {
409                hardware_acceleration: false,
410                dma_support: true,
411                memory_protection: false,
412                realtime_support: true,
413                multicore_support: false,
414                max_cores: 1,
415            }
416        }
417
418        fn is_platform_supported() -> bool {
419            true
420        }
421
422        fn platform_merge(&mut self, other: &Self) -> CRDTResult<()> {
423            // Platform-optimized merge (same as regular merge for this example)
424            self.merge(other)
425        }
426    }
427
428    #[test]
429    fn test_platform_features() {
430        assert_eq!(STM32Platform::NAME, "STM32");
431        assert_eq!(STM32Platform::ARCHITECTURE, Architecture::CortexM);
432        assert_eq!(STM32Platform::memory_alignment(), 4);
433        assert_eq!(STM32Platform::cache_line_size(), 32);
434        assert!(STM32Platform::supports_atomics());
435        assert!(STM32Platform::supports_fpu());
436        assert!(!STM32Platform::supports_simd());
437
438        let features = STM32Platform::features();
439        assert!(features.atomics);
440        assert!(features.fpu);
441        assert!(!features.simd);
442        assert!(features.hardware_crc);
443        assert!(!features.hardware_crypto);
444    }
445
446    #[test]
447    fn test_platform_crdt() {
448        let mut crdt = MockPlatformCRDT::new();
449
450        assert!(!crdt.initialized);
451        assert!(MockPlatformCRDT::is_platform_supported());
452
453        assert!(crdt.platform_init().is_ok());
454        assert!(crdt.initialized);
455
456        let capabilities = crdt.platform_capabilities();
457        assert!(capabilities.dma_support);
458        assert!(capabilities.realtime_support);
459        assert!(!capabilities.multicore_support);
460        assert_eq!(capabilities.max_cores, 1);
461
462        assert!(crdt.platform_cleanup().is_ok());
463        assert!(!crdt.initialized);
464    }
465
466    #[test]
467    fn test_platform_alignment() {
468        assert_eq!(MockPlatformCRDT::platform_alignment(), 4);
469        assert_eq!(MockPlatformCRDT::platform_cache_line_size(), 32);
470    }
471
472    #[test]
473    fn test_architecture_types() {
474        assert_eq!(AurixPlatform::ARCHITECTURE, Architecture::TriCore);
475        assert_eq!(STM32Platform::ARCHITECTURE, Architecture::CortexM);
476        assert_eq!(CortexMPlatform::ARCHITECTURE, Architecture::CortexM);
477        assert_eq!(RiscVPlatform::ARCHITECTURE, Architecture::RiscV);
478    }
479}