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
#![cfg_attr(not(test), no_std)] //! Trait for requesting values by type from a given object. //! //! # Examples //! //! ## Using a Provider //! //! ``` //! # use object_provider::*; //! # use std::path::{Path, PathBuf}; //! # use std::fmt::Debug; //! # use std::pin::Pin; //! # struct MyProvider { //! # path: PathBuf, //! # } //! # impl ObjectProvider for MyProvider { //! # fn provide<'a>(&'a self, request: Pin<&mut Request<'a>>) { //! # request //! # .provide_ref::<PathBuf>(&self.path) //! # .provide_ref::<Path>(&self.path) //! # .provide_ref::<dyn Debug>(&self.path); //! # } //! # } //! # let my_path = Path::new("hello/world"); //! # let my_provider = MyProvider { path: my_path.to_owned() }; //! let provider: &dyn ObjectProvider; //! # provider = &my_provider; //! //! // It's possible to request concrete types like `PathBuf` //! let path_buf = provider.request_ref::<PathBuf>().unwrap(); //! assert_eq!(path_buf, my_path); //! //! // Requesting `!Sized` types, like slices and trait objects, is also supported. //! let path = provider.request_ref::<Path>().unwrap(); //! assert_eq!(path, my_path); //! //! let debug = provider.request_ref::<dyn Debug>().unwrap(); //! assert_eq!( //! format!("{:?}", debug), //! format!("{:?}", my_path), //! ); //! //! // Types or interfaces not explicitly provided return `None`. //! assert!(provider.request_ref::<i32>().is_none()); //! assert!(provider.request_ref::<dyn AsRef<Path>>().is_none()); //! ``` //! //! ## Implementing a Provider //! //! ``` //! # use object_provider::*; //! # use std::path::{Path, PathBuf}; //! # use std::fmt::Debug; //! # use std::pin::Pin; //! struct MyProvider { //! path: PathBuf, //! } //! //! impl ObjectProvider for MyProvider { //! fn provide<'a>(&'a self, request: Pin<&mut Request<'a>>) { //! request //! .provide_ref::<PathBuf>(&self.path) //! .provide_ref::<Path>(&self.path) //! .provide_ref::<dyn Debug>(&self.path); //! } //! } //! ``` use core::any::TypeId; use core::fmt; use core::marker::{PhantomData, PhantomPinned}; use core::pin::Pin; struct ReqRef<T: ?Sized + 'static>(&'static T); struct ReqVal<T: 'static>(T); /// A dynamic request for an object based on its type. #[repr(C)] pub struct Request<'a> { type_id: TypeId, _pinned: PhantomPinned, _marker: PhantomData<&'a ()>, } impl<'a> Request<'a> { /// Provides a reference of type `&'a T` in response to this request. /// /// If a reference of type `&'a T` has already been provided for this /// request, the existing value will be replaced by the newly provided /// value. /// /// This method can be chained within `provide` implementations to concisely /// provide multiple objects. pub fn provide_ref<T: ?Sized + 'static>(self: Pin<&mut Self>, value: &'a T) -> Pin<&mut Self> { self.provide_ref_with(|| value) } /// Lazily provides a reference of type `&'a T` in response to this request. /// /// If a reference of type `&'a T` has already been provided for this /// request, the existing value will be replaced by the newly provided /// value. /// /// The passed closure is only called if the value will be successfully /// provided. /// /// This method can be chained within `provide` implementations to concisely /// provide multiple objects. pub fn provide_ref_with<T: ?Sized + 'static, F>( mut self: Pin<&mut Self>, cb: F, ) -> Pin<&mut Self> where F: FnOnce() -> &'a T, { if self.is_ref::<T>() { // safety: `self.is_ref::<T>()` ensured the data field is `&'a T`. unsafe { *self.as_mut().downcast_unchecked::<&'a T>() = Some(cb()); } } self } /// Provides an value of type `T` in response to this request. /// /// If a value of type `T` has already been provided for this request, the /// existing value will be replaced by the newly provided value. /// /// This method can be chained within `provide` implementations to concisely /// provide multiple objects. pub fn provide_value<T: 'static>(self: Pin<&mut Self>, value: T) -> Pin<&mut Self> { self.provide_value_with(|| value) } /// Lazily provides a value of type `T` in response to this request. /// /// If a value of type `T` has already been provided for this request, the /// existing value will be replaced by the newly provided value. /// /// The passed closure is only called if the value will be successfully /// provided. /// /// This method can be chained within `provide` implementations to concisely /// provide multiple objects. pub fn provide_value_with<T: 'static, F>(mut self: Pin<&mut Self>, cb: F) -> Pin<&mut Self> where F: FnOnce() -> T, { if self.is_value::<T>() { // safety: `self.is_value::<T>()` ensured the data field is `T`. unsafe { *self.as_mut().downcast_unchecked::<T>() = Some(cb()); } } self } /// Returns `true` if the requested type is `&'a T` pub fn is_ref<T: ?Sized + 'static>(&self) -> bool { self.type_id == TypeId::of::<ReqRef<T>>() } /// Returns `true` if the requested type is `T` pub fn is_value<T: 'static>(&self) -> bool { self.type_id == TypeId::of::<ReqVal<T>>() } // internal implementation detail - performs an unchecked downcast. unsafe fn downcast_unchecked<T>(self: Pin<&mut Self>) -> &mut Option<T> { let ptr = self.get_unchecked_mut() as *mut Self as *mut RequestBuf<'a, T>; &mut (*ptr).value } /// Calls the provided closure with a request for the the type `&'a T`, /// returning `Some(&T)` if the request was fulfilled, and `None` otherwise. /// /// The `ObjectProviderExt` trait provides helper methods specifically for /// types implementing `ObjectProvider`. pub fn request_ref<T: ?Sized + 'static, F>(f: F) -> Option<&'a T> where F: FnOnce(Pin<&mut Request<'a>>), { let mut buf = RequestBuf::for_ref(); // safety: We never move `buf` after creating `pinned`. let mut pinned = unsafe { Pin::new_unchecked(&mut buf) }; f(pinned.as_mut().request()); pinned.take() } /// Calls the provided closure with a request for the the type `T`, /// returning `Some(T)` if the request was fulfilled, and `None` otherwise. /// /// The `ObjectProviderExt` trait provides helper methods specifically for /// types implementing `ObjectProvider`. pub fn request_value<T: 'static, F>(f: F) -> Option<T> where F: FnOnce(Pin<&mut Request<'a>>), { let mut buf = RequestBuf::for_value(); // safety: We never move `buf` after creating `pinned`. let mut pinned = unsafe { Pin::new_unchecked(&mut buf) }; f(pinned.as_mut().request()); pinned.take() } } impl<'a> fmt::Debug for Request<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Request") .field("type_id", &self.type_id) .finish() } } /// Low level buffer API used to create typed object requests. /// /// Due to a heavy dependency on [`Pin`], this type is inconvenient to use /// directly. Prefer using the [`ObjectProviderExt`] trait and [`Request::with`] /// APIs when possible. // Needs to have a known layout so we can do unsafe pointer shenanigans. #[repr(C)] #[derive(Debug)] struct RequestBuf<'a, T> { request: Request<'a>, value: Option<T>, } impl<'a, T: ?Sized + 'static> RequestBuf<'a, &'a T> { /// Create a new `RequestBuf` object. /// /// This type must be pinned before it can be used. fn for_ref() -> Self { // safety: ReqRef is a marker type for `&'a T` unsafe { Self::new_internal(TypeId::of::<ReqRef<T>>()) } } } impl<'a, T: 'static> RequestBuf<'a, T> { /// Create a new `RequestBuf` object. /// /// This type must be pinned before it can be used. fn for_value() -> Self { // safety: ReqVal is a marker type for `T` unsafe { Self::new_internal(TypeId::of::<ReqVal<T>>()) } } } impl<'a, T> RequestBuf<'a, T> { unsafe fn new_internal(type_id: TypeId) -> Self { RequestBuf { request: Request { type_id, _pinned: PhantomPinned, _marker: PhantomData, }, value: None, } } /// Get the untyped `Request` reference for this `RequestBuf`. fn request(self: Pin<&mut Self>) -> Pin<&mut Request<'a>> { // safety: projecting Pin onto our `request` field. unsafe { self.map_unchecked_mut(|this| &mut this.request) } } /// Take a value previously provided to this `RequestBuf`. fn take(self: Pin<&mut Self>) -> Option<T> { // safety: we don't project Pin onto our `value` field. unsafe { self.get_unchecked_mut().value.take() } } } /// Trait to provide other objects based on a requested type at runtime. /// /// See also the [`ObjectProviderExt`] trait which provides the `request` method. pub trait ObjectProvider { /// Provide an object of a given type in response to an untyped request. fn provide<'a>(&'a self, request: Pin<&mut Request<'a>>); } /// Methods supported by all [`ObjectProvider`] implementors. pub trait ObjectProviderExt { /// Request a reference of type `&T` from an object provider. fn request_ref<T: ?Sized + 'static>(&self) -> Option<&T>; /// Request an owned value of type `T` from an object provider. fn request_value<T: 'static>(&self) -> Option<T>; } impl<O: ?Sized + ObjectProvider> ObjectProviderExt for O { fn request_ref<T: ?Sized + 'static>(&self) -> Option<&T> { Request::request_ref::<T, _>(|req| self.provide(req)) } fn request_value<T: 'static>(&self) -> Option<T> { Request::request_value::<T, _>(|req| self.provide(req)) } } #[cfg(test)] mod test { use super::*; use std::path::{Path, PathBuf}; #[test] fn basic_context() { struct HasContext { int: i32, path: PathBuf, } impl ObjectProvider for HasContext { fn provide<'a>(&'a self, request: Pin<&mut Request<'a>>) { request .provide_ref::<i32>(&self.int) .provide_ref::<Path>(&self.path) .provide_ref::<dyn fmt::Display>(&self.int) .provide_value::<i32>(self.int); } } let provider: &dyn ObjectProvider = &HasContext { int: 10, path: PathBuf::new(), }; assert_eq!(provider.request_ref::<i32>(), Some(&10)); assert_eq!(provider.request_value::<i32>(), Some(10)); assert!(provider.request_ref::<u32>().is_none()); assert_eq!( provider .request_ref::<dyn fmt::Display>() .map(|d| d.to_string()), Some("10".to_owned()) ); assert!(provider.request_ref::<dyn fmt::Debug>().is_none()); assert_eq!(provider.request_ref::<Path>(), Some(Path::new(""))); } }