Skip to main content

fp_library/classes/
pointer.rs

1//! A hierarchy of traits for abstracting over different types of pointers, specifically focusing on reference-counted pointers ([`Rc`](`std::rc::Rc`), [`Arc`](std::sync::Arc)) and their capabilities.
2//!
3//! The hierarchy is as follows:
4//! * [`Pointer`]: Base trait for any heap-allocated pointer.
5//! * [`RefCountedPointer`][super::ref_counted_pointer::RefCountedPointer]: Extension for pointers that allow shared ownership (cloning).
6//! * [`SendRefCountedPointer`][super::send_ref_counted_pointer::SendRefCountedPointer]: Extension for thread-safe reference-counted pointers.
7//!
8//! Additionally, [`UnsizedCoercible`][super::unsized_coercible::UnsizedCoercible] and [`SendUnsizedCoercible`][super::send_unsized_coercible::SendUnsizedCoercible] are provided to support
9//! coercing sized closures into trait objects (`dyn Fn`).
10//!
11//! ### Examples
12//!
13//! ```
14//! use fp_library::{brands::*, functions::*};
15//!
16//! let ptr = pointer_new::<RcBrand, _>(42);
17//! assert_eq!(*ptr, 42);
18//! ```
19
20use std::ops::Deref;
21
22/// Base type class for heap-allocated pointers.
23///
24/// This is the minimal abstraction: any type that can wrap a value and
25/// dereference to it. Does NOT require Clone — that's added by subtraits.
26pub trait Pointer {
27	/// The pointer type constructor.
28	///
29	/// For `RcBrand`, this is `Rc<T>`. For `BoxBrand`, this would be `Box<T>`.
30	type Of<T: ?Sized>: Deref<Target = T>;
31
32	/// Wraps a sized value in the pointer.
33	///
34	/// ### Type Signature
35	///
36	/// `forall a. a -> Pointer a`
37	///
38	/// ### Type Parameters
39	///
40	/// * `T`: The type of the value to wrap.
41	///
42	/// ### Parameters
43	///
44	/// * `value`: The value to wrap.
45	///
46	/// ### Returns
47	///
48	/// The value wrapped in the pointer type.
49	///
50	/// ### Examples
51	///
52	/// ```
53	/// use fp_library::{brands::*, classes::*};
54	///
55	/// let ptr = <RcBrand as Pointer>::new(42);
56	/// assert_eq!(*ptr, 42);
57	/// ```
58	fn new<T>(value: T) -> Self::Of<T>
59	where
60		Self::Of<T>: Sized;
61}
62
63/// Wraps a sized value in the pointer.
64///
65/// ### Type Signature
66///
67/// `forall p a. Pointer p => a -> Pointer a`
68///
69/// ### Type Parameters
70///
71/// * `P`: The pointer brand.
72/// * `T`: The type of the value to wrap.
73///
74/// ### Parameters
75///
76/// * `value`: The value to wrap.
77///
78/// ### Returns
79///
80/// The value wrapped in the pointer type.
81///
82/// ### Examples
83///
84/// ```
85/// use fp_library::{brands::*, functions::*};
86///
87/// let ptr = pointer_new::<RcBrand, _>(42);
88/// assert_eq!(*ptr, 42);
89/// ```
90pub fn new<P: Pointer, T>(value: T) -> P::Of<T>
91where
92	P::Of<T>: Sized,
93{
94	P::new(value)
95}