1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
use PhantomData;
use crate;
use Register;
/// A shared-memory register, backed by an 64 bits of "atomic" memory.
///
/// This object works by serializing data and storing it in an
/// [`AtomicU64`], and so can only be used to store small amounts
/// of data.
///
/// # Atomics and Memory Ordering
///
/// Unfortunately, the theoretical atomic memory model in which atomic really means
/// [_linearizable_](https://en.wikipedia.org/wiki/Linearizability),
/// is not the same as the model used by languages such as
/// [Rust](https://doc.rust-lang.org/nomicon/atomics.html) and
/// [C++](https://en.cppreference.com/w/cpp/atomic/memory_order).
/// In practice, the compiler and hardware optimizations that make life livable
/// come at the cost of potentially re-ordering memory accesses. The strictest
/// consistency model that we can ask for in Rust is
/// [_sequential consistency_](https://en.wikipedia.org/wiki/Sequential_consistency),
/// which means that all processes perform operations in a sequential order, but
/// the relative order of operations perfomed by different processes is undefined.
///
/// As a result, operations performed on an `AtomicRegister` are only
/// guaranteed to be sequentially consistent, not necessarily lineariazable.
///
/// Thankfully, it was recently shown by Perrin, Petrolia, Mostefaoui, and Jard
/// [[PPM+2016]](https://arxiv.org/abs/1607.06258) that objects that would be
/// linearizable if they were implemented on top of linearizable memory become
/// sequentially consistent if implemented on top of sequentially consistent
/// memory. This means that, while implemenations of linearizable algorithms
/// from [`AtomicRegister`] objects may fail to be linearizable, they will at least
/// be sequentially consistent, and will retain all other properties such as
/// wait-freedom.
///
/// ## Linearizability
///
/// For a register that guarantees linearizability at the cost of lock-freedom,
/// see [`MutexRegister`](super::mutex::MutexRegister).
///
/// # Examples
///
/// A simple spinlock.
///
/// ```
/// use std::sync::Arc;
/// use std::{hint, thread};
/// use todc_mem::register::{AtomicRegister, Register};
///
///
/// let register: Arc<AtomicRegister<u64>> = Arc::new(AtomicRegister::new());
///
/// let register_clone = register.clone();
/// let thread = thread::spawn(move || {
/// register_clone.write(1)
/// });
///
/// while register.read() == 0 {
/// hint::spin_loop();
/// }
///
/// thread.join().unwrap();
/// ```
///
/// Although space is limited, it is still possible to store any type that can
/// be converted to [`u64`] and back again.
///
/// ```
/// use heapless::String;
/// use todc_mem::register::{AtomicRegister, Register};
///
/// // A String with a fixed capacity of 64 bits
/// #[derive(Clone, Debug, Default, PartialEq)]
/// struct TinyString(String<8>);
///
/// impl From<TinyString> for u64 {
/// fn from(string: TinyString) -> Self {
/// // -- snipped --
/// # let mut result = Self::MAX;
/// # let bytes = string.0.into_bytes();
/// # for (i, num) in bytes.iter().rev().enumerate() {
/// # let mut num = (*num as u64) << (i * 8);
/// # for j in 0..i {
/// # num |= (u8::MAX as u64) << (j * 8);
/// # }
/// # for k in 0..(8 - i - 1) {
/// # num |= ((u8::MAX as u64) << ((8 - k - 1) * 8));
/// # }
/// # result &= num;
/// # }
/// # result
/// }
/// }
///
/// impl From<u64> for TinyString {
/// fn from(value: u64) -> Self {
/// // -- snipped --
/// # let bytes: Vec<u8> = value.to_be_bytes()
/// # .into_iter()
/// # .filter(|&x| x != u8::MAX)
/// # .collect();
/// # let mut result: String<8> = String::from("");
/// # if let Ok(string) = std::str::from_utf8(&bytes[..]) {
/// # result.push_str(string);
/// # };
/// # Self(result)
/// }
/// }
///
/// let register: AtomicRegister<TinyString> = AtomicRegister::new();
///
/// let empty = TinyString(String::from(""));
/// assert_eq!(register.read(), empty);
///
/// let greeting = TinyString(String::from("hi"));
/// register.write(greeting.clone());
/// assert_eq!(register.read(), greeting);
///
/// let emojis = TinyString(String::from("👋🦀"));
/// register.write(emojis.clone());
/// assert_eq!(register.read(), emojis);
/// ```