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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
//! The [`BorrowWithRefObj`][1] and [`BorrowMutWithRefObj`][2]
//! traits are versions of [`Borrow`][3] and [`BorrowMut`][4] that can return a reference
//! object (Such as `std::cell::Ref` or `std::sync::MutexGuard`) instead of just
//! a pointer.
//! 
//! This allows you to accept `T`, `&T`, `Rc<RefCell<T>>`, `Arc<Mutex<T>>`, and
//! `Arc<RwLock<T>>` by requiring a single trait.
//! 
//! Note: using these traits requires using higher-ranked trait bounds, [until
//! RFC 1598 is implemented][5].
//! See the example below.
//! 
//! # Example
//! ```
//! use borrow_with_ref_obj::BorrowWithRefObj;
//! 
//! /// Example structure that can possibly share ownership of a u32.
//! /// 
//! /// Modeled after a work queue getting data from a central source (ex. a
//! /// database) that may or may not be shared with others.
//! /// 
//! /// Note: Need to use higher-ranked trait bound here (for<'refr>), to tell
//! /// rust that the object that `borrow` returns about its lifetime.
//! struct Processor<Ref: for<'refr> BorrowWithRefObj<'refr, u32>> {
//! 	/// Potentially-shared reference to a datum.
//! 	/// Pretend this is a database connection or something like that.
//! 	data_source: Ref,
//! 	/// Queue of work to process
//! 	work_queue: Vec<u32>,
//! }
//! impl<Ref: for<'refr> BorrowWithRefObj<'refr, u32>> Processor<Ref> {
//! 	pub fn new(source: Ref) -> Self {
//! 		Self {
//! 			data_source: source,
//! 			work_queue: vec![1,2,3,4,5],
//! 		}
//! 	}
//! 	
//! 	/// Processes one element in the work queue
//! 	pub fn process_one(&mut self) {
//! 		let current_work = match self.work_queue.pop() {
//! 			Some(v) => v,
//! 			None => { return; }
//! 		};
//! 		let data_source = self.data_source.borrow();
//! 		let current_result = current_work + *data_source;
//! 		println!("{}", current_result);
//! 	}
//! 	
//! 	/// Processes all elements in the work queue
//! 	pub fn process_all(&mut self) {
//! 		while !self.work_queue.is_empty() {
//! 			self.process_one();
//! 		}
//! 	}
//! }
//! 
//! // Create a processor that is the sole owner of the data
//! let mut sole_owning_processor = Processor::new(1);
//! // Prints 2,3,4,5,6
//! sole_owning_processor.process_all();
//! 
//! // Creates a processor that borrows the data
//! let value = 2;
//! let mut borrowing_processor = Processor::new(&value);
//! // Prints 3,4,5,6,7
//! sole_owning_processor.process_all();
//! 
//! // Creates a processor that shares ownership via Rc<RefCell<u32>>
//! use std::rc::Rc;
//! use std::cell::RefCell;
//! 
//! let value = Rc::new(RefCell::new(1));
//! let mut rc_processor = Processor::new(Rc::clone(&value));
//! // Prints 2,3,4
//! rc_processor.process_one();
//! rc_processor.process_one();
//! rc_processor.process_one();
//! // Modify the value
//! *value.borrow_mut() = 5;
//! // Prints 9,10
//! rc_processor.process_one();
//! rc_processor.process_one();
//! 
//! // You can do the same as above with Arc<Mutex<T>> or Arc<RwLock<T>>, if you
//! // need thread-safe access.
//! ```
//! 
//! [1]: trait.BorrowWithRefObj.html
//! [2]: trait.BorrowMutWithRefObj.html
//! [3]: https://doc.rust-lang.org/std/borrow/trait.Borrow.html
//! [4]: https://doc.rust-lang.org/std/borrow/trait.BorrowMut.html
//! [5]: https://github.com/rust-lang/rfcs/blob/master/text/1598-generic_associated_types.md#push-hrtbs-harder-without-associated-type-constructors

use std::sync::Arc;
use std::rc::Rc;
use std::cell::{self, RefCell};
use std::ops::{Deref, DerefMut};
use std::sync::{self, Mutex, RwLock};

