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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
use crate::{AnyObjError, RawStr};
use std::cell::Cell;
use std::fmt;
use std::future::Future;
use std::mem::ManuallyDrop;
use std::ops;
use std::pin::Pin;
use std::task::{Context, Poll};
use thiserror::Error;

/// Bitflag which if set indicates that the accessed value is an external
/// reference (exclusive or not).
const IS_REF_MASK: isize = 1isize;
/// Sentinel value to indicate that access is taken.
const TAKEN: isize = (isize::max_value() ^ IS_REF_MASK) >> 1;
/// Panic if we reach this number of shared accesses and we try to add one more,
/// since it's the largest we can support.
const MAX_USES: isize = 0b11isize.rotate_right(2);

/// An error raised while downcasting.
#[allow(missing_docs)]
#[derive(Debug, Error)]
pub enum AccessError {
    #[error("expected data of type `{expected}`, but found `{actual}`")]
    UnexpectedType { expected: RawStr, actual: RawStr },
    #[error("{error}")]
    NotAccessibleRef {
        #[source]
        #[from]
        error: NotAccessibleRef,
    },
    #[error("{error}")]
    NotAccessibleMut {
        #[source]
        #[from]
        error: NotAccessibleMut,
    },
    #[error("{error}")]
    NotAccessibleTake {
        #[source]
        #[from]
        error: NotAccessibleTake,
    },
    #[error("{error}")]
    AnyObjError {
        #[source]
        #[from]
        error: AnyObjError,
    },
}

/// The kind of access to perform.
#[derive(Debug, Clone, Copy)]
pub(crate) enum AccessKind {
    /// Access a reference.
    Any,
    /// Access something owned.
    Owned,
}

/// Error raised when tried to access for shared access but it was not
/// accessible.
#[derive(Debug, Error)]
#[error("cannot read, value is {0}")]
pub struct NotAccessibleRef(Snapshot);

/// Error raised when tried to access for exclusive access but it was not
/// accessible.
#[derive(Debug, Error)]
#[error("cannot write, value is {0}")]
pub struct NotAccessibleMut(Snapshot);

/// Error raised when tried to access the guarded data for taking.
///
/// This requires exclusive access, but it's a scenario we structure separately
/// for diagnostics purposes.
#[derive(Debug, Error)]
#[error("cannot take, value is {0}")]
pub struct NotAccessibleTake(Snapshot);

/// Snapshot that can be used to indicate how the value was being accessed at
/// the time of an error.
#[derive(Debug)]
#[repr(transparent)]
struct Snapshot(isize);

impl fmt::Display for Snapshot {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 >> 1 {
            0 => write!(f, "fully accessible")?,
            1 => write!(f, "exclusively accessed")?,
            TAKEN => write!(f, "moved")?,
            n if n < 0 => write!(f, "shared by {}", -n)?,
            n => write!(f, "invalidly marked ({})", n)?,
        }

        if self.0 & IS_REF_MASK == 1 {
            write!(f, " (ref)")?;
        }

        Ok(())
    }
}

/// Access flags.
///
/// These accomplish the following things:
/// * Indicates if a value is a reference.
/// * Indicates if a value is exclusively held.
/// * Indicates if a value is shared, and if so by how many.
///
/// It has the following bit-pattern (assume isize is 16 bits for simplicity):
///
/// ```text
/// S0000000_00000000_00000000_0000000F
/// |                                ||
/// '-- Sign bit and number base ----'|
///                   Reference Flag -'
///
/// The reference flag is the LSB, and the rest is treated as a signed number
/// with the following properties:
/// * If the value is `0`, it is not being accessed.
/// * If the value is `1`, it is being exclusively accessed.
/// * If the value is negative `n`, it is being shared accessed by `-n` uses.
///
/// This means that the maximum number of accesses for a 64-bit `isize` is
/// `(1 << 62) - 1` uses.
///
/// ```
#[repr(transparent)]
pub(crate) struct Access(Cell<isize>);

impl Access {
    /// Construct a new default access.
    pub(crate) const fn new(is_ref: bool) -> Self {
        let initial = if is_ref { 1 } else { 0 };
        Self(Cell::new(initial))
    }

