lock.rs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. use core::ops::{Deref, DerefMut};
  2. /// ValidLock is a trait that needs to be implemented for locks used internally within XArray.
  3. /// It abstracts the functionalities of the necessary locks inside.
  4. pub trait ValidLock<T>: Sized {
  5. type Target<'a>: Deref<Target = T> + DerefMut<Target = T>
  6. where
  7. Self: 'a;
  8. fn new(inner: T) -> Self;
  9. fn lock(&self) -> Self::Target<'_>;
  10. }
  11. /// XLock represents a HKT (Higher-Kinded Type) abstraction of ValidLock used within XArray,
  12. /// leveraging Rust's GAT (Generic Associated Types) to empower an HKT.
  13. ///
  14. /// This trait is typically auto-implemented via the abstract_lock_to! macro. For example, for a lock type Mutex<T>,
  15. /// using `abstract_lock_to!(Mutex, XMutex);` yields the corresponding higher-kinded type XMutex,
  16. /// which is automatically implemented with the XLock trait inside the macro. This allows XMutex to serve any type T,
  17. /// obtaining the corresponding Mutex<T> by using `XMutex::Lock<T>`.
  18. pub trait XLock {
  19. type Lock<T>: ValidLock<T>;
  20. fn new<T>(inner: T) -> Self::Lock<T> {
  21. Self::Lock::<T>::new(inner)
  22. }
  23. }
  24. #[macro_export]
  25. /// Abstract a lock type that implements `ValidLock` to its HKT (Higher-Kinded Type) struct.
  26. /// The first parameter is the source type name and the second parameter is the HKT type name.
  27. /// This HKT type will implement `XLock` trait automatically and can be used as a generic parameter
  28. /// for `XArray`.
  29. macro_rules! abstract_lock_to {
  30. ($lock_type:ident, $name:ident) => {
  31. pub struct $name;
  32. impl XLock for $name {
  33. type Lock<T> = $lock_type<T>;
  34. }
  35. };
  36. }
  37. #[cfg(feature = "std")]
  38. pub mod std_specific {
  39. extern crate std;
  40. use crate::*;
  41. use std::sync::{Mutex, MutexGuard};
  42. impl<T> ValidLock<T> for Mutex<T> {
  43. type Target<'a> = MutexGuard<'a, T>
  44. where T: 'a;
  45. fn new(inner: T) -> Self {
  46. Mutex::new(inner)
  47. }
  48. fn lock(&self) -> Self::Target<'_> {
  49. self.lock().unwrap()
  50. }
  51. }
  52. abstract_lock_to!(Mutex, StdMutex);
  53. }