/// Immutable borrower whose reference is an object.
/// 
/// See the crate documentation for more info.
pub trait BorrowWithRefObj<'refr, T: 'refr + ?Sized> {
	/// Type of the reference object.
	type Reference: Deref<Target=T> + 'refr;
	
	/// Borrows the object immutably.
	/// 
	/// # Panics
	/// 
	/// May panic if borrowing a mutably-borrowed `RefCell`, a poisoned `Mutex`
	/// or `RwLock`, or some other implementation-defined issue.
	fn borrow(&'refr self) -> Self::Reference;
}

impl<'refr, T: 'refr + ?Sized> BorrowWithRefObj<'refr, T> for T {
	type Reference = &'refr T;
	fn borrow(&'refr self) -> Self::Reference { self }
}
impl<'refr, 'main, T: 'refr + ?Sized> BorrowWithRefObj<'refr, T> for &'main T {
	type Reference = &'refr T;
	fn borrow(&'refr self) -> Self::Reference { *self }
}
impl<'refr, T: 'refr + ?Sized> BorrowWithRefObj<'refr, T> for Box<T> {
	type Reference = &'refr T;
	fn borrow(&'refr self) -> Self::Reference { &*self }
}
impl<'refr, T: 'refr + ?Sized> BorrowWithRefObj<'refr, T> for Rc<RefCell<T>> {
	type Reference = cell::Ref<'refr, T>;
	fn borrow(&'refr self) -> Self::Reference { RefCell::borrow(self) }
}
impl<'refr, T: 'refr + ?Sized> BorrowWithRefObj<'refr, T> for Arc<Mutex<T>> {
	type Reference = sync::MutexGuard<'refr, T>;
	fn borrow(&'refr self) -> Self::Reference { self.lock().unwrap() }
}
impl<'refr, T: 'refr + ?Sized> BorrowWithRefObj<'refr, T> for Arc<RwLock<T>> {
	type Reference = sync::RwLockReadGuard<'refr, T>;
	fn borrow(&'refr self) -> Self::Reference { self.read().unwrap() }
}



/// Mutable borrower whose reference is an object.
/// 
/// See the crate documentation for more info.
pub trait BorrowMutWithRefObj<'refr, T: 'refr + ?Sized> {
	/// Type of the reference object.
	/// 
	/// Unlike `Borrow` and `BorrowMut`, the type may be (and usually is)
	/// different than the immutable version of the reference.
	type ReferenceMut: DerefMut<Target=T> + 'refr;
	
