nixl_sys/descriptors/
sync_manager.rs

1// SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Synchronization manager for frontend-backend data consistency
5
6use std::cell::Cell;
7
8/// Trait for types that can synchronize their state to a backend
9pub trait BackendSyncable {
10    type Backend;
11    type Error;
12    fn sync_to_backend(&self, backend: &Self::Backend) -> Result<(), Self::Error>;
13}
14
15/// Manager that enforces correct synchronization between frontend and backend
16pub struct SyncManager<T: BackendSyncable> {
17    data: T,
18    backend: T::Backend,
19    dirty: Cell<bool>,
20}
21
22impl<T: BackendSyncable> SyncManager<T> {
23    /// Creates a new sync manager (starts dirty to ensure first sync)
24    pub fn new(data: T, backend: T::Backend) -> Self {
25        Self {
26            data,
27            backend,
28            dirty: Cell::new(true),
29        }
30    }
31
32    /// Provides mutable access to the frontend data
33    pub fn data_mut(&mut self) -> &mut T {
34        self.dirty.set(true);
35        &mut self.data
36    }
37
38    /// Provides read-only access to the frontend data (no sync)
39    pub fn data(&self) -> &T {
40        &self.data
41    }
42
43    /// Provides read-only access to the backend after ensuring synchronization
44    pub fn backend(&self) -> Result<&T::Backend, T::Error> {
45        self.ensure_synced()?;
46        Ok(&self.backend)
47    }
48
49    fn ensure_synced(&self) -> Result<(), T::Error> {
50        if self.dirty.get() {
51            self.data.sync_to_backend(&self.backend)?;
52            self.dirty.set(false);
53        }
54        Ok(())
55    }
56}
57