pyrucast 0.12.0

Finite-element library in Rust, inspired by cast3m, exposed to Python
Documentation
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Object handles — pyrucast's "object pile", cast3m-style.
//!
//! Every object the user manipulates lives behind a [`Handle<T>`]: a counted,
//! cheaply cloned reference carrying its own lock. There is no session to pass
//! around and no global registry — a handle *is* the object's address, and the
//! object dies with the last handle that names it.
//!
//! ```text
//! Handle<T>  =  Arc<RwLock<T>>  +  the API we want on it
//! ```
//!
//! # Guarantees
//!
//! - **Counted.** `Clone` shares, `Drop` releases; when the last handle goes,
//!   the value is dropped — running its own `Drop`, so side effects such as
//!   `SubMesh` releasing its nodes inside the `Coords` happen exactly once.
//! - **Always valid.** A handle cannot outlive its object: holding one keeps
//!   the object alive. There is no stale handle, no generation to check, and
//!   [`Handle::read`] / [`Handle::write`] cannot fail.
//! - **Identity is the pointer.** [`Handle::same_object`] answers « are these
//!   two references the same object? » — the basis of the aggregates' union.
//!
//! # Why not a slab of numbered slots
//!
//! A registry of numbered slots — one slab per type, a generation per slot, a
//! hand-written refcount — would duplicate what `Arc` already does: the count
//! is the `Arc`'s, and a handle cannot outlive its object, so there is no
//! stale number for a generation to catch.
//!
//! What such a registry adds is **enumeration** (« list every live mesh ») and
//! a **stable number** per object; pyrucast offers neither. Every object is
//! created through [`Handle::new`], the one place where a `Vec<Weak<_>>` would
//! register them if enumeration were needed.
//!
//! # Concurrency
//!
//! Locking is **per object**: each handle carries its own
//! [`parking_lot::RwLock`]. [`Handle::read`] returns a shared guard (many
//! concurrent readers), [`Handle::write`] an exclusive one. Guards are *owned*
//! (`'static`): they can be returned from functions and stored in structs, so
//! operators read the data **in place** instead of copying it out.
//!
//! Two usage rules apply, and the compiler checks neither:
//!
//! - **Do not take a second guard on an object the same thread already holds,
//!   even for reading.** The lock is not reentrant, and it is task-fair: a
//!   writer that starts waiting between the two guards makes the second reader
//!   wait for it, while it waits for the first reader — forever.
//! - **Nest locks in one order**: a `SubMesh` before its `Coords`, never the
//!   reverse.
//!
//! Apart from that, distinct objects are independent.
//!
//! # Example
//!
//! ```
//! use pyrucast::handle::Handle;
//!
//! #[derive(Debug, PartialEq)]
//! struct Points(Vec<f64>);
//!
//! let h = Handle::new(Points(vec![1.0, 2.0]));
//! h.write().0.push(3.0);
//! assert_eq!(h.read().0.len(), 3);
//!
//! // A clone names the same object.
//! let g = h.clone();
//! assert!(g.same_object(&h));
//! ```

use parking_lot::lock_api::{ArcRwLockReadGuard, ArcRwLockWriteGuard};
use parking_lot::{RawRwLock, RwLock};
use std::fmt;
use std::sync::Arc;

/// Shared (read) access to an object, returned by [`Handle::read`].
///
/// Owned (`'static`): it can be returned from a function and stored in a
/// struct. Dereferences to `&T`; the lock is released when the guard goes out
/// of scope. The guard holds the object itself alive, so it may outlive every
/// handle it came from.
///
/// ```
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # let handle = Handle::new(Coords::new(2).unwrap());
/// // The lock covers **this object alone**, and lasts as long as the guard.
/// let lu = handle.read();
/// // Another thread reads meanwhile: readers do not wait for one another.
/// let autre = handle.clone();
/// let dim = std::thread::spawn(move || autre.read().dim()).join().unwrap();
/// assert_eq!(lu.dim(), dim);
/// ```
pub type ReadGuard<T> = ArcRwLockReadGuard<RawRwLock, T>;

/// Exclusive (write) access to an object, returned by [`Handle::write`].
///
/// Same ownership properties as [`ReadGuard`]; dereferences to `&mut T`.
///
/// ```
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # let handle = Handle::new(Coords::new(2).unwrap());
/// // Writing is exclusive, for the duration of the call. Releasing it before
/// // taking a read again is what avoids the deadlock.
/// handle.write().add_node(&[0.0, 0.0])?;
/// assert_eq!(handle.read().node_count(), 1);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub type WriteGuard<T> = ArcRwLockWriteGuard<RawRwLock, T>;

