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 if let Ok(mut cache) = self.cache.write() {
114 cache.insert(state.state_id, encoded_state.clone());
115 }
116
117 let target_layer = self.select_storage_layer(&encoded_state).await?;
119 target_layer.store_state(encoded_state.state_id, &encoded_state)?;
120
121 self.coherence_manager
123 .start_tracking(encoded_state.state_id, encoded_state.coherence_time);
124
125 Ok(encoded_state.state_id)
126 }
127
128 pub async fn retrieve_state(
130 &self,
131 state_id: Uuid,
132 ) -> Result<Option<QuantumState>, QuantRS2Error> {
133 self.access_controller.check_read_permission(state_id)?;
135
136 if let Ok(mut cache) = self.cache.write() {
138 if let Some(cached_state) = cache.get(&state_id) {
139 self.update_access_stats(state_id).await;
141 return Ok(Some(self.error_correction.decode_state(cached_state)?));
142 }
143 }
144
145 for layer in &self.storage_layers {
147 if let Some(encoded_state) = layer.retrieve_state(state_id)? {
148 if self.coherence_manager.is_coherent(state_id) {
150 let decoded_state = self.error_correction.decode_state(&encoded_state)?;
152
153 if let Ok(mut cache) = self.cache.write() {
154 cache.insert(state_id, encoded_state);
155 }
156
157 self.update_access_stats(state_id).await;
158 return Ok(Some(decoded_state));
159 }
160 layer.delete_state(state_id)?;
162 return Err(QuantRS2Error::QuantumDecoherence(format!(
163 "State {state_id} has decoherent"
164 )));
165 }
166 }
167
168 Ok(None)
169 }
170
171 pub async fn delete_state(&self, state_id: Uuid) -> Result<(), QuantRS2Error> {
173 self.access_controller.check_delete_permission(state_id)?;
175
176 if let Ok(mut cache) = self.cache.write() {
178 cache.remove(&state_id);
179 }
180
181 for layer in &self.storage_layers {
183 let _ = layer.delete_state(state_id); }
185
186 self.coherence_manager.stop_tracking(state_id);
188
189 Ok(())
190 }
191
192 async fn select_storage_layer(
194 &self,
195 state: &QuantumState,
196 ) -> Result<Arc<dyn QuantumStorageLayer>, QuantRS2Error> {
197 let access_pattern = self.predict_access_pattern(state).await;
199 let _importance_score = self.calculate_importance_score(state);
200
201 for layer in &self.storage_layers {
203 let info = layer.get_storage_info();
204
205 match (&access_pattern, info.layer_type.clone()) {
206 (
207 &AccessPattern::Frequent,
208 StorageLayerType::UltraFast | StorageLayerType::Fast,
209 )
210 | (
211 &AccessPattern::Moderate,
212 StorageLayerType::Fast | StorageLayerType::Persistent,
213 )
214 | (
215 &AccessPattern::Rare,
216 StorageLayerType::Persistent | StorageLayerType::Archive,
217 ) => {
218 return Ok(layer.clone());
219 }
220 _ => {}
221 }
222 }
223
224 self.storage_layers.first().cloned().ok_or_else(|| {
226 QuantRS2Error::NoStorageAvailable("No storage layers configured".to_string())
227 })
228 }
229
230 async fn predict_access_pattern(&self, state: &QuantumState) -> AccessPattern {
232 let recency_factor = state
236 .last_access
237 .elapsed()
238 .unwrap_or(Duration::ZERO)
239 .as_secs() as f64
240 / 3600.0; let access_frequency = state.metadata.access_count as f64
243 / state
244 .creation_time
245 .elapsed()
246 .unwrap_or(Duration::from_secs(1))
247 .as_secs() as f64;
248
249 if access_frequency > 0.1 && recency_factor < 1.0 {
250 AccessPattern::Frequent
251 } else if access_frequency > 0.01 && recency_factor < 24.0 {
252 AccessPattern::Moderate
253 } else {
254 AccessPattern::Rare
255 }
256 }
257
258 fn calculate_importance_score(&self, state: &QuantumState) -> f64 {
260 let mut score = 0.0;
261
262 score += state.fidelity * 10.0;
264
265 score += state.metadata.entanglement_entropy * 5.0;
267
268 let hours_since_access = state
270 .last_access
271 .elapsed()
272 .unwrap_or(Duration::ZERO)
273 .as_secs() as f64
274 / 3600.0;
275 score += (24.0 - hours_since_access.min(24.0)) / 24.0 * 3.0;
276
277 score += (state.metadata.access_count as f64).ln().max(0.0);
279
280 score
281 }
282
283 async fn update_access_stats(&self, _state_id: Uuid) {
285 }
288
289 pub async fn garbage_collect(&self) -> Result<GarbageCollectionResult, QuantRS2Error> {
291 let mut collected_states = 0;
292 let mut freed_space = 0;
293 let start_time = Instant::now();
294
295 let mut all_states = Vec::new();
297 for layer in &self.storage_layers {
298 let layer_states = layer.list_states()?;
299 all_states.extend(layer_states);
300 }
301
302 for state_id in all_states {
304 if !self.coherence_manager.is_coherent(state_id) {
305 self.delete_state(state_id).await?;
307 collected_states += 1;
308 freed_space += 1; }
310 }
311
312 if let Ok(mut cache) = self.cache.write() {
314 cache.compact();
315 }
316
317 Ok(GarbageCollectionResult {
318 collected_states,
319 freed_space,
320 execution_time: start_time.elapsed(),
321 })
322 }
323}
324
325#[derive(Debug)]
327pub struct QuantumCache {
328 cache: HashMap<Uuid, QuantumState>,
329 access_order: Vec<Uuid>,
330 max_size: usize,
331}
332
333impl QuantumCache {
334 pub fn new(max_size: usize) -> Self {
335 Self {
336 cache: HashMap::new(),
337 access_order: Vec::new(),
338 max_size,
339 }
340 }
341
342 pub fn insert(&mut self, state_id: Uuid, state: QuantumState) {
343 if self.cache.contains_key(&state_id) {
345 self.remove(&state_id);
346 }
347
348 self.cache.insert(state_id, state);
350 self.access_order.push(state_id);
351
352 while self.cache.len() > self.max_size {
354 if let Some(oldest) = self.access_order.first().copied() {
355 self.remove(&oldest);
356 }
357 }
358 }
359
360 pub fn get(&mut self, state_id: &Uuid) -> Option<&QuantumState> {
361 if self.cache.contains_key(state_id) {
362 self.access_order.retain(|&id| id != *state_id);
364 self.access_order.push(*state_id);
365 self.cache.get(state_id)
366 } else {
367 None
368 }
369 }
370
371 pub fn remove(&mut self, state_id: &Uuid) {
372 self.cache.remove(state_id);
373 self.access_order.retain(|&id| id != *state_id);
374 }
375
376 pub fn compact(&mut self) {
377 self.access_order.retain(|id| self.cache.contains_key(id));
379 }
380}
381
382#[derive(Debug)]
384pub struct QuantumMemoryErrorCorrection {
385 pub code_type: QuantumErrorCode,
386 pub syndrome_table: HashMap<Vec<bool>, Array1<Complex64>>,
387 pub encoding_overhead: f64,
388}
389
390#[derive(Debug, Clone)]
391pub enum QuantumErrorCode {
392 ShorCode,
393 SteaneCode,
394 SurfaceCode {
395 distance: usize,
396 },
397 ColorCode {
398 distance: usize,
399 },
400 Custom {
401 name: String,
402 parameters: HashMap<String, f64>,
403 },
404}
405
406impl QuantumMemoryErrorCorrection {
407 pub fn new() -> Self {
408 Self {
409 code_type: QuantumErrorCode::SteaneCode,
410 syndrome_table: HashMap::new(),
411 encoding_overhead: 7.0, }
413 }
414
415 pub fn encode_state(&self, state: &QuantumState) -> Result<QuantumState, QuantRS2Error> {
417 match &self.code_type {
418 QuantumErrorCode::SteaneCode => self.encode_steane(state),
419 QuantumErrorCode::ShorCode => self.encode_shor(state),
420 QuantumErrorCode::SurfaceCode { distance } => self.encode_surface(state, *distance),
421 QuantumErrorCode::ColorCode { distance } => self.encode_color(state, *distance),
422 QuantumErrorCode::Custom { .. } => self.encode_custom(state),
423 }
424 }
425
426 pub fn decode_state(
428 &self,
429 encoded_state: &QuantumState,
430 ) -> Result<QuantumState, QuantRS2Error> {
431 match &self.code_type {
432 QuantumErrorCode::SteaneCode => self.decode_steane(encoded_state),
433 QuantumErrorCode::ShorCode => self.decode_shor(encoded_state),
434 QuantumErrorCode::SurfaceCode { distance } => {
435 self.decode_surface(encoded_state, *distance)
436 }
437 QuantumErrorCode::ColorCode { distance } => self.decode_color(encoded_state, *distance),
438 QuantumErrorCode::Custom { .. } => self.decode_custom(encoded_state),
439 }
440 }
441
442 fn encode_steane(&self, state: &QuantumState) -> Result<QuantumState, QuantRS2Error> {
444 let encoded_amplitudes = self.apply_steane_encoding(&state.amplitudes)?;
446
447 Ok(QuantumState {
448 state_id: state.state_id,
449 amplitudes: encoded_amplitudes,
450 qubit_count: state.qubit_count * 7, creation_time: state.creation_time,
452 last_access: SystemTime::now(),
453 coherence_time: state.coherence_time,
454 fidelity: state.fidelity * 0.99, metadata: state.metadata.clone(),
456 })
457 }
458
459 fn apply_steane_encoding(
461 &self,
462 amplitudes: &[Complex64],
463 ) -> Result<Vec<Complex64>, QuantRS2Error> {
464 let mut encoded = Vec::new();
466
467 for amp in amplitudes {
468 for _ in 0..7 {
470 encoded.push(*amp / (7.0_f64.sqrt()));
471 }
472 }
473
474 Ok(encoded)
475 }
476
477 fn decode_steane(&self, encoded_state: &QuantumState) -> Result<QuantumState, QuantRS2Error> {
479 let decoded_amplitudes = self.apply_steane_decoding(&encoded_state.amplitudes)?;
481
482 Ok(QuantumState {
483 state_id: encoded_state.state_id,
484 amplitudes: decoded_amplitudes,
485 qubit_count: encoded_state.qubit_count / 7,
486 creation_time: encoded_state.creation_time,
487 last_access: SystemTime::now(),
488 coherence_time: encoded_state.coherence_time,
489 fidelity: encoded_state.fidelity,
490 metadata: encoded_state.metadata.clone(),
491 })
492 }
493
494 fn apply_steane_decoding(
496 &self,
497 encoded_amplitudes: &[Complex64],
498 ) -> Result<Vec<Complex64>, QuantRS2Error> {
499 let mut decoded = Vec::new();
501
502 for chunk in encoded_amplitudes.chunks(7) {
503 if chunk.len() == 7 {
504 let recovered_amp = chunk.iter().sum::<Complex64>() / Complex64::new(7.0, 0.0)
506 * Complex64::new(7.0_f64.sqrt(), 0.0);
507 decoded.push(recovered_amp);
508 }
509 }
510
511 Ok(decoded)
512 }
513
514 fn encode_shor(&self, state: &QuantumState) -> Result<QuantumState, QuantRS2Error> {
516 let mut encoded_state = state.clone();
518 encoded_state.qubit_count *= 9;
519 Ok(encoded_state)
520 }
521
522 fn decode_shor(&self, encoded_state: &QuantumState) -> Result<QuantumState, QuantRS2Error> {
523 let mut decoded_state = encoded_state.clone();
524 decoded_state.qubit_count /= 9;
525 Ok(decoded_state)
526 }
527
528 fn encode_surface(
529 &self,
530 state: &QuantumState,
531 distance: usize,
532 ) -> Result<QuantumState, QuantRS2Error> {
533 let mut encoded_state = state.clone();
534 encoded_state.qubit_count *= distance * distance;
535 Ok(encoded_state)
536 }
537
538 fn decode_surface(
539 &self,
540 encoded_state: &QuantumState,
541 distance: usize,
542 ) -> Result<QuantumState, QuantRS2Error> {
543 let mut decoded_state = encoded_state.clone();
544 decoded_state.qubit_count /= distance * distance;
545 Ok(decoded_state)
546 }
547
548 fn encode_color(
549 &self,
550 state: &QuantumState,
551 distance: usize,
552 ) -> Result<QuantumState, QuantRS2Error> {
553 let mut encoded_state = state.clone();
554 encoded_state.qubit_count *= distance * distance * 2;
555 Ok(encoded_state)
556 }
557
558 fn decode_color(
559 &self,
560 encoded_state: &QuantumState,
561 distance: usize,
562 ) -> Result<QuantumState, QuantRS2Error> {
563 let mut decoded_state = encoded_state.clone();
564 decoded_state.qubit_count /= distance * distance * 2;
565 Ok(decoded_state)
566 }
567
568 fn encode_custom(&self, state: &QuantumState) -> Result<QuantumState, QuantRS2Error> {
569 Ok(state.clone())
570 }
571
572 fn decode_custom(&self, encoded_state: &QuantumState) -> Result<QuantumState, QuantRS2Error> {
573 Ok(encoded_state.clone())
574 }
575}
576
577#[derive(Debug)]
579pub struct CoherenceManager {
580 coherence_tracking: Arc<Mutex<HashMap<Uuid, CoherenceInfo>>>,
581}
582
583#[derive(Debug, Clone)]
584pub struct CoherenceInfo {
585 pub creation_time: Instant,
586 pub coherence_time: Duration,
587 pub last_check: Instant,
588 pub predicted_fidelity: f64,
589}
590
591impl CoherenceManager {
592 pub fn new() -> Self {
593 Self {
594 coherence_tracking: Arc::new(Mutex::new(HashMap::new())),
595 }
596 }
597
598 pub fn start_tracking(&self, state_id: Uuid, coherence_time: Duration) {
600 let info = CoherenceInfo {
601 creation_time: Instant::now(),
602 coherence_time,
603 last_check: Instant::now(),
604 predicted_fidelity: 1.0,
605 };
606
607 if let Ok(mut tracking) = self.coherence_tracking.lock() {
608 tracking.insert(state_id, info);
609 }
610 }
611
612 pub fn stop_tracking(&self, state_id: Uuid) {
614 if let Ok(mut tracking) = self.coherence_tracking.lock() {
615 tracking.remove(&state_id);
616 }
617 }
618
619 pub fn is_coherent(&self, state_id: Uuid) -> bool {
621 if let Ok(tracking) = self.coherence_tracking.lock() {
622 if let Some(info) = tracking.get(&state_id) {
623 let elapsed = info.creation_time.elapsed();
624 return elapsed < info.coherence_time;
625 }
626 }
627 false }
629
630 pub fn get_predicted_fidelity(&self, state_id: Uuid) -> f64 {
632 if let Ok(tracking) = self.coherence_tracking.lock() {
633 if let Some(info) = tracking.get(&state_id) {
634 let elapsed = info.creation_time.elapsed();
635 let decay_factor = elapsed.as_secs_f64() / info.coherence_time.as_secs_f64();
636
637 return (1.0 - decay_factor).max(0.0);
639 }
640 }
641 0.0
642 }
643}
644
645#[derive(Debug)]
647pub struct MemoryAccessController {
648 permissions: Arc<RwLock<HashMap<Uuid, StatePermissions>>>,
649 access_log: Arc<Mutex<Vec<AccessLogEntry>>>,
650}
651
652#[derive(Debug, Clone)]
653pub struct StatePermissions {
654 pub read: bool,
655 pub write: bool,
656 pub delete: bool,
657 pub owner: Option<String>,
658 pub authorized_users: Vec<String>,
659}
660
661#[derive(Debug, Clone)]
662pub struct AccessLogEntry {
663 pub timestamp: SystemTime,
664 pub state_id: Uuid,
665 pub operation: AccessOperation,
666 pub user: Option<String>,
667 pub success: bool,
668}
669
670#[derive(Debug, Clone)]
671pub enum AccessOperation {
672 Read,
673 Write,
674 Delete,
675}
676
677impl MemoryAccessController {
678 pub fn new() -> Self {
679 Self {
680 permissions: Arc::new(RwLock::new(HashMap::new())),
681 access_log: Arc::new(Mutex::new(Vec::new())),
682 }
683 }
684
685 pub fn check_read_permission(&self, state_id: Uuid) -> Result<(), QuantRS2Error> {
687 let permissions = self
688 .permissions
689 .read()
690 .map_err(|_| QuantRS2Error::LockPoisoned("permissions lock poisoned".to_string()))?;
691 if let Some(perms) = permissions.get(&state_id) {
692 if perms.read {
693 self.log_access(state_id, AccessOperation::Read, true);
694 Ok(())
695 } else {
696 self.log_access(state_id, AccessOperation::Read, false);
697 Err(QuantRS2Error::AccessDenied(
698 "Read access denied".to_string(),
699 ))
700 }
701 } else {
702 Ok(())
704 }
705 }
706
707 pub fn check_write_permission(&self, state: &QuantumState) -> Result<(), QuantRS2Error> {
709 let permissions = self
710 .permissions
711 .read()
712 .map_err(|_| QuantRS2Error::LockPoisoned("permissions lock poisoned".to_string()))?;
713 if let Some(perms) = permissions.get(&state.state_id) {
714 if perms.write {
715 self.log_access(state.state_id, AccessOperation::Write, true);
716 Ok(())
717 } else {
718 self.log_access(state.state_id, AccessOperation::Write, false);
719 Err(QuantRS2Error::AccessDenied(
720 "Write access denied".to_string(),
721 ))
722 }
723 } else {
724 Ok(())
726 }
727 }
728
729 pub fn check_delete_permission(&self, state_id: Uuid) -> Result<(), QuantRS2Error> {
731 let permissions = self
732 .permissions
733 .read()
734 .map_err(|_| QuantRS2Error::LockPoisoned("permissions lock poisoned".to_string()))?;
735 if let Some(perms) = permissions.get(&state_id) {
736 if perms.delete {
737 self.log_access(state_id, AccessOperation::Delete, true);
738 Ok(())
739 } else {
740 self.log_access(state_id, AccessOperation::Delete, false);
741 Err(QuantRS2Error::AccessDenied(
742 "Delete access denied".to_string(),
743 ))
744 }
745 } else {
746 Ok(())
748 }
749 }
750
751 fn log_access(&self, state_id: Uuid, operation: AccessOperation, success: bool) {
753 let entry = AccessLogEntry {
754 timestamp: SystemTime::now(),
755 state_id,
756 operation,
757 user: None, success,
759 };
760
761 if let Ok(mut log) = self.access_log.lock() {
762 log.push(entry);
763 }
764 }
765}
766
767#[derive(Debug)]
769pub struct InMemoryStorage {
770 states: Arc<RwLock<HashMap<Uuid, QuantumState>>>,
771 info: StorageLayerInfo,
772}
773
774impl InMemoryStorage {
775 pub fn new(capacity: usize) -> Self {
776 Self {
777 states: Arc::new(RwLock::new(HashMap::new())),
778 info: StorageLayerInfo {
779 layer_type: StorageLayerType::UltraFast,
780 capacity,
781 latency: Duration::from_nanos(100),
782 reliability: 0.99999,
783 energy_cost: 1.0,
784 },
785 }
786 }
787}
788
789impl QuantumStorageLayer for InMemoryStorage {
790 fn store_state(&self, state_id: Uuid, state: &QuantumState) -> Result<(), QuantRS2Error> {
791 let mut states = self
792 .states
793 .write()
794 .map_err(|_| QuantRS2Error::LockPoisoned("states lock poisoned".to_string()))?;
795 if states.len() >= self.info.capacity {
796 return Err(QuantRS2Error::StorageCapacityExceeded(
797 "Memory storage full".to_string(),
798 ));
799 }
800 states.insert(state_id, state.clone());
801 Ok(())
802 }
803
804 fn retrieve_state(&self, state_id: Uuid) -> Result<Option<QuantumState>, QuantRS2Error> {
805 let states = self
806 .states
807 .read()
808 .map_err(|_| QuantRS2Error::LockPoisoned("states lock poisoned".to_string()))?;
809 Ok(states.get(&state_id).cloned())
810 }
811
812 fn delete_state(&self, state_id: Uuid) -> Result<(), QuantRS2Error> {
813 let mut states = self
814 .states
815 .write()
816 .map_err(|_| QuantRS2Error::LockPoisoned("states lock poisoned".to_string()))?;
817 states.remove(&state_id);
818 Ok(())
819 }
820
821 fn list_states(&self) -> Result<Vec<Uuid>, QuantRS2Error> {
822 let states = self
823 .states
824 .read()
825 .map_err(|_| QuantRS2Error::LockPoisoned("states lock poisoned".to_string()))?;
826 Ok(states.keys().copied().collect())
827 }
828
829 fn get_storage_info(&self) -> StorageLayerInfo {
830 self.info.clone()
831 }
832}
833
834#[derive(Debug, Clone)]
836pub enum AccessPattern {
837 Frequent,
838 Moderate,
839 Rare,
840}
841
842#[derive(Debug)]
843pub struct GarbageCollectionResult {
844 pub collected_states: usize,
845 pub freed_space: usize,
846 pub execution_time: Duration,
847}
848
849#[cfg(test)]
850mod tests {
851 use super::*;
852
853 #[tokio::test]
854 async fn test_quantum_memory_creation() {
855 let memory = QuantumMemory::new();
856 assert_eq!(memory.storage_layers.len(), 0);
857 }
858
859 #[tokio::test]
860 async fn test_in_memory_storage() {
861 let storage = InMemoryStorage::new(100);
862
863 let state = QuantumState {
864 state_id: Uuid::new_v4(),
865 amplitudes: vec![Complex64::new(1.0, 0.0), Complex64::new(0.0, 0.0)],
866 qubit_count: 1,
867 creation_time: SystemTime::now(),
868 last_access: SystemTime::now(),
869 coherence_time: Duration::from_millis(100),
870 fidelity: 0.99,
871 metadata: StateMetadata {
872 name: Some("test_state".to_string()),
873 description: None,
874 tags: vec!["test".to_string()],
875 creator: None,
876 access_count: 0,
877 compression_ratio: 1.0,
878 entanglement_entropy: 0.0,
879 },
880 };
881
882 let state_id = state.state_id;
883 storage
884 .store_state(state_id, &state)
885 .expect("failed to store state");
886
887 let retrieved = storage
888 .retrieve_state(state_id)
889 .expect("failed to retrieve state");
890 assert!(retrieved.is_some());
891 assert_eq!(retrieved.expect("state should be Some").state_id, state_id);
892 }
893
894 #[tokio::test]
895 async fn test_quantum_cache() {
896 let mut cache = QuantumCache::new(2);
897
898 let state1 = QuantumState {
899 state_id: Uuid::new_v4(),
900 amplitudes: vec![Complex64::new(1.0, 0.0)],
901 qubit_count: 1,
902 creation_time: SystemTime::now(),
903 last_access: SystemTime::now(),
904 coherence_time: Duration::from_millis(100),
905 fidelity: 0.99,
906 metadata: StateMetadata {
907 name: None,
908 description: None,
909 tags: Vec::new(),
910 creator: None,
911 access_count: 0,
912 compression_ratio: 1.0,
913 entanglement_entropy: 0.0,
914 },
915 };
916
917 let state2 = QuantumState {
918 state_id: Uuid::new_v4(),
919 ..state1.clone()
920 };
921
922 let state3 = QuantumState {
923 state_id: Uuid::new_v4(),
924 ..state1.clone()
925 };
926
927 cache.insert(state1.state_id, state1.clone());
928 cache.insert(state2.state_id, state2.clone());
929 assert_eq!(cache.cache.len(), 2);
930
931 cache.insert(state3.state_id, state3.clone());
933 assert_eq!(cache.cache.len(), 2);
934 assert!(!cache.cache.contains_key(&state1.state_id));
935 }
936
937 #[tokio::test]
938 async fn test_coherence_manager() {
939 let manager = CoherenceManager::new();
940 let state_id = Uuid::new_v4();
941
942 manager.start_tracking(state_id, Duration::from_millis(100));
943 assert!(manager.is_coherent(state_id));
944
945 tokio::time::sleep(Duration::from_millis(150)).await;
947 assert!(!manager.is_coherent(state_id));
948 }
949}