    /// Test if access is guarding a reference.
    #[inline]
    pub(crate) fn is_ref(&self) -> bool {
        self.0.get() & IS_REF_MASK != 0
    }

    /// Test if we can have shared access without modifying the internal count.
    #[inline]
    pub(crate) fn is_shared(&self) -> bool {
        self.get() <= 0
    }

    /// Test if we can have exclusive access without modifying the internal
    /// count.
    #[inline]
    pub(crate) fn is_exclusive(&self) -> bool {
        self.get() == 0
    }

    /// Test if the data has been taken.
    #[inline]
    pub(crate) fn is_taken(&self) -> bool {
        self.get() == TAKEN
    }

    /// Mark that we want shared access to the given access token.
    ///
    /// # Safety
    ///
    /// The returned guard must not outlive the access token that created it.
    #[inline]
    pub(crate) unsafe fn shared(
        &self,
        kind: AccessKind,
    ) -> Result<AccessGuard<'_>, NotAccessibleRef> {
        if let AccessKind::Owned = kind {
            if self.is_ref() {
                return Err(NotAccessibleRef(Snapshot(self.0.get())));
            }
        }

        let state = self.get();

        if state == MAX_USES {
            std::process::abort();
        }

        let n = state.wrapping_sub(1);

        if n >= 0 {
            return Err(NotAccessibleRef(Snapshot(self.0.get())));
        }

        self.set(n);
        Ok(AccessGuard(self))
    }

    /// Mark that we want exclusive access to the given access token.
    ///
    /// # Safety
    ///
    /// The returned guard must not outlive the access token that created it.
    #[inline]
    pub(crate) unsafe fn exclusive(
        &self,
        kind: AccessKind,
    ) -> Result<AccessGuard<'_>, NotAccessibleMut> {
        if let AccessKind::Owned = kind {
            if self.is_ref() {
                return Err(NotAccessibleMut(Snapshot(self.0.get())));
            }
        }

        let n = self.get();

        if n != 0 {
            return Err(NotAccessibleMut(Snapshot(self.0.get())));
        }

        self.set(n.wrapping_add(1));
        Ok(AccessGuard(self))
    }

    /// Mark that we want to mark the given access as "taken".
    ///
    /// I.e. whatever guarded data is no longer available.
    ///
    /// # Safety
    ///
    /// The returned guard must not outlive the access token that created it.
    #[inline]
    pub(crate) unsafe fn take(&self, kind: AccessKind) -> Result<RawTakeGuard, NotAccessibleTake> {
        if let AccessKind::Owned = kind {
            if self.is_ref() {
                return Err(NotAccessibleTake(Snapshot(self.0.get())));
            }
        }

        let state = self.get();

        if state != 0 {
            return Err(NotAccessibleTake(Snapshot(self.0.get())));
        }

        self.set(TAKEN);
        Ok(RawTakeGuard { access: self })
    }

    /// Release the current access level.
    #[inline]
    fn release(&self) {
        let b = self.get();

        let b = if b < 0 {
            debug_assert!(b < 0);
            b.wrapping_add(1)
        } else {
            debug_assert_eq!(b, 1, "borrow value should be exclusive (0)");
            b.wrapping_sub(1)
        };

        self.set(b);
    }

    /// Untake the current access.
    #[inline]
    fn release_take(&self) {
        let b = self.get();
        debug_assert_eq!(b, TAKEN, "borrow value should be TAKEN ({})", TAKEN);
        self.set(0);
    }

    /// Get the current value of the flag.
    #[inline]
    fn get(&self) -> isize {
        self.0.get() >> 1
    }

    /// Set the current value of the flag.
    #[inline]
    fn set(&self, value: isize) {
        self.0.set(self.0.get() & IS_REF_MASK | value << 1);
    }
}

impl fmt::Debug for Access {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", Snapshot(self.get()))
    }
}

/// Guard for a data borrowed from a slot in the virtual machine.
///
/// These guards are necessary, since we need to guarantee certain forms of
/// access depending on what we do. Releasing the guard releases the access.
pub struct BorrowRef<'a, T: ?Sized + 'a> {
    data: &'a T,
    guard: AccessGuard<'a>,
}

