instance_copy_on_write/
lib.rs

1/*-
2 * instance-copy-on-write - a synchronization primitive based on copy-on-write.
3 * 
4 * Copyright (C) 2025 Aleksandr Morozov alex@
5 * 
6 * The scram-rs crate can be redistributed and/or modified
7 * under the terms of either of the following licenses:
8 *
9 *   1. the Mozilla Public License Version 2.0 (the “MPL”) OR
10 *                     
11 *   2. EUROPEAN UNION PUBLIC LICENCE v. 1.2 EUPL © the European Union 2007, 2016
12 */
13
14 /// Type of the sync code.
15 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
16 pub enum ICoWLockTypes
17 {
18    /// Based on atomic and backoff.
19    Atomic,
20
21    /// based on the OS RwLock
22    RwLock,
23 }
24
25impl fmt::Display for ICoWLockTypes
26{
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
28    {
29        match self
30        {
31            Self::Atomic => 
32                write!(f, "atomic"),
33            Self::RwLock => 
34                write!(f, "rwlock"),
35        }
36    }
37}
38
39/// Errors which may be returned.
40#[derive(Copy, Clone, Debug, PartialEq, Eq)]
41pub enum ICoWError
42{
43    /// An attempt to write to the instance using non exclusive copy-on-write operation
44    /// while the exclusive is still going.
45    ExclusiveLockPending,
46
47    /// Is issued if "exponential backoff has completed and blocking the thread is advised".
48    WouldBlock,
49
50    /// Duplicate write operation prevented.
51    AlreadyUpdated,
52
53    /// Race condition on the exclusive lock.
54    RaceCondition
55}
56
57impl fmt::Display for ICoWError
58{
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
60    {
61        match self
62        {
63            Self::ExclusiveLockPending => 
64                write!(f, "already exlcusivly locked"),
65            Self::WouldBlock => 
66                write!(f, "cannot perform try operation due to blocking"),
67            Self::AlreadyUpdated => 
68                write!(f, "the value has been updated before the current thread"),
69            Self::RaceCondition => 
70                write!(f, "a race condition detected"),
71        }
72    }
73}
74
75extern crate crossbeam_utils;
76extern crate crossbeam_deque;
77
78/// A lightweight CoW implementation.
79#[cfg(all(target_has_atomic = "ptr", feature = "prefer_atomic"))]
80pub mod cow;
81
82/// A RwLock based copy-on-write.
83#[cfg(any(not(target_has_atomic = "ptr"), not(feature = "prefer_atomic")))]
84pub mod cow_mutex;
85
86use std::fmt;
87
88#[cfg(all(target_has_atomic = "ptr", feature = "prefer_atomic"))]
89pub use cow::{ICoW, ICoWRead, ICoWCopy, ICoWLock};
90
91#[cfg(any(not(target_has_atomic = "ptr"), not(feature = "prefer_atomic")))]
92pub use cow_mutex::{ICoW, ICoWRead, ICoWCopy, ICoWLock};