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
//! A container which provides typed scratch storage for external owners.

// Copyright 2023 Eric Michael Sumner
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::collections::{HashMap,HashSet};
use std::hash::{Hash,Hasher};
use std::borrow::Borrow;

use parking_lot::Mutex;

#[cfg(test)] mod tests;

type Id = u128;

/// A non-cloneable, guaranteed-unique `Id`
#[derive(Debug)]
struct UniqueId(Id);

impl Default for UniqueId {
    fn default()->Self {
        static NEXT: Mutex<Id> = Mutex::new(0);
        let mut guard = NEXT.lock();
        let result = *guard;
        *guard = result.checked_add(1).unwrap();
        UniqueId(result)
    }
}

impl std::ops::Deref for UniqueId {
    type Target = Id;
    fn deref(&self)->&Id { &self.0 }
}

/// A typed slot for `Guest`s to store private values.
/// Stores multiple values, one per guest.
#[derive(Default,Debug)]
pub struct GuestCell<T:?Sized> {
    map: Mutex<HashMap<Id, Box<T>>>,
    id: UniqueId
}

/// Accessor for a `GuestCell`.
/// Safety: `borrow` must always return the same `GuestCell`
pub unsafe trait IndirectGuestCell: Borrow<GuestCell<Self::Inner>> {
    type Inner: ?Sized;
}

unsafe impl<T:?Sized> IndirectGuestCell for &'_ GuestCell<T> { type Inner = T; }
unsafe impl<T:?Sized> IndirectGuestCell for std::sync::Arc<GuestCell<T>> { type Inner = T; }
unsafe impl<T:?Sized> IndirectGuestCell for std::rc::Rc<GuestCell<T>> { type Inner = T; }

trait ErasedGuestCell {
    fn guest_drop(&self, guest: &mut UniqueId);
    fn id(&self)->&UniqueId;
}

impl<T:?Sized> ErasedGuestCell for GuestCell<T> {
    fn guest_drop(&self, guest_id: &mut UniqueId) {
        self.map.lock().remove(&guest_id).unwrap();
    }

    fn id(&self)->&UniqueId { &self.id }
}

impl<Ptr:IndirectGuestCell> ErasedGuestCell for Ptr {
    fn guest_drop(&self, guest: &mut UniqueId) {
        self.borrow().guest_drop(guest)
    }

    fn id(&self)->&UniqueId {
        self.borrow().id()
    }
}

impl PartialEq for dyn ErasedGuestCell + '_ {
    fn eq(&self, rhs: &dyn ErasedGuestCell)->bool {
        **self.id() == **rhs.id()
    }
}

impl Eq for dyn ErasedGuestCell + '_ {}

impl Hash for dyn ErasedGuestCell + '_ {
    fn hash<H:Hasher>(&self, h:&mut H) {
        self.id().hash(h);
    }
}

/// An owner for private values stored in various `GuestCell`s.
#[derive(Default)]
pub struct Guest<'a> {
    id: UniqueId,
    cells: HashSet<Box<dyn ErasedGuestCell + 'a>>,
}

impl Drop for Guest<'_> {
    fn drop(&mut self) {
        for map in &self.cells {
            map.guest_drop(&mut self.id);
        }
    }
}

impl std::fmt::Debug for Guest<'_> {
    fn fmt(&self, f:&mut std::fmt::Formatter<'_>)->Result<(), std::fmt::Error> {
        f.debug_struct("Guest")
            .field("id", &self.id)
            .field("cells", &self.cells.iter().map(|x| x.id()).collect::<Vec<_>>())
            .finish()
    }
}

impl<'a> Guest<'a> {
    pub fn get<T:?Sized>(&self, cell: impl 'a + IndirectGuestCell<Inner=T>)->Option<&T> {
        let guard = cell.borrow().map.lock();
        let boxed:&Box<T> = guard.get(&self.id)?;

        // Safety: Access to this box is mediated through self.id 
        Some(unsafe { &*((&**boxed) as *const T) })
    }

    pub fn get_mut<T:?Sized>(&mut self, cell: impl 'a + IndirectGuestCell<Inner=T>)->Option<&mut T> {
        let mut guard = cell.borrow().map.lock();
        let boxed:&mut Box<T> = guard.get_mut(&self.id)?;

        // Safety: Access to this box is mediated through self.id 
        Some(unsafe { &mut *((&mut **boxed) as *mut T) })
    }

    pub fn set<T:?Sized>(&mut self, cell: impl 'a + IndirectGuestCell<Inner=T>, val:Box<T>)->Option<Box<T>> {
        let result = cell.borrow().map.lock().insert(*self.id, val);
        self.cells.insert(Box::new(cell));
        result
    }

    pub fn take<T:?Sized>(&mut self, cell: impl 'a + IndirectGuestCell<Inner=T>)->Option<Box<T>> {
        let result = cell.borrow().map.lock().remove(&self.id);
        self.cells.remove(&cell as &dyn ErasedGuestCell);
        result
    }
}