Skip to main content

rspack_cacheable/
context.rs

1use std::{any::Any, ops::Deref, path::Path};
2
3use rkyv::{
4  de::{ErasedPtr, Pooling, PoolingState},
5  ser::{Sharing, sharing::SharingState},
6};
7
8use crate::error::{Error, Result};
9
10const CONTEXT_ADDR: usize = 0;
11unsafe fn default_drop(_: ErasedPtr) {}
12
13pub trait CacheableContext: Any {
14  /// Returns the project root used for portable path conversion.
15  ///
16  /// `Some` enables portable conversion relative to this root, while `None` keeps paths in their
17  /// native representation.
18  fn project_root(&self) -> Option<&Path>;
19}
20
21// Implement for unit type for convenience in tests and simple cases
22impl CacheableContext for () {
23  fn project_root(&self) -> Option<&Path> {
24    None
25  }
26}
27
28/// A context wrapper that provides shared context methods
29pub struct ContextGuard<'a> {
30  context: &'a dyn CacheableContext,
31}
32
33impl<'a> Deref for ContextGuard<'a> {
34  type Target = dyn CacheableContext;
35  fn deref(&self) -> &Self::Target {
36    self.context
37  }
38}
39
40impl<'a> ContextGuard<'a> {
41  pub fn new(context: &'a dyn CacheableContext) -> Self {
42    Self { context }
43  }
44
45  pub fn add_to_sharing<S: Sharing<Error> + ?Sized>(&self, sharing: &mut S) -> Result<()> {
46    sharing.start_sharing(CONTEXT_ADDR);
47    sharing.finish_sharing(CONTEXT_ADDR, self as *const _ as usize)
48  }
49
50  pub fn sharing_guard<S: Sharing<Error> + ?Sized>(sharing: &'a mut S) -> Result<&'a Self> {
51    match sharing.start_sharing(CONTEXT_ADDR) {
52      SharingState::Finished(addr) => {
53        let guard: &Self = unsafe { &*(addr as *const Self) };
54        Ok(guard)
55      }
56      _ => Err(Error::NoContext),
57    }
58  }
59
60  pub fn add_to_pooling<P: Pooling<Error> + ?Sized>(&self, pooling: &mut P) -> Result<()> {
61    unsafe {
62      let ctx_ptr = ErasedPtr::new(self as *const _ as *mut ());
63      pooling.start_pooling(CONTEXT_ADDR);
64      pooling.finish_pooling(CONTEXT_ADDR, ctx_ptr, default_drop)
65    }
66  }
67
68  pub fn pooling_guard<P: Pooling<Error> + ?Sized>(pooling: &'a mut P) -> Result<&'a Self> {
69    match pooling.start_pooling(CONTEXT_ADDR) {
70      PoolingState::Finished(ptr) => {
71        let guard: &Self = unsafe { &*(ptr.data_address() as *const Self) };
72        Ok(guard)
73      }
74      _ => Err(Error::NoContext),
75    }
76  }
77
78  pub fn downcast_context<T: 'static>(&'a self) -> Result<&'a T> {
79    (self.context as &dyn Any)
80      .downcast_ref()
81      .ok_or(Error::NoContext)
82  }
83}