fp_library/classes/pointer.rs
1//! Hierarchy of traits for abstracting over different types of pointers 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 fp_macros::doc_params;
21use fp_macros::doc_type_params;
22use fp_macros::hm_signature;
23use std::ops::Deref;
24
25/// Base type class for heap-allocated pointers.
26///
27/// This is the minimal abstraction: any type that can wrap a value and
28/// dereference to it. Does NOT require Clone — that's added by subtraits.
29pub trait Pointer {
30 /// The pointer type constructor.
31 ///
32 /// For `RcBrand`, this is `Rc<T>`. For `BoxBrand`, this would be `Box<T>`.
33 type Of<T: ?Sized>: Deref<Target = T>;
34
35 /// Wraps a sized value in the pointer.
36 ///
37 /// ### Type Signature
38 ///
39 #[hm_signature]
40 ///
41 /// ### Type Parameters
42 ///
43 #[doc_type_params("The type of the value to wrap.")]
44 ///
45 /// ### Parameters
46 ///
47 #[doc_params("The value to wrap.")]
48 ///
49 /// ### Returns
50 ///
51 /// The value wrapped in the pointer type.
52 ///
53 /// ### Examples
54 ///
55 /// ```
56 /// use fp_library::{brands::*, classes::*};
57 ///
58 /// let ptr = <RcBrand as Pointer>::new(42);
59 /// assert_eq!(*ptr, 42);
60 /// ```
61 fn new<T>(value: T) -> Self::Of<T>
62 where
63 Self::Of<T>: Sized;
64}
65
66/// Wraps a sized value in the pointer.
67///
68/// ### Type Signature
69///
70#[hm_signature(Pointer)]
71///
72/// ### Type Parameters
73///
74#[doc_type_params("The pointer brand.", "The type of the value to wrap.")]
75///
76/// ### Parameters
77///
78#[doc_params("The value to wrap.")]
79///
80/// ### Returns
81///
82/// The value wrapped in the pointer type.
83///
84/// ### Examples
85///
86/// ```
87/// use fp_library::{brands::*, functions::*};
88///
89/// let ptr = pointer_new::<RcBrand, _>(42);
90/// assert_eq!(*ptr, 42);
91/// ```
92pub fn new<P: Pointer, T>(value: T) -> P::Of<T>
93where
94 P::Of<T>: Sized,
95{
96 P::new(value)
97}