	/// Borrows the object mutably.
	/// 
	/// # Panics
	/// 
	/// May panic if borrowing a borrowed `RefCell`, a poisoned `Mutex`
	/// or `RwLock`, or some other implementation-defined issue.
	fn borrow_mut(&'refr mut self) -> Self::ReferenceMut;
}

impl<'refr, T: 'refr + ?Sized> BorrowMutWithRefObj<'refr, T> for T {
	type ReferenceMut = &'refr mut T;
	fn borrow_mut(&'refr mut self) -> Self::ReferenceMut { self }
}
impl<'refr, 'main, T: 'refr + ?Sized> BorrowMutWithRefObj<'refr, T> for &'main mut T {
	type ReferenceMut = &'refr mut T;
	fn borrow_mut(&'refr mut self) -> Self::ReferenceMut { *self }
}
impl<'refr, T: 'refr + ?Sized> BorrowMutWithRefObj<'refr, T> for Box<T> {
	type ReferenceMut = &'refr mut T;
	fn borrow_mut(&'refr mut self) -> Self::ReferenceMut { &mut *self }
}
impl<'refr, T: 'refr + ?Sized> BorrowMutWithRefObj<'refr, T> for Rc<RefCell<T>> {
	type ReferenceMut = cell::RefMut<'refr, T>;
	fn borrow_mut(&'refr mut self) -> Self::ReferenceMut { RefCell::borrow_mut(self) }
}
impl<'refr, T: 'refr + ?Sized> BorrowMutWithRefObj<'refr, T> for Arc<Mutex<T>> {
	type ReferenceMut = sync::MutexGuard<'refr, T>;
	fn borrow_mut(&'refr mut self) -> Self::ReferenceMut { self.lock().unwrap() }
}
impl<'refr, T: 'refr + ?Sized> BorrowMutWithRefObj<'refr, T> for Arc<RwLock<T>> {
	type ReferenceMut = sync::RwLockWriteGuard<'refr, T>;
	fn borrow_mut(&'refr mut self) -> Self::ReferenceMut { self.write().unwrap() }
}



/// Dynamic `BorrowWithRefObj` whose contents can be any `BorrowWithRefObj`.
/// 
/// This allows you to select a borrower object at runtime, and potentially swap
/// out the borrower for one with an underlying type.
/// 
/// If you don't care about storing `&T`, you can select `'main` to be `'static`.
/// 
/// # Example
/// ```
/// use borrow_with_ref_obj::{BorrowWithRefObj, BoxedBorrowWithRefObj};
/// 
/// struct Foo<Ref: for<'a> BorrowWithRefObj<'a, u32>> {
/// 	data: Ref
/// }
/// impl<Ref: for<'a> BorrowWithRefObj<'a, u32>> Foo<Ref> {
/// 	fn new(theref: Ref) -> Self {
/// 		Self { data: theref }
/// 	}
/// 	fn test(&self) {
/// 		let v = self.data.borrow();
/// 		assert_eq!(*v, 123);
/// 	}
/// }
/// 
/// // Create foo directly owning a boxed value
/// let mut foo = Foo::new(BoxedBorrowWithRefObj::from(Box::new(123)));
/// foo.test(); // passes
/// 
/// // Replace foo with one that owns the value via an Rc<RefCell<T>>.
/// // Note how while the way the data is owned is completely different, the type
/// // foo hasn't changed.
/// 
/// use std::rc::Rc;
/// use std::cell::RefCell;
/// let value = Rc::new(RefCell::new(123));
/// foo = Foo::new(BoxedBorrowWithRefObj::from(Box::new(Rc::clone(&value))));
/// foo.test(); // passes
/// ```
pub struct BoxedBorrowWithRefObj<'main, T: ?Sized> {
	theref: Box<for<'refr> DynBorrowWithRefObj<'refr, T>+'main>,
}
impl<'refr, 'main, T: ?Sized+'refr> BorrowWithRefObj<'refr, T> for BoxedBorrowWithRefObj<'main, T> {
	type Reference = BoxedReference<'refr, T>;
	fn borrow(&'refr self) -> Self::Reference {
		(*self.theref).borrow_boxed()
	}
}
impl<'main, T, Obj> From<Box<Obj>> for BoxedBorrowWithRefObj<'main, T>
where
	Obj: for<'refr> BorrowWithRefObj<'refr, T> + 'main,
	T: ?Sized + 'static /* TODO: should be `+ 'refr`, but no way to express that? */
{
	fn from(v: Box<Obj>) -> Self {
		Self { theref: v }
	}
}


/// Extention trait to add some dynamic-ness to `BorrowWithRefObj`
trait DynBorrowWithRefObj<'refr, T: ?Sized+'refr> {
	fn borrow_boxed(&'refr self) -> BoxedReference<'refr, T>;
}
impl<'refr, T: ?Sized+'refr, Target: BorrowWithRefObj<'refr, T>> DynBorrowWithRefObj<'refr, T> for Target {
	fn borrow_boxed(&'refr self) -> BoxedReference<'refr, T> {
		let underlying_ref = BorrowWithRefObj::borrow(self);
		BoxedReference::from(Box::new(underlying_ref))
	}
}



/// Dynamic `BorrowMutWithRefObj` whose contents can be any `BorrowMutWithRefObj`.
/// 
/// This is the mutable version of `BorrowWithRefObj`; see its documentation for
/// more information.
pub struct BoxedBorrowMutWithRefObj<'main, T: ?Sized> {
	theref: Box<for<'refr> DynBorrowMutWithRefObj<'refr, T>+'main>,
}
impl<'refr, 'main, T: ?Sized+'refr> BorrowMutWithRefObj<'refr, T> for BoxedBorrowMutWithRefObj<'main, T> {
	type ReferenceMut = BoxedMutReference<'refr, T>;
	fn borrow_mut(&'refr mut self) -> Self::ReferenceMut {
		(*self.theref).borrow_mut_boxed()
	}
}
impl<'main, T, Obj> From<Box<Obj>> for BoxedBorrowMutWithRefObj<'main, T>
where
	Obj: for<'refr> BorrowMutWithRefObj<'refr, T> + 'main,
	T: ?Sized + 'static /* TODO: should be `+ 'refr`, but no way to express that? */
{
	fn from(v: Box<Obj>) -> Self {
		Self { theref: v }
	}
}


