Skip to main content

mln_wire/
shared.rs

1//! Values behind an `Arc` that cross once, then by key.
2//!
3//! The map side and a worker instance exchange many messages that refer to
4//! the same values: every tile's layout job has its source's style, its
5//! layers and their expressions, and every layout the worker sends back has
6//! buckets whose binders hold those expressions again. A [`Kind`] names such
7//! a value type, and the fields that hold one opt in with [`ByKey`]
8//! (`#[wire(with = ...)]`) or [`write()`] and [`read()`]. Each side keeps a
9//! [`Table`] of each kind it shares, and while a message is written or read
10//! with a kind's table in its context, a value is written as follows:
11//!
12//! - On the side the value comes from ([`Role::Origin`]), the first time as
13//!   a definition under a new key, then as the key. That side keeps the key
14//!   while the value lives (a weak reference), so the other side can refer
15//!   to the value by it too, and lists the keys of the values that died
16//!   ([`ErasedTable::forget_dead`]) for the other side to drop.
17//! - On the side that gets it ([`Role::Copies`]), the definition makes the
18//!   value and keeps it under its key until it is forgotten. Sending that
19//!   value back writes its key, and the origin reads its own value again.
20//!   A value of this side's own is written in full.
21//!
22//! Without its kind's table in the context, a value is written in full.
23
24use std::marker::PhantomData;
25use std::sync::{Arc, Weak};
26
27use crate::hash::HashMap;
28use crate::{Reader, Writer};
29
30/// A type of value that crosses once, then by key, and how it is written
31/// in full.
32pub trait Kind: 'static {
33    /// The value behind the `Arc`.
34    type Value: ?Sized + Send + Sync + 'static;
35    /// Writes the value in full.
36    fn write(value: &Self::Value, w: &mut Writer);
37    /// Reads what `write` wrote.
38    fn read(r: &mut Reader<'_>) -> Option<Arc<Self::Value>>;
39}
40
41/// A value the side it comes from gave a key, and that key.
42type Keyed<T> = (Weak<T>, u64);
43
44/// The keys the side a kind's values come from gave them.
45struct Origin<T: ?Sized> {
46    by_address: HashMap<usize, Keyed<T>>,
47    by_key: HashMap<u64, Weak<T>>,
48    /// The keys of values that died and whose address a new value took
49    /// before `forget_dead` saw them.
50    dead: Vec<u64>,
51    /// The keys given since the last `commit`, which `rollback` takes back.
52    uncommitted: Vec<(usize, Option<Keyed<T>>)>,
53    next: u64,
54}
55
56/// The values the other side defined, by key.
57struct Copies<T: ?Sized> {
58    by_key: HashMap<u64, Arc<T>>,
59    keys: HashMap<usize, u64>,
60}
61
62fn address<T: ?Sized>(value: &Arc<T>) -> usize {
63    Arc::as_ptr(value).cast::<()>() as usize
64}
65
66impl<T: ?Sized> Origin<T> {
67    /// The value's key, and whether it is new (the other side doesn't have
68    /// the value yet).
69    fn key(&mut self, value: &Arc<T>) -> (u64, bool) {
70        let address = address(value);
71        if let Some((weak, key)) = self.by_address.get(&address)
72            && weak.upgrade().is_some_and(|known| Arc::ptr_eq(&known, value))
73        {
74            return (*key, false);
75        }
76        let key = self.next;
77        self.next += 1;
78        let replaced = self.by_address.insert(address, (Arc::downgrade(value), key));
79        self.by_key.insert(key, Arc::downgrade(value));
80        self.uncommitted.push((address, replaced));
81        (key, true)
82    }
83
84    fn commit(&mut self) {
85        for (_, replaced) in self.uncommitted.drain(..) {
86            if let Some((_, dead)) = replaced {
87                self.dead.push(dead);
88            }
89        }
90    }
91
92    fn rollback(&mut self) {
93        for (address, replaced) in self.uncommitted.drain(..).rev() {
94            if let Some((_, key)) = self.by_address.remove(&address) {
95                self.by_key.remove(&key);
96            }
97            if let Some(replaced) = replaced {
98                self.by_address.insert(address, replaced);
99            }
100        }
101    }
102
103    fn forget_dead(&mut self) -> Vec<u64> {
104        let mut forget = std::mem::take(&mut self.dead);
105        self.by_address.retain(|_, (weak, key)| {
106            let alive = weak.strong_count() > 0;
107            if !alive {
108                forget.push(*key);
109            }
110            alive
111        });
112        for key in &forget {
113            self.by_key.remove(key);
114        }
115        forget.sort_unstable();
116        forget
117    }
118}
119
120/// Which side of a kind's values a table is.
121#[derive(Clone, Copy, Debug, PartialEq, Eq)]
122pub enum Role {
123    /// The side the values come from.
124    Origin,
125    /// The side that gets them.
126    Copies,
127}
128
129/// One side's table of the values of kind `K`. A message written or read
130/// with it in its context ([`Context`](crate::Context)) refers to them by key.
131pub struct Table<K: Kind>(Side<K::Value>);
132
133enum Side<T: ?Sized> {
134    Origin(Origin<T>),
135    Copies(Copies<T>),
136}
137
138impl<K: Kind> Table<K> {
139    #[must_use]
140    pub fn new(role: Role) -> Self {
141        Table(match role {
142            Role::Origin => Side::Origin(Origin {
143                by_address: HashMap::default(),
144                by_key: HashMap::default(),
145                dead: Vec::new(),
146                uncommitted: Vec::new(),
147                next: 0,
148            }),
149            Role::Copies => Side::Copies(Copies { by_key: HashMap::default(), keys: HashMap::default() }),
150        })
151    }
152
153    /// How `value` is written, giving it a key if it is new.
154    fn how(&mut self, value: &Arc<K::Value>) -> How {
155        match &mut self.0 {
156            Side::Origin(origin) => match origin.key(value) {
157                (key, true) => How::Define(key),
158                (key, false) => How::Ref(key),
159            },
160            Side::Copies(copies) => copies.keys.get(&address(value)).map_or(How::Inline, |key| How::Ref(*key)),
161        }
162    }
163
164    /// Keeps a value the other side defined under `key`.
165    fn define(&mut self, key: u64, value: &Arc<K::Value>) {
166        if let Side::Copies(copies) = &mut self.0 {
167            copies.keys.insert(address(value), key);
168            copies.by_key.insert(key, Arc::clone(value));
169        }
170    }
171
172    /// The value either side knows by `key`.
173    fn by_key(&self, key: u64) -> Option<Arc<K::Value>> {
174        match &self.0 {
175            Side::Origin(origin) => origin.by_key.get(&key).and_then(Weak::upgrade),
176            Side::Copies(copies) => copies.by_key.get(&key).cloned(),
177        }
178    }
179}
180
181impl<K: Kind> crate::Context for Table<K> {
182    fn provide<'a>(&'a mut self, request: &mut crate::Request<'a>) {
183        request.give_mut(self);
184    }
185}
186
187/// A table of any kind, as a side keeps its tables together.
188pub trait ErasedTable: crate::Context + Send {
189    /// Keeps the keys given since the last `commit` or `rollback`: the
190    /// message that gave them was sent.
191    fn commit(&mut self);
192    /// Takes back the keys given since the last `commit` or `rollback`, so
193    /// that a message that wasn't sent defines nothing.
194    fn rollback(&mut self);
195    /// The keys of the values that died on the origin side, for the other
196    /// side to forget.
197    fn forget_dead(&mut self) -> Vec<u64>;
198    /// Drops the copies of the values the origin lists as dead.
199    fn forget(&mut self, keys: &[u64]);
200}
201
202impl<K: Kind> ErasedTable for Table<K> {
203    fn commit(&mut self) {
204        if let Side::Origin(origin) = &mut self.0 {
205            origin.commit();
206        }
207    }
208
209    fn rollback(&mut self) {
210        if let Side::Origin(origin) = &mut self.0 {
211            origin.rollback();
212        }
213    }
214
215    fn forget_dead(&mut self) -> Vec<u64> {
216        match &mut self.0 {
217            Side::Origin(origin) => origin.forget_dead(),
218            Side::Copies(_) => Vec::new(),
219        }
220    }
221
222    fn forget(&mut self, keys: &[u64]) {
223        if let Side::Copies(copies) = &mut self.0 {
224            for key in keys {
225                if let Some(value) = copies.by_key.remove(key) {
226                    copies.keys.remove(&address(&value));
227                }
228            }
229        }
230    }
231}
232
233/// How a value is written, as the variant index it is written with.
234enum How {
235    /// The first time from the origin: the key, and the value in full.
236    Define(u64),
237    /// The key either side knows the value by.
238    Ref(u64),
239    /// The value in full, without a key.
240    Inline,
241}
242
243/// Writes a value of kind `K`.
244pub fn write<K: Kind>(value: &Arc<K::Value>, w: &mut Writer) {
245    let how = w.context_mut::<Table<K>>().map_or(How::Inline, |table| table.how(value));
246    match how {
247        How::Define(key) => {
248            w.push(0);
249            crate::write_varint(w, key);
250            K::write(value, w);
251        }
252        How::Ref(key) => {
253            w.push(1);
254            crate::write_varint(w, key);
255        }
256        How::Inline => {
257            w.push(2);
258            K::write(value, w);
259        }
260    }
261}
262
263/// Reads what `write` wrote.
264pub fn read<K: Kind>(r: &mut Reader<'_>) -> Option<Arc<K::Value>> {
265    match r.byte()? {
266        0 => {
267            let key = r.varint()?;
268            let value = K::read(r)?;
269            if let Some(table) = r.context_mut::<Table<K>>() {
270                table.define(key, &value);
271            }
272            Some(value)
273        }
274        1 => {
275            let key = r.varint()?;
276            let value = r.context_mut::<Table<K>>().and_then(|table| table.by_key(key));
277            value.or_else(|| r.fail("a value by a key this side doesn't know"))
278        }
279        2 => K::read(r),
280        _ => r.fail_tag(),
281    }
282}
283
284/// Writes an `Option` of a value of kind `K`.
285pub fn write_option<K: Kind>(value: &Option<Arc<K::Value>>, w: &mut Writer) {
286    match value {
287        None => w.push(0),
288        Some(value) => {
289            w.push(1);
290            write::<K>(value, w);
291        }
292    }
293}
294
295/// Reads what `write_option` wrote.
296pub fn read_option<K: Kind>(r: &mut Reader<'_>) -> Option<Option<Arc<K::Value>>> {
297    match r.byte()? {
298        0 => Some(None),
299        1 => read::<K>(r).map(Some),
300        _ => r.fail("invalid option"),
301    }
302}
303
304/// `#[wire(with = "shared::ByKey::<K>")]` for an `Arc` of a value of kind
305/// `K`: [`write()`] and [`read()`].
306pub struct ByKey<K>(PhantomData<K>);
307
308impl<K: Kind> ByKey<K> {
309    pub fn write(value: &Arc<K::Value>, w: &mut Writer) {
310        write::<K>(value, w);
311    }
312
313    pub fn read(r: &mut Reader<'_>) -> Option<Arc<K::Value>> {
314        read::<K>(r)
315    }
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321
322    struct Text;
323
324    impl Kind for Text {
325        type Value = str;
326
327        fn write(value: &str, w: &mut Writer) {
328            crate::write_str(w, value);
329        }
330
331        fn read(r: &mut Reader<'_>) -> Option<Arc<str>> {
332            crate::read_str(r).map(Arc::from)
333        }
334    }
335
336    fn encode(table: &mut Table<Text>, value: &Arc<str>) -> Vec<u8> {
337        let mut w = Writer::new().with_context(table);
338        write::<Text>(value, &mut w);
339        let bytes = w.finish().unwrap();
340        table.commit();
341        bytes
342    }
343
344    fn decode(table: &mut Table<Text>, bytes: &[u8]) -> Option<Arc<str>> {
345        read::<Text>(&mut Reader::new(bytes).with_context(table))
346    }
347
348    /// A value crosses in full once, then by key, both ways; the side it
349    /// comes from reads its own value back.
350    #[test]
351    fn values_cross_once() {
352        let mut origin = Table::<Text>::new(Role::Origin);
353        let mut copies = Table::<Text>::new(Role::Copies);
354        let value: Arc<str> = Arc::from("a value long enough to tell apart from a key");
355
356        let first = encode(&mut origin, &value);
357        let second = encode(&mut origin, &value);
358        assert!(first.len() > value.len() && second.len() < 4);
359        let copy = decode(&mut copies, &first).unwrap();
360        assert_eq!(&*copy, &*value);
361        assert!(Arc::ptr_eq(&decode(&mut copies, &second).unwrap(), &copy));
362
363        let back = encode(&mut copies, &copy);
364        assert_eq!(back, second);
365        assert!(Arc::ptr_eq(&decode(&mut origin, &back).unwrap(), &value));
366
367        // A value of the copies' side's own crosses in full.
368        let own: Arc<str> = Arc::from("own");
369        assert_eq!(&*decode(&mut origin, &encode(&mut copies, &own)).unwrap(), "own");
370
371        // Without the table in the context, a value crosses in full.
372        let mut w = Writer::new();
373        write::<Text>(&value, &mut w);
374        assert_eq!(read::<Text>(&mut Reader::new(&w.finish().unwrap())).as_deref(), Some(&*value));
375    }
376
377    /// The copies forget what died at the origin, and a message that wasn't
378    /// sent defines nothing.
379    #[test]
380    fn dead_and_unsent_values() {
381        let mut origin = Table::<Text>::new(Role::Origin);
382        let mut copies = Table::<Text>::new(Role::Copies);
383        let value: Arc<str> = Arc::from("value");
384        let reference = {
385            decode(&mut copies, &encode(&mut origin, &value)).unwrap();
386            encode(&mut origin, &value)
387        };
388        drop(value);
389        let dead = origin.forget_dead();
390        assert_eq!(dead, vec![0]);
391        copies.forget(&dead);
392        assert!(decode(&mut copies, &reference).is_none());
393
394        let unsent: Arc<str> = Arc::from("unsent");
395        write::<Text>(&unsent, &mut Writer::new().with_context(&mut origin));
396        origin.rollback();
397        let sent = encode(&mut origin, &unsent);
398        assert_eq!(&*decode(&mut copies, &sent).unwrap(), "unsent");
399    }
400}