1use crate::error::QuantRS2Error;
7
8use scirs2_core::ndarray::Array1;
9use scirs2_core::Complex64;
10use serde::{Deserialize, Serialize};
11use std::collections::HashMap;
12use std::sync::{Arc, Mutex, RwLock};
13use std::time::{Duration, Instant, SystemTime};
14use uuid::Uuid;
15
16#[derive(Debug)]
18pub struct QuantumMemory {
19 pub memory_id: Uuid,
20 pub storage_layers: Vec<Arc<dyn QuantumStorageLayer>>,
21 pub cache: Arc<RwLock<QuantumCache>>,
22 pub error_correction: QuantumMemoryErrorCorrection,
23 pub coherence_manager: CoherenceManager,
24 pub access_controller: MemoryAccessController,
25}
26
27pub trait QuantumStorageLayer: Send + Sync + std::fmt::Debug {
29 fn store_state(&self, state_id: Uuid, state: &QuantumState) -> Result<(), QuantRS2Error>;
30 fn retrieve_state(&self, state_id: Uuid) -> Result<Option<QuantumState>, QuantRS2Error>;
31 fn delete_state(&self, state_id: Uuid) -> Result<(), QuantRS2Error>;
32 fn list_states(&self) -> Result<Vec<Uuid>, QuantRS2Error>;
33 fn get_storage_info(&self) -> StorageLayerInfo;
34}
35
36#[derive(Debug, Clone, Serialize, Deserialize)]
37pub struct QuantumState {
38 pub state_id: Uuid,
39 pub amplitudes: Vec<Complex64>,
40 pub qubit_count: usize,
41 pub creation_time: SystemTime,
42 pub last_access: SystemTime,
43 pub coherence_time: Duration,
44 pub fidelity: f64,
45 pub metadata: StateMetadata,
46}
47
48#[derive(Debug, Clone, Serialize, Deserialize)]
49pub struct StateMetadata {
50 pub name: Option<String>,
51 pub description: Option<String>,
52 pub tags: Vec<String>,
53 pub creator: Option<String>,
54 pub access_count: u64,
55 pub compression_ratio: f64,
56 pub entanglement_entropy: f64,
57}
58
59#[derive(Debug, Clone)]
60pub struct StorageLayerInfo {
61 pub layer_type: StorageLayerType,
62 pub capacity: usize, pub latency: Duration,
64 pub reliability: f64,
65 pub energy_cost: f64, }
67
68#[derive(Debug, Clone)]
69pub enum StorageLayerType {
70 UltraFast, Fast, Persistent, Archive, Distributed, }
76
77impl QuantumMemory {
78 pub fn new() -> Self {
80 let memory_id = Uuid::new_v4();
81 let cache = Arc::new(RwLock::new(QuantumCache::new(1000))); Self {
84 memory_id,
85 storage_layers: Vec::new(),
86 cache,
87 error_correction: QuantumMemoryErrorCorrection::new(),
88 coherence_manager: CoherenceManager::new(),
89 access_controller: MemoryAccessController::new(),
90 }
91 }
92
93 pub fn add_storage_layer(&mut self, layer: Arc<dyn QuantumStorageLayer>) {
95 self.storage_layers.push(layer);
96 self.storage_layers.sort_by(|a, b| {
98 a.get_storage_info()
99 .latency
100 .cmp(&b.get_storage_info().latency)
101 });
102 }
103
104 pub async fn store_state(&self, state: QuantumState) -> Result<Uuid, QuantRS2Error> {
106 self.access_controller.check_write_permission(&state)?;
108
109 let encoded_state = self.error_correction.encode_state(&state)?;
111
112 {
114 let mut cache = self.cache.write().unwrap();
115 cache.insert(state.state_id, encoded_state.clone());
116 }
117
118 let target_layer = self.select_storage_layer(&encoded_state).await?;
120 target_layer.store_state(encoded_state.state_id, &encoded_state)?;
121
122 self.coherence_manager
124 .start_tracking(encoded_state.state_id, encoded_state.coherence_time);
125
126 Ok(encoded_state.state_id)
127 }
128
129 pub async fn retrieve_state(
131 &self,
132 state_id: Uuid,
133 ) -> Result<Option<QuantumState>, QuantRS2Error> {
134 self.access_controller.check_read_permission(state_id)?;
136
137 {
139 let mut cache = self.cache.write().unwrap();
140 if let Some(cached_state) = cache.get(&state_id) {
141 self.update_access_stats(state_id).await;
143 return Ok(Some(self.error_correction.decode_state(cached_state)?));
144 }
145 }
146
147 for layer in &self.storage_layers {
149 if let Some(encoded_state) = layer.retrieve_state(state_id)? {
150 if self.coherence_manager.is_coherent(state_id) {
152 let decoded_state = self.error_correction.decode_state(&encoded_state)?;
154
155 {
156 let mut cache = self.cache.write().unwrap();
157 cache.insert(state_id, encoded_state);
158 }
159
160 self.update_access_stats(state_id).await;
161 return Ok(Some(decoded_state));
162 }
163 layer.delete_state(state_id)?;
165 return Err(QuantRS2Error::QuantumDecoherence(format!(
166 "State {} has decoherent",
167 state_id
168 )));
169 }
170 }
171
172 Ok(None)
173 }
174
175 pub async fn delete_state(&self, state_id: Uuid) -> Result<(), QuantRS2Error> {
177 self.access_controller.check_delete_permission(state_id)?;
179
180 {
182 let mut cache = self.cache.write().unwrap();
183 cache.remove(&state_id);
184 }
185
186 for layer in &self.storage_layers {
188 let _ = layer.delete_state(state_id); }
190
191 self.coherence_manager.stop_tracking(state_id);
193
194 Ok(())
195 }
196
197 async fn select_storage_layer(
199 &self,
200 state: &QuantumState,
201 ) -> Result<Arc<dyn QuantumStorageLayer>, QuantRS2Error> {
202 let access_pattern = self.predict_access_pattern(state).await;
204 let _importance_score = self.calculate_importance_score(state);
205
206 for layer in &self.storage_layers {
208 let info = layer.get_storage_info();
209
210 match (&access_pattern, info.layer_type.clone()) {
211 (
212 &AccessPattern::Frequent,
213 StorageLayerType::UltraFast | StorageLayerType::Fast,
214 ) => {
215 return Ok(layer.clone());
216 }
217 (
218 &AccessPattern::Moderate,
219 StorageLayerType::Fast | StorageLayerType::Persistent,
220 ) => {
221 return Ok(layer.clone());
222 }
223 (
224 &AccessPattern::Rare,
225 StorageLayerType::Persistent | StorageLayerType::Archive,
226 ) => {
227 return Ok(layer.clone());
228 }
229 _ => {}
230 }
231 }
232
233 self.storage_layers.first().cloned().ok_or_else(|| {
235 QuantRS2Error::NoStorageAvailable("No storage layers configured".to_string())
236 })
237 }
238
239 async fn predict_access_pattern(&self, state: &QuantumState) -> AccessPattern {
241 let recency_factor = state
245 .last_access
246 .elapsed()
247 .unwrap_or(Duration::ZERO)
248 .as_secs() as f64
249 / 3600.0; let access_frequency = state.metadata.access_count as f64
252 / state
253 .creation_time
254 .elapsed()
255 .unwrap_or(Duration::from_secs(1))
256 .as_secs() as f64;
257
258 if access_frequency > 0.1 && recency_factor < 1.0 {
259 AccessPattern::Frequent
260 } else if access_frequency > 0.01 && recency_factor < 24.0 {
261 AccessPattern::Moderate
262 } else {
263 AccessPattern::Rare
264 }
265 }
266
267 fn calculate_importance_score(&self, state: &QuantumState) -> f64 {
269 let mut score = 0.0;
270
271 score += state.fidelity * 10.0;
273
274 score += state.metadata.entanglement_entropy * 5.0;
276
277 let hours_since_access = state
279 .last_access
280 .elapsed()
281 .unwrap_or(Duration::ZERO)
282 .as_secs() as f64
283 / 3600.0;
284 score += (24.0 - hours_since_access.min(24.0)) / 24.0 * 3.0;
285
286 score += (state.metadata.access_count as f64).ln().max(0.0);
288
289 score
290 }
291
292 async fn update_access_stats(&self, _state_id: Uuid) {
294 }
297
298 pub async fn garbage_collect(&self) -> Result<GarbageCollectionResult, QuantRS2Error> {
300 let mut collected_states = 0;
301 let mut freed_space = 0;
302 let start_time = Instant::now();
303
304 let mut all_states = Vec::new();
306 for layer in &self.storage_layers {
307 let layer_states = layer.list_states()?;
308 all_states.extend(layer_states);
309 }
310
311 for state_id in all_states {
313 if !self.coherence_manager.is_coherent(state_id) {
314 self.delete_state(state_id).await?;
316 collected_states += 1;
317 freed_space += 1; }
319 }
320
321 {
323 let mut cache = self.cache.write().unwrap();
324 cache.compact();
325 }
326
327 Ok(GarbageCollectionResult {
328 collected_states,
329 freed_space,
330 execution_time: start_time.elapsed(),
331 })
332 }
333}
334
335#[derive(Debug)]
337pub struct QuantumCache {
338 cache: HashMap<Uuid, QuantumState>,
339 access_order: Vec<Uuid>,
340 max_size: usize,
341}
342
343impl QuantumCache {
344 pub fn new(max_size: usize) -> Self {
345 Self {
346 cache: HashMap::new(),
347 access_order: Vec::new(),
348 max_size,
349 }
350 }
351
352 pub fn insert(&mut self, state_id: Uuid, state: QuantumState) {
353 if self.cache.contains_key(&state_id) {
355 self.remove(&state_id);
356 }
357
358 self.cache.insert(state_id, state);
360 self.access_order.push(state_id);
361
362 while self.cache.len() > self.max_size {
364 if let Some(oldest) = self.access_order.first().cloned() {
365 self.remove(&oldest);
366 }
367 }
368 }
369
370 pub fn get(&mut self, state_id: &Uuid) -> Option<&QuantumState> {
371 if self.cache.contains_key(state_id) {
372 self.access_order.retain(|&id| id != *state_id);
374 self.access_order.push(*state_id);
375 self.cache.get(state_id)
376 } else {
377 None
378 }
379 }
380
381 pub fn remove(&mut self, state_id: &Uuid) {
382 self.cache.remove(state_id);
383 self.access_order.retain(|&id| id != *state_id);
384 }
385
386 pub fn compact(&mut self) {
387 self.access_order.retain(|id| self.cache.contains_key(id));
389 }
390}
391
392#[derive(Debug)]
394pub struct QuantumMemoryErrorCorrection {
395 pub code_type: QuantumErrorCode,
396 pub syndrome_table: HashMap<Vec<bool>, Array1<Complex64>>,
397 pub encoding_overhead: f64,
398}
399
400#[derive(Debug, Clone)]
401pub enum QuantumErrorCode {
402 ShorCode,
403 SteaneCode,
404 SurfaceCode {
405 distance: usize,
406 },
407 ColorCode {
408 distance: usize,
409 },
410 Custom {
411 name: String,
412 parameters: HashMap<String, f64>,
413 },
414}
415
416impl QuantumMemoryErrorCorrection {
417 pub fn new() -> Self {
418 Self {
419 code_type: QuantumErrorCode::SteaneCode,
420 syndrome_table: HashMap::new(),
421 encoding_overhead: 7.0, }
423 }
424
425 pub fn encode_state(&self, state: &QuantumState) -> Result<QuantumState, QuantRS2Error> {
427 match &self.code_type {
428 QuantumErrorCode::SteaneCode => self.encode_steane(state),
429 QuantumErrorCode::ShorCode => self.encode_shor(state),
430 QuantumErrorCode::SurfaceCode { distance } => self.encode_surface(state, *distance),
431 QuantumErrorCode::ColorCode { distance } => self.encode_color(state, *distance),
432 QuantumErrorCode::Custom { .. } => self.encode_custom(state),
433 }
434 }
435
436 pub fn decode_state(
438 &self,
439 encoded_state: &QuantumState,
440 ) -> Result<QuantumState, QuantRS2Error> {
441 match &self.code_type {
442 QuantumErrorCode::SteaneCode => self.decode_steane(encoded_state),
443 QuantumErrorCode::ShorCode => self.decode_shor(encoded_state),
444 QuantumErrorCode::SurfaceCode { distance } => {
445 self.decode_surface(encoded_state, *distance)
446 }
447 QuantumErrorCode::ColorCode { distance } => self.decode_color(encoded_state, *distance),
448 QuantumErrorCode::Custom { .. } => self.decode_custom(encoded_state),
449 }
450 }
451
452 fn encode_steane(&self, state: &QuantumState) -> Result<QuantumState, QuantRS2Error> {
454 let encoded_amplitudes = self.apply_steane_encoding(&state.amplitudes)?;
456
457 Ok(QuantumState {
458 state_id: state.state_id,
459 amplitudes: encoded_amplitudes,
460 qubit_count: state.qubit_count * 7, creation_time: state.creation_time,
462 last_access: SystemTime::now(),
463 coherence_time: state.coherence_time,
464 fidelity: state.fidelity * 0.99, metadata: state.metadata.clone(),
466 })
467 }
468
469 fn apply_steane_encoding(
471 &self,
472 amplitudes: &[Complex64],
473 ) -> Result<Vec<Complex64>, QuantRS2Error> {
474 let mut encoded = Vec::new();
476
477 for amp in amplitudes {
478 for _ in 0..7 {
480 encoded.push(*amp / (7.0_f64.sqrt()));
481 }
482 }
483
484 Ok(encoded)
485 }
486
487 fn decode_steane(&self, encoded_state: &QuantumState) -> Result<QuantumState, QuantRS2Error> {
489 let decoded_amplitudes = self.apply_steane_decoding(&encoded_state.amplitudes)?;
491
492 Ok(QuantumState {
493 state_id: encoded_state.state_id,
494 amplitudes: decoded_amplitudes,
495 qubit_count: encoded_state.qubit_count / 7,
496 creation_time: encoded_state.creation_time,
497 last_access: SystemTime::now(),
498 coherence_time: encoded_state.coherence_time,
499 fidelity: encoded_state.fidelity,
500 metadata: encoded_state.metadata.clone(),
501 })
502 }
503
504 fn apply_steane_decoding(
506 &self,
507 encoded_amplitudes: &[Complex64],
508 ) -> Result<Vec<Complex64>, QuantRS2Error> {
509 let mut decoded = Vec::new();
511
512 for chunk in encoded_amplitudes.chunks(7) {
513 if chunk.len() == 7 {
514 let recovered_amp = chunk.iter().sum::<Complex64>() / Complex64::new(7.0, 0.0)
516 * Complex64::new(7.0_f64.sqrt(), 0.0);
517 decoded.push(recovered_amp);
518 }
519 }
520
521 Ok(decoded)
522 }
523
524 fn encode_shor(&self, state: &QuantumState) -> Result<QuantumState, QuantRS2Error> {
526 let mut encoded_state = state.clone();
528 encoded_state.qubit_count *= 9;
529 Ok(encoded_state)
530 }
531
532 fn decode_shor(&self, encoded_state: &QuantumState) -> Result<QuantumState, QuantRS2Error> {
533 let mut decoded_state = encoded_state.clone();
534 decoded_state.qubit_count /= 9;
535 Ok(decoded_state)
536 }
537
538 fn encode_surface(
539 &self,
540 state: &QuantumState,
541 distance: usize,
542 ) -> Result<QuantumState, QuantRS2Error> {
543 let mut encoded_state = state.clone();
544 encoded_state.qubit_count *= distance * distance;
545 Ok(encoded_state)
546 }
547
548 fn decode_surface(
549 &self,
550 encoded_state: &QuantumState,
551 distance: usize,
552 ) -> Result<QuantumState, QuantRS2Error> {
553 let mut decoded_state = encoded_state.clone();
554 decoded_state.qubit_count /= distance * distance;
555 Ok(decoded_state)
556 }
557
558 fn encode_color(
559 &self,
560 state: &QuantumState,
561 distance: usize,
562 ) -> Result<QuantumState, QuantRS2Error> {
563 let mut encoded_state = state.clone();
564 encoded_state.qubit_count *= distance * distance * 2;
565 Ok(encoded_state)
566 }
567
568 fn decode_color(
569 &self,
570 encoded_state: &QuantumState,
571 distance: usize,
572 ) -> Result<QuantumState, QuantRS2Error> {
573 let mut decoded_state = encoded_state.clone();
574 decoded_state.qubit_count /= distance * distance * 2;
575 Ok(decoded_state)
576 }
577
578 fn encode_custom(&self, state: &QuantumState) -> Result<QuantumState, QuantRS2Error> {
579 Ok(state.clone())
580 }
581
582 fn decode_custom(&self, encoded_state: &QuantumState) -> Result<QuantumState, QuantRS2Error> {
583 Ok(encoded_state.clone())
584 }
585}
586
587#[derive(Debug)]
589pub struct CoherenceManager {
590 coherence_tracking: Arc<Mutex<HashMap<Uuid, CoherenceInfo>>>,
591}
592
593#[derive(Debug, Clone)]
594pub struct CoherenceInfo {
595 pub creation_time: Instant,
596 pub coherence_time: Duration,
597 pub last_check: Instant,
598 pub predicted_fidelity: f64,
599}
600
601impl CoherenceManager {
602 pub fn new() -> Self {
603 Self {
604 coherence_tracking: Arc::new(Mutex::new(HashMap::new())),
605 }
606 }
607
608 pub fn start_tracking(&self, state_id: Uuid, coherence_time: Duration) {
610 let info = CoherenceInfo {
611 creation_time: Instant::now(),
612 coherence_time,
613 last_check: Instant::now(),
614 predicted_fidelity: 1.0,
615 };
616
617 self.coherence_tracking
618 .lock()
619 .unwrap()
620 .insert(state_id, info);
621 }
622
623 pub fn stop_tracking(&self, state_id: Uuid) {
625 self.coherence_tracking.lock().unwrap().remove(&state_id);
626 }
627
628 pub fn is_coherent(&self, state_id: Uuid) -> bool {
630 if let Some(info) = self.coherence_tracking.lock().unwrap().get(&state_id) {
631 let elapsed = info.creation_time.elapsed();
632 elapsed < info.coherence_time
633 } else {
634 false }
636 }
637
638 pub fn get_predicted_fidelity(&self, state_id: Uuid) -> f64 {
640 if let Some(info) = self.coherence_tracking.lock().unwrap().get(&state_id) {
641 let elapsed = info.creation_time.elapsed();
642 let decay_factor = elapsed.as_secs_f64() / info.coherence_time.as_secs_f64();
643
644 (1.0 - decay_factor).max(0.0)
646 } else {
647 0.0
648 }
649 }
650}
651
652#[derive(Debug)]
654pub struct MemoryAccessController {
655 permissions: Arc<RwLock<HashMap<Uuid, StatePermissions>>>,
656 access_log: Arc<Mutex<Vec<AccessLogEntry>>>,
657}
658
659#[derive(Debug, Clone)]
660pub struct StatePermissions {
661 pub read: bool,
662 pub write: bool,
663 pub delete: bool,
664 pub owner: Option<String>,
665 pub authorized_users: Vec<String>,
666}
667
668#[derive(Debug, Clone)]
669pub struct AccessLogEntry {
670 pub timestamp: SystemTime,
671 pub state_id: Uuid,
672 pub operation: AccessOperation,
673 pub user: Option<String>,
674 pub success: bool,
675}
676
677#[derive(Debug, Clone)]
678pub enum AccessOperation {
679 Read,
680 Write,
681 Delete,
682}
683
684impl MemoryAccessController {
685 pub fn new() -> Self {
686 Self {
687 permissions: Arc::new(RwLock::new(HashMap::new())),
688 access_log: Arc::new(Mutex::new(Vec::new())),
689 }
690 }
691
692 pub fn check_read_permission(&self, state_id: Uuid) -> Result<(), QuantRS2Error> {
694 let permissions = self.permissions.read().unwrap();
695 if let Some(perms) = permissions.get(&state_id) {
696 if perms.read {
697 self.log_access(state_id, AccessOperation::Read, true);
698 Ok(())
699 } else {
700 self.log_access(state_id, AccessOperation::Read, false);
701 Err(QuantRS2Error::AccessDenied(
702 "Read access denied".to_string(),
703 ))
704 }
705 } else {
706 Ok(())
708 }
709 }
710
711 pub fn check_write_permission(&self, state: &QuantumState) -> Result<(), QuantRS2Error> {
713 let permissions = self.permissions.read().unwrap();
714 if let Some(perms) = permissions.get(&state.state_id) {
715 if perms.write {
716 self.log_access(state.state_id, AccessOperation::Write, true);
717 Ok(())
718 } else {
719 self.log_access(state.state_id, AccessOperation::Write, false);
720 Err(QuantRS2Error::AccessDenied(
721 "Write access denied".to_string(),
722 ))
723 }
724 } else {
725 Ok(())
727 }
728 }
729
730 pub fn check_delete_permission(&self, state_id: Uuid) -> Result<(), QuantRS2Error> {
732 let permissions = self.permissions.read().unwrap();
733 if let Some(perms) = permissions.get(&state_id) {
734 if perms.delete {
735 self.log_access(state_id, AccessOperation::Delete, true);
736 Ok(())
737 } else {
738 self.log_access(state_id, AccessOperation::Delete, false);
739 Err(QuantRS2Error::AccessDenied(
740 "Delete access denied".to_string(),
741 ))
742 }
743 } else {
744 Ok(())
746 }
747 }
748
749 fn log_access(&self, state_id: Uuid, operation: AccessOperation, success: bool) {
751 let entry = AccessLogEntry {
752 timestamp: SystemTime::now(),
753 state_id,
754 operation,
755 user: None, success,
757 };
758
759 self.access_log.lock().unwrap().push(entry);
760 }
761}
762
763#[derive(Debug)]
765pub struct InMemoryStorage {
766 states: Arc<RwLock<HashMap<Uuid, QuantumState>>>,
767 info: StorageLayerInfo,
768}
769
770impl InMemoryStorage {
771 pub fn new(capacity: usize) -> Self {
772 Self {
773 states: Arc::new(RwLock::new(HashMap::new())),
774 info: StorageLayerInfo {
775 layer_type: StorageLayerType::UltraFast,
776 capacity,
777 latency: Duration::from_nanos(100),
778 reliability: 0.99999,
779 energy_cost: 1.0,
780 },
781 }
782 }
783}
784
785impl QuantumStorageLayer for InMemoryStorage {
786 fn store_state(&self, state_id: Uuid, state: &QuantumState) -> Result<(), QuantRS2Error> {
787 let mut states = self.states.write().unwrap();
788 if states.len() >= self.info.capacity {
789 return Err(QuantRS2Error::StorageCapacityExceeded(
790 "Memory storage full".to_string(),
791 ));
792 }
793 states.insert(state_id, state.clone());
794 Ok(())
795 }
796
797 fn retrieve_state(&self, state_id: Uuid) -> Result<Option<QuantumState>, QuantRS2Error> {
798 let states = self.states.read().unwrap();
799 Ok(states.get(&state_id).cloned())
800 }
801
802 fn delete_state(&self, state_id: Uuid) -> Result<(), QuantRS2Error> {
803 let mut states = self.states.write().unwrap();
804 states.remove(&state_id);
805 Ok(())
806 }
807
808 fn list_states(&self) -> Result<Vec<Uuid>, QuantRS2Error> {
809 let states = self.states.read().unwrap();
810 Ok(states.keys().cloned().collect())
811 }
812
813 fn get_storage_info(&self) -> StorageLayerInfo {
814 self.info.clone()
815 }
816}
817
818#[derive(Debug, Clone)]
820pub enum AccessPattern {
821 Frequent,
822 Moderate,
823 Rare,
824}
825
826#[derive(Debug)]
827pub struct GarbageCollectionResult {
828 pub collected_states: usize,
829 pub freed_space: usize,
830 pub execution_time: Duration,
831}
832
833#[cfg(test)]
834mod tests {
835 use super::*;
836
837 #[tokio::test]
838 async fn test_quantum_memory_creation() {
839 let memory = QuantumMemory::new();
840 assert_eq!(memory.storage_layers.len(), 0);
841 }
842
843 #[tokio::test]
844 async fn test_in_memory_storage() {
845 let storage = InMemoryStorage::new(100);
846
847 let state = QuantumState {
848 state_id: Uuid::new_v4(),
849 amplitudes: vec![Complex64::new(1.0, 0.0), Complex64::new(0.0, 0.0)],
850 qubit_count: 1,
851 creation_time: SystemTime::now(),
852 last_access: SystemTime::now(),
853 coherence_time: Duration::from_millis(100),
854 fidelity: 0.99,
855 metadata: StateMetadata {
856 name: Some("test_state".to_string()),
857 description: None,
858 tags: vec!["test".to_string()],
859 creator: None,
860 access_count: 0,
861 compression_ratio: 1.0,
862 entanglement_entropy: 0.0,
863 },
864 };
865
866 let state_id = state.state_id;
867 storage.store_state(state_id, &state).unwrap();
868
869 let retrieved = storage.retrieve_state(state_id).unwrap();
870 assert!(retrieved.is_some());
871 assert_eq!(retrieved.unwrap().state_id, state_id);
872 }
873
874 #[tokio::test]
875 async fn test_quantum_cache() {
876 let mut cache = QuantumCache::new(2);
877
878 let state1 = QuantumState {
879 state_id: Uuid::new_v4(),
880 amplitudes: vec![Complex64::new(1.0, 0.0)],
881 qubit_count: 1,
882 creation_time: SystemTime::now(),
883 last_access: SystemTime::now(),
884 coherence_time: Duration::from_millis(100),
885 fidelity: 0.99,
886 metadata: StateMetadata {
887 name: None,
888 description: None,
889 tags: Vec::new(),
890 creator: None,
891 access_count: 0,
892 compression_ratio: 1.0,
893 entanglement_entropy: 0.0,
894 },
895 };
896
897 let state2 = QuantumState {
898 state_id: Uuid::new_v4(),
899 ..state1.clone()
900 };
901
902 let state3 = QuantumState {
903 state_id: Uuid::new_v4(),
904 ..state1.clone()
905 };
906
907 cache.insert(state1.state_id, state1.clone());
908 cache.insert(state2.state_id, state2.clone());
909 assert_eq!(cache.cache.len(), 2);
910
911 cache.insert(state3.state_id, state3.clone());
913 assert_eq!(cache.cache.len(), 2);
914 assert!(!cache.cache.contains_key(&state1.state_id));
915 }
916
917 #[tokio::test]
918 async fn test_coherence_manager() {
919 let manager = CoherenceManager::new();
920 let state_id = Uuid::new_v4();
921
922 manager.start_tracking(state_id, Duration::from_millis(100));
923 assert!(manager.is_coherent(state_id));
924
925 tokio::time::sleep(Duration::from_millis(150)).await;
927 assert!(!manager.is_coherent(state_id));
928 }
929}