/// Extention trait to add some dynamic-ness to `BorrowMutWithRefObj`
trait DynBorrowMutWithRefObj<'refr, T: ?Sized+'refr> {
	fn borrow_mut_boxed(&'refr mut self) -> BoxedMutReference<'refr, T>;
}
impl<'refr, T: ?Sized+'refr, Target: BorrowMutWithRefObj<'refr, T>> DynBorrowMutWithRefObj<'refr, T> for Target {
	fn borrow_mut_boxed(&'refr mut self) -> BoxedMutReference<'refr, T> {
		let underlying_ref = BorrowMutWithRefObj::borrow_mut(self);
		let boxed: Box<dyn DerefMut<Target=T>+'refr> = Box::new(underlying_ref);
		BoxedMutReference::from(boxed)
	}
}



/// Wrapper for `Box<dyn Deref<Target=T>` that dereferences directly to T.
/// 
/// Removes a layer of Deref.
/// 
/// The implementation of `BoxedBorrowWithRefObj` uses this type; you should
/// not need to use it yourself.
pub struct BoxedReference<'a, T: ?Sized> {
	pub boxed: Box<dyn Deref<Target=T>+'a>,
}
impl<'a, T: ?Sized, Target: Deref<Target=T>+'a> From<Box<Target>> for BoxedReference<'a, T> {
	fn from(boxed: Box<Target>) -> Self {
		Self { boxed: boxed as Box<dyn Deref<Target=T>+'a> }
	}
}
impl<'a, T: ?Sized> Into<Box<dyn Deref<Target=T>+'a>> for BoxedReference<'a, T> {
	fn into(self) -> Box<dyn Deref<Target=T>+'a> {
		self.boxed
	}
}
impl<'a, T: ?Sized> Deref for BoxedReference<'a, T> {
	type Target = T;
	fn deref(&self) -> &Self::Target {
		(*self.boxed).deref()
	}
}