/// A counted reference to an object, with its own lock.
///
/// Cloning shares the object rather than copying it — the whole point, since a
/// `SubMesh` or a `Coords` is large and shared by construction. Two handles
/// name the same object exactly when [`same_object`](Self::same_object) says
/// so.
// ANCHOR: declaration
///
/// ```
/// # use pyrucast::handle::Handle;
/// # use pyrucast::coords::Coords;
/// let h1 = Handle::new(Coords::new(2).unwrap()); // premier ticket
/// let h2 = h1.clone(); // même objet
/// assert!(h1.same_object(&h2));
/// drop(h1); // h2 tient encore l'objet
/// assert_eq!(h2.read().dim(), 2);
/// ```
pub struct Handle<T> {
    cell: Arc<RwLock<T>>,
}
// ANCHOR_END: declaration

impl<T> Handle<T> {
    /// Take ownership of `value` and hand back the first reference to it.
    ///
    /// **The single funnel through which objects are created.** Keeping it that
    /// way is what would make a future registry — for enumeration, or a
    /// whole-session save — a change to one function rather than a hunt through
    /// every construction site.
    ///
    /// ```
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::coords::Coords;
    /// let h = Handle::new(Coords::new(2).unwrap());
    /// assert_eq!(h.read().dim(), 2);
    /// ```
    pub fn new(value: T) -> Self {
        Self {
            cell: Arc::new(RwLock::new(value)),
        }
    }

    /// Shared access. Blocks while a writer holds the object.
    ///
    /// Infallible: holding `self` guarantees the object is there.
    ///
    /// ```
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::coords::Coords;
    /// let h = Handle::new(Coords::new(2).unwrap());
    /// let g = h.read(); // verrou lecture, relâché à la fin de portée
    /// assert_eq!(g.dim(), 2);
    /// // Plusieurs lecteurs coexistent.
    /// assert_eq!(h.read().dim(), 2);
    /// ```
    pub fn read(&self) -> ReadGuard<T> {
        self.cell.read_arc()
    }

    /// Exclusive access. Blocks while any other guard holds the object.
    ///
    /// Infallible, for the same reason as [`read`](Self::read).
    ///
    /// ```
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::coords::Coords;
    /// let h = Handle::new(Coords::new(2).unwrap());
    /// let id = h.write().add_node(&[0.0, 0.0]).unwrap(); // verrou le temps de l'appel
    /// assert_eq!(h.read().node_count(), 1);
    /// # let _ = id;
    /// ```
    pub fn write(&self) -> WriteGuard<T> {
        self.cell.write_arc()
    }

    /// Whether two handles name the **same object**.
    ///
    /// Identity, not equality: this is what lets an aggregate's union skip a
    /// sub it already holds, and what tells a field that its support is the
    /// mesh it was handed.
    ///
    /// ```
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::coords::Coords;
    /// let a = Handle::new(Coords::new(2).unwrap());
    /// let b = a.clone(); // même objet, ticket de plus
    /// let c = Handle::new(Coords::new(2).unwrap()); // objet distinct, contenu égal
    /// assert!(a.same_object(&b));
    /// assert!(!a.same_object(&c));
    /// ```
    pub fn same_object(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.cell, &other.cell)
    }

    /// `true` when this is the **only** handle on the object — nothing else can
    /// observe a mutation made through it.
    ///
    /// The one licence to modify a shared object in place instead of rebuilding
    /// it: an owner holding the sole handle knows no other holder exists, so the
    /// side effect a shared object would suffer cannot happen. Used by the
    /// matrix scalar operators, which rebuild a block rather than rescale it
    /// (see [`crate::containers::matrix`]) — except when this says the block
    /// belongs to no one else.
    ///
    /// Sound to act on: a second handle can only be made by cloning an existing
    /// one, so an answer of `true` cannot be invalidated by another thread while
    /// the caller holds `self`. The converse is a snapshot — `false` may turn
    /// stale the instant another holder drops its handle — which only ever costs
    /// a copy that was not strictly needed.
    ///
    /// ```
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::coords::Coords;
    /// let a = Handle::new(Coords::new(2).unwrap());
    /// assert!(a.is_sole_owner()); // personne d'autre ne le tient
    /// let b = a.clone();
    /// assert!(!a.is_sole_owner()); // b l'observerait
    /// drop(b);
    /// assert!(a.is_sole_owner()); // de nouveau seul
    /// ```
    pub fn is_sole_owner(&self) -> bool {
        Arc::strong_count(&self.cell) == 1
    }

    /// An opaque identity, hashable and comparable — for use as a map key when
    /// grouping by object.
    ///
    /// Two handles give the same `id` exactly when they name the same object.
    /// Like the tag shown by [`fmt::Display`], it is an **address**: unique
    /// among objects alive at the same instant, and reused once an object is
    /// gone. Safe to key a table built and consumed within one operation; not a
    /// durable identity to store or write to a file.
    ///
    /// ```
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::coords::Coords;
    /// let a = Handle::new(Coords::new(2).unwrap());
    /// assert_eq!(a.id(), a.clone().id()); // stable pour un même objet
    /// ```
    pub fn id(&self) -> usize {
        Arc::as_ptr(&self.cell) as *const () as usize
    }

    /// The object's address, as the short tag shown by [`fmt::Display`].
    ///
    /// Distinguishes objects **alive at the same instant** — which is what a
    /// human comparing two lines of output needs. It is *not* a durable
    /// identity: an address is reused once the object is gone, so two entries
    /// bearing the same tag in a log written over time may be two different
    /// objects.
    ///
    /// Public so a holder can name its sub-objects without recomputing the tag:
    /// an aggregate's `Display` lists `[#7f3a2c, …]`, where repeating the type
    /// of every zone would say nothing that `submesh(es)` has not already said.
    ///
    /// ```
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::coords::Coords;
    /// let a = Handle::new(Coords::new(2).unwrap());
    /// // The address's low 24 bits: short enough to read at a glance, wide enough
    /// // to tell apart objects alive together.
    /// assert_eq!(a.tag(), a.id() & 0xff_ffff);
    /// assert_eq!(a.tag(), a.clone().tag()); // stable pour un même objet
    /// ```
    pub fn tag(&self) -> usize {
        self.id() & 0xff_ffff
    }
}