impl<'a, T: ?Sized> BorrowRef<'a, T> {
    /// Construct a new shared guard.
    ///
    /// # Safety
    ///
    /// since this has implications for releasing access, the caller must
    /// ensure that access has been acquired correctly using e.g.
    /// [Access::shared]. Otherwise access can be release incorrectly once
    /// this guard is dropped.
    pub(crate) fn new(data: &'a T, access: &'a Access) -> Self {
        Self {
            data,
            guard: AccessGuard(access),
        }
    }

    /// Map the reference.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use runestick::{BorrowRef, Shared};
    ///
    /// # fn main() -> runestick::Result<()> {
    /// let vec = Shared::<Vec<u32>>::new(vec![1, 2, 3, 4]);
    /// let vec = vec.borrow_ref()?;
    /// let value: BorrowRef<[u32]> = BorrowRef::map(vec, |vec| &vec[0..2]);
    ///
    /// assert_eq!(&*value, &[1u32, 2u32][..]);
    /// # Ok(()) }
    /// ```
    pub fn map<M, U: ?Sized>(this: Self, m: M) -> BorrowRef<'a, U>
    where
        M: FnOnce(&T) -> &U,
    {
        BorrowRef {
            data: m(this.data),
            guard: this.guard,
        }
    }

    /// Try to map the reference to a projection.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use runestick::{BorrowRef, Shared};
    ///
    /// # fn main() -> runestick::Result<()> {
    /// let vec = Shared::<Vec<u32>>::new(vec![1, 2, 3, 4]);
    /// let vec = vec.borrow_ref()?;
    /// let mut value: Option<BorrowRef<[u32]>> = BorrowRef::try_map(vec, |vec| vec.get(0..2));
    ///
    /// assert_eq!(value.as_deref(), Some(&[1u32, 2u32][..]));
    /// # Ok(()) }
    /// ```
    pub fn try_map<M, U: ?Sized>(this: Self, m: M) -> Option<BorrowRef<'a, U>>
    where
        M: FnOnce(&T) -> Option<&U>,
    {
        Some(BorrowRef {
            data: m(this.data)?,
            guard: this.guard,
        })
    }
}

impl<T: ?Sized> ops::Deref for BorrowRef<'_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.data
    }
}

impl<T: ?Sized> fmt::Debug for BorrowRef<'_, T>
where
    T: fmt::Debug,
{
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&**self, fmt)
    }
}

/// A guard around some specific access access.
#[repr(transparent)]
pub struct AccessGuard<'a>(&'a Access);

impl AccessGuard<'_> {
    /// Convert into a raw guard which does not have a lifetime associated with
    /// it. Droping the raw guard will release the resource.
    ///
    /// # Safety
    ///
    /// Since we're losing track of the lifetime, caller must ensure that the
    /// access outlives the guard.
    pub unsafe fn into_raw(self) -> RawAccessGuard {
        RawAccessGuard(ManuallyDrop::new(self).0)
    }
}

impl Drop for AccessGuard<'_> {
    fn drop(&mut self) {
        self.0.release();
    }
}

/// A raw guard around some level of access.
#[repr(transparent)]
pub struct RawAccessGuard(*const Access);

impl Drop for RawAccessGuard {
    fn drop(&mut self) {
        unsafe { (*self.0).release() }
    }
}

/// A taken access guard.
///
/// This is created with [Access::take], and must not outlive the [Access]
/// instance it was created from.
pub(crate) struct RawTakeGuard {
    access: *const Access,
}

impl Drop for RawTakeGuard {
    fn drop(&mut self) {
        unsafe { (*self.access).release_take() }
    }
}

/// Guard for data exclusively borrowed from a slot in the virtual machine.
///
/// These guards are necessary, since we need to guarantee certain forms of
/// access depending on what we do. Releasing the guard releases the access.
pub struct BorrowMut<'a, T: ?Sized> {
    data: &'a mut T,
    guard: AccessGuard<'a>,
}

impl<'a, T: ?Sized> BorrowMut<'a, T> {
    /// Construct a new exclusive guard.
    ///
    /// # Safety
    ///
    /// since this has implications for releasing access, the caller must
    /// ensure that access has been acquired correctly using e.g.
    /// [Access::exclusive]. Otherwise access can be release incorrectly once
    /// this guard is dropped.
    pub(crate) unsafe fn new(data: &'a mut T, access: &'a Access) -> Self {
        Self {
            data,
            guard: AccessGuard(access),
        }
    }