/// Wrapper for `Box<dyn DerefMut<Target=T>` that dereferences directly to T.
/// 
/// Removes a layer of DerefMut.
/// 
/// The implementation of `BoxedBorrowMutWithRefObj` uses this type; you should
/// not need to use it yourself.
pub struct BoxedMutReference<'a, T: ?Sized> {
	pub boxed: Box<dyn DerefMut<Target=T>+'a>,
}
impl<'a, T: ?Sized> From<Box<dyn DerefMut<Target=T>+'a>> for BoxedMutReference<'a, T> {
	fn from(boxed: Box<dyn DerefMut<Target=T>+'a>) -> Self {
		Self { boxed }
	}
}
impl<'a, T: ?Sized> Into<Box<dyn DerefMut<Target=T>+'a>> for BoxedMutReference<'a, T> {
	fn into(self) -> Box<dyn DerefMut<Target=T>+'a> {
		self.boxed
	}
}
impl<'a, T: ?Sized> Deref for BoxedMutReference<'a, T> {
	type Target = T;
	fn deref(&self) -> &Self::Target {
		(*self.boxed).deref()
	}
}
impl<'a, T: ?Sized> DerefMut for BoxedMutReference<'a, T> {
	fn deref_mut(&mut self) -> &mut Self::Target {
		(*self.boxed).deref_mut()
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	
	struct BorrowingStruct<Ref: for<'refr> BorrowWithRefObj<'refr, u32>> {
		theref: Ref,
	}
	impl<Ref: for<'refr> BorrowWithRefObj<'refr, u32>> BorrowingStruct<Ref> {
		fn new(theref: Ref) -> Self {
			Self { theref }
		}
		
		fn test(&self) {
			assert_eq!(*self.theref.borrow(), 123);
		}
	}
	
	#[test]
	fn move_value() {
		let value: u32 = 123;
		let borrower = BorrowingStruct::new(value);
		borrower.test();
	}
	
	#[test]
	fn ref_value() {
		let value: u32 = 123;
		let borrower = BorrowingStruct::new(&value);
		borrower.test();
		assert_eq!(value, 123);
	}
	
	#[test]
	fn rc_refcell_value() {
		let value = Rc::new(RefCell::new(123));
		let borrower = BorrowingStruct::new(Rc::clone(&value));
		borrower.test();
		assert_eq!(*RefCell::borrow(&*value), 123);
	}
	
	#[test]
	fn arc_mutex_value() {
		let value = Arc::new(Mutex::new(123));
		let borrower = BorrowingStruct::new(Arc::clone(&value));
		borrower.test();
		assert_eq!(*Mutex::lock(&*value).unwrap(), 123);
	}
	
	#[test]
	fn arc_rwlock_value() {
		let value = Arc::new(RwLock::new(123));
		let borrower = BorrowingStruct::new(Arc::clone(&value));
		borrower.test();
		assert_eq!(*RwLock::read(&*value).unwrap(), 123);
	}
	
	
	
	struct BorrowingMutStruct<Ref: for<'refr> BorrowMutWithRefObj<'refr, u32>> {
		theref: Ref,
	}
	impl<Ref: for<'refr> BorrowMutWithRefObj<'refr, u32>> BorrowingMutStruct<Ref> {
		fn new(theref: Ref) -> Self {
			Self { theref }
		}
		
		fn modify(&mut self) {
			*self.theref.borrow_mut() = 456;
		}
		
		fn test(&mut self) {
			assert_eq!(*self.theref.borrow_mut(), 456);
		}
	}
	
	#[test]
	fn mut_move_value() {
		let value: u32 = 123;
		let mut borrower = BorrowingMutStruct::new(value);
		borrower.modify();
		borrower.test();
	}
	
	#[test]
	fn mut_ref_value() {
		let mut value = 123;
		{
			let mut borrower = BorrowingMutStruct::new(&mut value);
			borrower.modify();
			borrower.test();
		}
		assert_eq!(value, 456);
	}
	
	#[test]
	fn mut_rc_refcell_value() {
		let value = Rc::new(RefCell::new(123));
		let mut borrower = BorrowingMutStruct::new(Rc::clone(&value));
		borrower.modify();
		borrower.test();
		assert_eq!(*RefCell::borrow(&*value), 456);
	}
	
	#[test]
	fn mut_arc_mutex_value() {
		let value = Arc::new(Mutex::new(123));
		let mut borrower = BorrowingMutStruct::new(Arc::clone(&value));
		borrower.modify();
		borrower.test();
		assert_eq!(*Mutex::lock(&*value).unwrap(), 456);
	}
	
	#[test]
	fn mut_arc_rwlock_value() {
		let value = Arc::new(RwLock::new(123));
		let mut borrower = BorrowingMutStruct::new(Arc::clone(&value));
		borrower.modify();
		borrower.test();
		assert_eq!(*RwLock::read(&*value).unwrap(), 456);
	}
	
	
	
	#[test]
	fn boxed_borrow() {
		let mut borrower = BorrowingStruct::new(BoxedBorrowWithRefObj::from(Box::new(123)));
		borrower.test();
		
		let value = Rc::new(RefCell::new(123));
		borrower = BorrowingStruct::new(BoxedBorrowWithRefObj::from(Box::new(Rc::clone(&value))));
		borrower.test();
	}
	
	#[test]
	fn boxed_mut_borrow() {
		let mut borrower = BorrowingMutStruct::new(BoxedBorrowMutWithRefObj::from(Box::new(123)));
		borrower.modify();
		borrower.test();
		
		let value = Rc::new(RefCell::new(123));
		borrower = BorrowingMutStruct::new(BoxedBorrowMutWithRefObj::from(Box::new(Rc::clone(&value))));
		borrower.modify();
		borrower.test();
		assert_eq!(*RefCell::borrow(&*value), 456);
	}
}