impl<T> Clone for Handle<T> {
    /// Written out rather than derived: `#[derive(Clone)]` would demand
    /// `T: Clone`, when cloning a handle never touches the object.
    fn clone(&self) -> Self {
        Self {
            cell: self.cell.clone(),
        }
    }
}

/// Short, lock-free view: `<SubMesh #7f3a2c>`.
///
/// Deliberately does **not** read the object. Printing a handle must stay free
/// — a `SubMesh` holds a connectivity of millions of entries, and a handle may
/// well be formatted while a write guard is held on it, which reading would
/// deadlock.
impl<T> fmt::Display for Handle<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let short = std::any::type_name::<T>()
            .rsplit("::")
            .next()
            .unwrap_or("?");
        write!(f, "<{} #{:x}>", short, self.tag())
    }
}

/// Same short view as [`fmt::Display`] — `<SubMesh #7f3a2c>`.
///
/// The two agree on purpose: a `Debug` of a container prints one handle per
/// member and per zone, and spelling the module path out at each would repeat
/// what the member's own name already says.
impl<T> fmt::Debug for Handle<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    #[derive(Debug, PartialEq)]
    struct P(Vec<f64>);

    #[test]
    fn new_then_read() {
        let h = Handle::new(P(vec![1.0, 2.0]));
        assert_eq!(h.read().0, vec![1.0, 2.0]);
    }

    #[test]
    fn write_modifies_in_place() {
        let h = Handle::new(P(vec![]));
        h.write().0.push(7.0);
        assert_eq!(h.read().0, vec![7.0]);
    }

    #[test]
    fn clone_shares_the_object() {
        let a = Handle::new(P(vec![1.0]));
        let b = a.clone();
        assert!(a.same_object(&b));
        b.write().0.push(2.0);
        assert_eq!(a.read().0.len(), 2);
    }

    #[test]
    fn distinct_objects_are_not_the_same() {
        let a = Handle::new(P(vec![1.0]));
        let b = Handle::new(P(vec![1.0]));
        assert!(!a.same_object(&b), "equal contents are not one object");
    }

    static DROPPED: AtomicUsize = AtomicUsize::new(0);
    struct Counted;
    impl Drop for Counted {
        fn drop(&mut self) {
            DROPPED.fetch_add(1, Ordering::SeqCst);
        }
    }

    /// The lifetime contract: the object dies with the **last** handle, and
    /// dies once. This is what replaced the hand-written refcount, so it is the
    /// assertion that says the replacement behaves.
    #[test]
    fn the_object_dies_with_the_last_handle_and_only_then() {
        DROPPED.store(0, Ordering::SeqCst);
        let a = Handle::new(Counted);
        let b = a.clone();
        drop(a);
        assert_eq!(
            DROPPED.load(Ordering::SeqCst),
            0,
            "one handle still names it"
        );
        drop(b);
        assert_eq!(DROPPED.load(Ordering::SeqCst), 1, "exactly one drop");
    }

    /// A guard keeps the object alive on its own — an operator may hold data in
    /// place after the handle it came from is gone.
    #[test]
    fn a_guard_outlives_the_last_handle() {
        DROPPED.store(0, Ordering::SeqCst);
        let h = Handle::new(Counted);
        let g = h.read();
        drop(h);
        assert_eq!(
            DROPPED.load(Ordering::SeqCst),
            0,
            "the guard still holds it"
        );
        drop(g);
        assert_eq!(DROPPED.load(Ordering::SeqCst), 1);
    }

    /// Formatting must neither read the object nor block: here it happens while
    /// a write guard is held, which reading would deadlock.
    #[test]
    fn display_does_not_touch_the_object() {
        let h = Handle::new(P(vec![1.0]));
        let _w = h.write();
        let shown = format!("{h}");
        assert!(shown.starts_with("<P #"), "unexpected: {shown}");
    }

    #[test]
    fn concurrent_readers() {
        let h = Handle::new(P(vec![1.0, 2.0]));
        std::thread::scope(|s| {
            for _ in 0..4 {
                let h = h.clone();
                s.spawn(move || {
                    let g = h.read();
                    assert_eq!(g.0.len(), 2);
                });
            }
        });
    }
}