    /// Map the mutable reference.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use runestick::{BorrowMut, Shared};
    ///
    /// # fn main() -> runestick::Result<()> {
    /// let vec = Shared::<Vec<u32>>::new(vec![1, 2, 3, 4]);
    /// let vec = vec.borrow_mut()?;
    /// let value: BorrowMut<[u32]> = BorrowMut::map(vec, |vec| &mut vec[0..2]);
    ///
    /// assert_eq!(&*value, &mut [1u32, 2u32][..]);
    /// # Ok(()) }
    /// ```
    pub fn map<M, U: ?Sized>(this: Self, m: M) -> BorrowMut<'a, U>
    where
        M: FnOnce(&mut T) -> &mut U,
    {
        BorrowMut {
            data: m(this.data),
            guard: this.guard,
        }
    }

    /// Try to map the mutable reference to a projection.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use runestick::{BorrowMut, Shared};
    ///
    /// # fn main() -> runestick::Result<()> {
    /// let vec = Shared::<Vec<u32>>::new(vec![1, 2, 3, 4]);
    /// let vec = vec.borrow_mut()?;
    /// let mut value: Option<BorrowMut<[u32]>> = BorrowMut::try_map(vec, |vec| vec.get_mut(0..2));
    ///
    /// assert_eq!(value.as_deref_mut(), Some(&mut [1u32, 2u32][..]));
    /// # Ok(()) }
    /// ```
    pub fn try_map<M, U: ?Sized>(this: Self, m: M) -> Option<BorrowMut<'a, U>>
    where
        M: FnOnce(&mut T) -> Option<&mut U>,
    {
        Some(BorrowMut {
            data: m(this.data)?,
            guard: this.guard,
        })
    }
}

impl<T: ?Sized> ops::Deref for BorrowMut<'_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.data
    }
}

impl<T: ?Sized> ops::DerefMut for BorrowMut<'_, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.data
    }
}

impl<T: ?Sized> fmt::Debug for BorrowMut<'_, T>
where
    T: fmt::Debug,
{
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&**self, fmt)
    }
}

impl<F> Future for BorrowMut<'_, F>
where
    F: Unpin + Future,
{
    type Output = F::Output;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        // NB: inner Future is Unpin.
        let this = self.get_mut();
        Pin::new(&mut **this).poll(cx)
    }
}

#[cfg(test)]
mod tests {
    use super::{Access, AccessKind};

    #[test]
    fn test_non_ref() {
        unsafe {
            let access = Access::new(false);

            assert!(!access.is_ref());
            assert!(access.is_shared());
            assert!(access.is_exclusive());

            let guard = access.shared(AccessKind::Any).unwrap();

            assert!(!access.is_ref());
            assert!(access.is_shared());
            assert!(!access.is_exclusive());

            drop(guard);

            assert!(!access.is_ref());
            assert!(access.is_shared());
            assert!(access.is_exclusive());

            let guard = access.exclusive(AccessKind::Any).unwrap();

            assert!(!access.is_ref());
            assert!(!access.is_shared());
            assert!(!access.is_exclusive());

            drop(guard);

            assert!(!access.is_ref());
            assert!(access.is_shared());
            assert!(access.is_exclusive());
        }
    }

    #[test]
    fn test_ref() {
        unsafe {
            let access = Access::new(true);

            assert!(access.is_ref());
            assert!(access.is_shared());
            assert!(access.is_exclusive());

            let guard = access.shared(AccessKind::Any).unwrap();

            assert!(access.is_ref());
            assert!(access.is_shared());
            assert!(!access.is_exclusive());

            drop(guard);

            assert!(access.is_ref());
            assert!(access.is_shared());
            assert!(access.is_exclusive());

            let guard = access.exclusive(AccessKind::Any).unwrap();

            assert!(access.is_ref());
            assert!(!access.is_shared());
            assert!(!access.is_exclusive());

            drop(guard);

            assert!(access.is_ref());
            assert!(access.is_shared());
            assert!(access.is_exclusive());
        }
    }
}