1#![warn(missing_docs)]
2
3extern crate maybe_dangling;
251use maybe_dangling::MaybeDangling;
252extern crate stable_deref_trait;
253pub use stable_deref_trait::{StableDeref as StableAddress, CloneStableDeref as CloneStableAddress};
254use std::marker::PhantomData;
255
256pub struct OwningRef<'t, O, T: ?Sized> {
266 owner: MaybeDangling<O>,
267 reference: *const T,
268 marker: PhantomData<&'t T>,
269}
270
271pub struct OwningRefMut<'t, O, T: ?Sized> {
281 owner: MaybeDangling<O>,
282 reference: *mut T,
283 marker: PhantomData<&'t T>,
284}
285
286pub trait Erased {}
290impl<T> Erased for T {}
291
292pub unsafe trait IntoErased<'a> {
296 type Erased;
298 fn into_erased(self) -> Self::Erased;
300}
301
302impl<'t, O, T: ?Sized> OwningRef<'t, O, T> {
307 pub fn new(o: O) -> Self
321 where O: StableAddress,
322 O: Deref<Target = T>,
323 {
324 let owner = MaybeDangling::new(o);
325 OwningRef {
326 reference: &**owner,
327 owner,
328 marker: PhantomData,
329 }
330 }
331
332 pub unsafe fn new_assert_stable_address(o: O) -> Self
338 where O: Deref<Target = T>,
339 {
340 let owner = MaybeDangling::new(o);
341 OwningRef {
342 reference: &**owner,
343 owner,
344 marker: PhantomData,
345 }
346 }
347
348 pub fn map<F, U: ?Sized>(self, f: F) -> OwningRef<'t, O, U>
369 where O: StableAddress,
370 F: FnOnce(&T) -> &U
371 {
372 OwningRef {
373 reference: f(&self),
374 owner: self.owner,
375 marker: PhantomData,
376 }
377 }
378
379 #[deprecated(since = "0.5.0", note = "unsafe function: please use map_with_owner instead")]
381 pub unsafe fn map_with_owner_direct<F, U: ?Sized>(self, f: F) -> OwningRef<'t, O, U>
382 where O: StableAddress,
383 F: for<'a> FnOnce(&'a O, &'a T) -> &'a U
384 {
385 OwningRef {
386 reference: f(&self.owner, &self),
387 owner: self.owner,
388 marker: PhantomData,
389 }
390 }
391
392 pub fn map_with_owner<F, U: ?Sized>(self, f: F) -> OwningRef<'t, O, U>
415 where O: StableAddress + Deref,
416 F: for<'a> FnOnce(&'a O::Target, &'a T) -> &'a U
417 {
418 OwningRef {
419 reference: f(&self.owner, &self),
420 owner: self.owner,
421 marker: PhantomData,
422 }
423 }
424
425 pub fn try_map<F, U: ?Sized, E>(self, f: F) -> Result<OwningRef<'t, O, U>, E>
448 where O: StableAddress,
449 F: FnOnce(&T) -> Result<&U, E>
450 {
451 Ok(OwningRef {
452 reference: f(&self)?,
453 owner: self.owner,
454 marker: PhantomData,
455 })
456 }
457
458 #[deprecated(since = "0.5.0", note = "unsafe function: please use try_map_with_owner instead")]
469 pub unsafe fn try_map_with_owner_direct<F, U: ?Sized, E>(self, f: F) -> Result<OwningRef<'t, O, U>, E>
470 where O: StableAddress,
471 F: for<'a> FnOnce(&'a O, &'a T) -> Result<&'a U, E>
472 {
473 Ok(OwningRef {
474 reference: f(&self.owner, &self)?,
475 owner: self.owner,
476 marker: PhantomData,
477 })
478 }
479
480 pub fn try_map_with_owner<F, U: ?Sized, E>(self, f: F) -> Result<OwningRef<'t, O, U>, E>
504 where O: StableAddress + Deref,
505 F: for<'a> FnOnce(&'a O::Target, &'a T) -> Result<&'a U, E>
506 {
507 Ok(OwningRef {
508 reference: f(&self.owner, &self)?,
509 owner: self.owner,
510 marker: PhantomData,
511 })
512 }
513
514 pub unsafe fn map_owner<F, P>(self, f: F) -> OwningRef<'t, P, T>
520 where O: StableAddress,
521 P: StableAddress,
522 F: FnOnce(O) -> P
523 {
524 OwningRef {
525 reference: self.reference,
526 owner: MaybeDangling::new(f(MaybeDangling::into_inner(self.owner))),
527 marker: PhantomData,
528 }
529 }
530
531 pub fn map_owner_box(self) -> OwningRef<'t, Box<O>, T> {
537 OwningRef {
538 reference: self.reference,
539 owner: MaybeDangling::new(Box::new(MaybeDangling::into_inner(self.owner))),
540 marker: PhantomData,
541 }
542 }
543
544 pub fn erase_owner<'a>(self) -> OwningRef<'t, O::Erased, T>
577 where O: IntoErased<'a>,
578 {
579 OwningRef {
580 reference: self.reference,
581 owner: MaybeDangling::new(MaybeDangling::into_inner(self.owner).into_erased()),
582 marker: PhantomData,
583 }
584 }
585
586 pub fn as_owner(&self) -> &O {
590 &self.owner
591 }
592
593 pub fn into_owner(self) -> O {
595 MaybeDangling::into_inner(self.owner)
596 }
597}
598
599impl<'t, O, T: ?Sized> OwningRefMut<'t, O, T> {
600 pub fn new(o: O) -> Self
614 where O: StableAddress,
615 O: DerefMut<Target = T>,
616 {
617 let mut owner = MaybeDangling::new(o);
618 OwningRefMut {
619 reference: &mut **owner,
620 owner,
621 marker: PhantomData,
622 }
623 }
624
625 pub unsafe fn new_assert_stable_address(o: O) -> Self
631 where O: DerefMut<Target = T>,
632 {
633 let mut owner = MaybeDangling::new(o);
634 OwningRefMut {
635 reference: &mut **owner,
636 owner,
637 marker: PhantomData,
638 }
639 }
640
641 #[deprecated(since = "0.5.0", note = "unsafe function. can create aliased references")]
663 pub unsafe fn map<F, U: ?Sized>(mut self, f: F) -> OwningRef<'t, O, U>
664 where O: StableAddress,
665 F: FnOnce(&mut T) -> &U
666 {
667 OwningRef {
668 reference: f(&mut self),
669 owner: self.owner,
670 marker: PhantomData,
671 }
672 }
673
674 pub fn map_mut<F, U: ?Sized>(mut self, f: F) -> OwningRefMut<'t, O, U>
695 where O: StableAddress,
696 F: FnOnce(&mut T) -> &mut U
697 {
698 OwningRefMut {
699 reference: f(&mut self),
700 owner: self.owner,
701 marker: PhantomData,
702 }
703 }
704
705 #[deprecated(since = "0.5.0", note = "unsafe function. can create aliased references")]
731 pub unsafe fn try_map<F, U: ?Sized, E>(mut self, f: F) -> Result<OwningRef<'t, O, U>, E>
732 where O: StableAddress,
733 F: FnOnce(&mut T) -> Result<&U, E>
734 {
735 Ok(OwningRef {
736 reference: f(&mut self)?,
737 owner: self.owner,
738 marker: PhantomData,
739 })
740 }
741
742 pub fn try_map_mut<F, U: ?Sized, E>(mut self, f: F) -> Result<OwningRefMut<'t, O, U>, E>
765 where O: StableAddress,
766 F: FnOnce(&mut T) -> Result<&mut U, E>
767 {
768 Ok(OwningRefMut {
769 reference: f(&mut self)?,
770 owner: self.owner,
771 marker: PhantomData,
772 })
773 }
774
775 pub unsafe fn map_owner<F, P>(self, f: F) -> OwningRefMut<'t, P, T>
781 where O: StableAddress,
782 P: StableAddress,
783 F: FnOnce(O) -> P
784 {
785 OwningRefMut {
786 reference: self.reference,
787 owner: MaybeDangling::new(f(MaybeDangling::into_inner(self.owner))),
788 marker: PhantomData,
789 }
790 }
791
792 pub fn map_owner_box(self) -> OwningRefMut<'t, Box<O>, T> {
798 OwningRefMut {
799 reference: self.reference,
800 owner: MaybeDangling::new(Box::new(MaybeDangling::into_inner(self.owner))),
801 marker: PhantomData,
802 }
803 }
804
805 pub fn erase_owner<'a>(self) -> OwningRefMut<'t, O::Erased, T>
838 where O: IntoErased<'a>,
839 {
840 OwningRefMut {
841 reference: self.reference,
842 owner: MaybeDangling::new(MaybeDangling::into_inner(self.owner).into_erased()),
843 marker: PhantomData,
844 }
845 }
846
847 #[deprecated(since = "0.5.0", note = "unsafe function. can create aliased references")]
849 pub unsafe fn as_owner(&self) -> &O {
850 &self.owner
851 }
852
853 #[deprecated(since = "0.5.0", note = "unsafe function. can create aliased references")]
855 pub unsafe fn as_owner_mut(&mut self) -> &mut O {
856 &mut self.owner
857 }
858
859 pub fn into_owner(self) -> O {
861 MaybeDangling::into_inner(self.owner)
862 }
863}
864
865use std::ops::{Deref, DerefMut};
870
871pub struct OwningHandle<O, H>
891 where O: StableAddress, H: Deref,
892{
893 handle: H,
894 _owner: MaybeDangling<O>,
895}
896
897impl<O, H> Deref for OwningHandle<O, H>
898 where O: StableAddress, H: Deref,
899{
900 type Target = H::Target;
901 fn deref(&self) -> &H::Target {
902 self.handle.deref()
903 }
904}
905
906unsafe impl<O, H> StableAddress for OwningHandle<O, H>
907 where O: StableAddress, H: StableAddress,
908{}
909
910impl<O, H> DerefMut for OwningHandle<O, H>
911 where O: StableAddress, H: DerefMut,
912{
913 fn deref_mut(&mut self) -> &mut H::Target {
914 self.handle.deref_mut()
915 }
916}
917
918pub trait ToHandle {
920 type Handle: Deref;
922
923 unsafe fn to_handle(x: *const Self) -> Self::Handle;
926}
927
928pub trait ToHandleMut {
930 type HandleMut: DerefMut;
932
933 unsafe fn to_handle_mut(x: *const Self) -> Self::HandleMut;
936}
937
938impl<O, H> OwningHandle<O, H>
939 where O: StableAddress, O::Target: ToHandle<Handle = H>, H: Deref,
940{
941 pub fn new(o: O) -> Self {
945 OwningHandle::new_with_fn(o, |x| unsafe { O::Target::to_handle(x) })
946 }
947}
948
949impl<O, H> OwningHandle<O, H>
950 where O: StableAddress, O::Target: ToHandleMut<HandleMut = H>, H: DerefMut,
951{
952 pub fn new_mut(o: O) -> Self {
954 OwningHandle::new_with_fn(o, |x| unsafe { O::Target::to_handle_mut(x) })
955 }
956}
957
958impl<O, H> OwningHandle<O, H>
959 where O: StableAddress, H: Deref,
960{
961 pub fn new_with_fn<F>(o: O, f: F) -> Self
966 where F: FnOnce(*const O::Target) -> H
967 {
968 let o = MaybeDangling::new(o);
969 let h: H = f(&**o as *const O::Target);
970
971 OwningHandle {
972 handle: h,
973 _owner: o,
974 }
975 }
976
977 pub fn try_new<F, E>(o: O, f: F) -> Result<Self, E>
982 where F: FnOnce(*const O::Target) -> Result<H, E>
983 {
984
985 let o = MaybeDangling::new(o);
986 let h: H = f(&**o as *const O::Target)?;
987
988 Ok(OwningHandle {
989 handle: h,
990 _owner: o,
991 })
992 }
993
994 pub fn as_owner(&self) -> &O {
996 &self._owner
997 }
998
999 pub fn into_owner(self) -> O {
1001 MaybeDangling::into_inner(self._owner)
1002 }
1003}
1004
1005use std::convert::From;
1010use std::fmt::{self, Debug};
1011use std::marker::{Send, Sync};
1012use std::cmp::{Eq, PartialEq, Ord, PartialOrd, Ordering};
1013use std::hash::{Hash, Hasher};
1014use std::borrow::{Borrow, BorrowMut};
1015
1016impl<'t, O, T: ?Sized> Deref for OwningRef<'t, O, T> {
1017 type Target = T;
1018
1019 fn deref(&self) -> &T {
1020 unsafe {
1021 &*self.reference
1022 }
1023 }
1024}
1025
1026impl<'t, O, T: ?Sized> Deref for OwningRefMut<'t, O, T> {
1027 type Target = T;
1028
1029 fn deref(&self) -> &T {
1030 unsafe {
1031 &*self.reference
1032 }
1033 }
1034}
1035
1036impl<'t, O, T: ?Sized> DerefMut for OwningRefMut<'t, O, T> {
1037 fn deref_mut(&mut self) -> &mut T {
1038 unsafe {
1039 &mut *self.reference
1040 }
1041 }
1042}
1043
1044unsafe impl<'t, O, T: ?Sized> StableAddress for OwningRef<'t, O, T> {}
1045
1046unsafe impl<'t, O, T: ?Sized> StableAddress for OwningRefMut<'t, O, T> {}
1047
1048impl<'t, O, T: ?Sized> AsRef<T> for OwningRef<'t, O, T> {
1049 fn as_ref(&self) -> &T {
1050 &*self
1051 }
1052}
1053
1054impl<'t, O, T: ?Sized> AsRef<T> for OwningRefMut<'t, O, T> {
1055 fn as_ref(&self) -> &T {
1056 &*self
1057 }
1058}
1059
1060impl<'t, O, T: ?Sized> AsMut<T> for OwningRefMut<'t, O, T> {
1061 fn as_mut(&mut self) -> &mut T {
1062 &mut *self
1063 }
1064}
1065
1066impl<'t, O, T: ?Sized> Borrow<T> for OwningRef<'t, O, T> {
1067 fn borrow(&self) -> &T {
1068 &*self
1069 }
1070}
1071
1072impl<'t, O, T: ?Sized> Borrow<T> for OwningRefMut<'t, O, T> {
1073 fn borrow(&self) -> &T {
1074 &*self
1075 }
1076}
1077
1078impl<'t, O, T: ?Sized> BorrowMut<T> for OwningRefMut<'t, O, T> {
1079 fn borrow_mut(&mut self) -> &mut T {
1080 &mut *self
1081 }
1082}
1083
1084impl<'t, O, T: ?Sized> From<O> for OwningRef<'t, O, T>
1085 where O: StableAddress,
1086 O: Deref<Target = T>,
1087{
1088 fn from(owner: O) -> Self {
1089 OwningRef::new(owner)
1090 }
1091}
1092
1093impl<'t, O, T: ?Sized> From<O> for OwningRefMut<'t, O, T>
1094 where O: StableAddress,
1095 O: DerefMut<Target = T>
1096{
1097 fn from(owner: O) -> Self {
1098 OwningRefMut::new(owner)
1099 }
1100}
1101
1102impl<'t, O, T: ?Sized> Debug for OwningRef<'t, O, T>
1105 where O: Debug,
1106 T: Debug,
1107{
1108 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1109 write!(f,
1110 "OwningRef {{ owner: {:?}, reference: {:?} }}",
1111 self.as_owner(),
1112 &**self)
1113 }
1114}
1115
1116impl<'t, O, T: ?Sized> Debug for OwningRefMut<'t, O, T>
1117 where O: Debug,
1118 T: Debug,
1119{
1120 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1121 write!(f,
1122 "OwningRefMut {{ owner: _, reference: {:?} }}",
1123 &**self)
1124 }
1125}
1126
1127impl<'t, O, T: ?Sized> Clone for OwningRef<'t, O, T>
1128 where O: CloneStableAddress,
1129{
1130 fn clone(&self) -> Self {
1131 OwningRef {
1132 owner: self.owner.clone(),
1133 reference: self.reference,
1134 marker: PhantomData,
1135 }
1136 }
1137}
1138
1139unsafe impl<'t, O, T: ?Sized> CloneStableAddress for OwningRef<'t, O, T>
1140 where O: CloneStableAddress {}
1141
1142unsafe impl<'t, O, T: ?Sized> Send for OwningRef<'t, O, T>
1143 where O: Send, for<'a> (&'a T): Send {}
1144unsafe impl<'t, O, T: ?Sized> Sync for OwningRef<'t, O, T>
1145 where O: Sync, for<'a> (&'a T): Sync {}
1146
1147unsafe impl<'t, O, T: ?Sized> Send for OwningRefMut<'t, O, T>
1148 where O: Send, for<'a> (&'a mut T): Send {}
1149unsafe impl<'t, O, T: ?Sized> Sync for OwningRefMut<'t, O, T>
1150 where O: Sync, for<'a> (&'a mut T): Sync {}
1151
1152impl Debug for dyn Erased {
1153 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1154 write!(f, "<dyn Erased>",)
1155 }
1156}
1157
1158impl<'t, O, T: ?Sized> PartialEq for OwningRef<'t, O, T> where T: PartialEq {
1159 fn eq(&self, other: &Self) -> bool {
1160 (&*self as &T).eq(&*other as &T)
1161 }
1162}
1163
1164impl<'t, O, T: ?Sized> Eq for OwningRef<'t, O, T> where T: Eq {}
1165
1166impl<'t, O, T: ?Sized> PartialOrd for OwningRef<'t, O, T> where T: PartialOrd {
1167 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1168 (&*self as &T).partial_cmp(&*other as &T)
1169 }
1170}
1171
1172impl<'t, O, T: ?Sized> Ord for OwningRef<'t, O, T> where T: Ord {
1173 fn cmp(&self, other: &Self) -> Ordering {
1174 (&*self as &T).cmp(&*other as &T)
1175 }
1176}
1177
1178impl<'t, O, T: ?Sized> Hash for OwningRef<'t, O, T> where T: Hash {
1179 fn hash<H: Hasher>(&self, state: &mut H) {
1180 (&*self as &T).hash(state);
1181 }
1182}
1183
1184impl<'t, O, T: ?Sized> PartialEq for OwningRefMut<'t, O, T> where T: PartialEq {
1185 fn eq(&self, other: &Self) -> bool {
1186 (&*self as &T).eq(&*other as &T)
1187 }
1188}
1189
1190impl<'t, O, T: ?Sized> Eq for OwningRefMut<'t, O, T> where T: Eq {}
1191
1192impl<'t, O, T: ?Sized> PartialOrd for OwningRefMut<'t, O, T> where T: PartialOrd {
1193 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1194 (&*self as &T).partial_cmp(&*other as &T)
1195 }
1196}
1197
1198impl<'t, O, T: ?Sized> Ord for OwningRefMut<'t, O, T> where T: Ord {
1199 fn cmp(&self, other: &Self) -> Ordering {
1200 (&*self as &T).cmp(&*other as &T)
1201 }
1202}
1203
1204impl<'t, O, T: ?Sized> Hash for OwningRefMut<'t, O, T> where T: Hash {
1205 fn hash<H: Hasher>(&self, state: &mut H) {
1206 (&*self as &T).hash(state);
1207 }
1208}
1209
1210use std::boxed::Box;
1215use std::rc::Rc;
1216use std::sync::Arc;
1217use std::sync::{MutexGuard, RwLockReadGuard, RwLockWriteGuard};
1218use std::cell::{Ref, RefCell, RefMut};
1219
1220impl<T: 'static> ToHandle for RefCell<T> {
1221 type Handle = Ref<'static, T>;
1222 unsafe fn to_handle(x: *const Self) -> Self::Handle { (*x).borrow() }
1223}
1224
1225impl<T: 'static> ToHandleMut for RefCell<T> {
1226 type HandleMut = RefMut<'static, T>;
1227 unsafe fn to_handle_mut(x: *const Self) -> Self::HandleMut { (*x).borrow_mut() }
1228}
1229
1230pub type BoxRef<'u, T, U = T> = OwningRef<'u, Box<T>, U>;
1236pub type VecRef<'u, T, U = T> = OwningRef<'u, Vec<T>, U>;
1238pub type StringRef<'u> = OwningRef<'u, String, str>;
1240
1241pub type RcRef<'u, T, U = T> = OwningRef<'u, Rc<T>, U>;
1243pub type ArcRef<'u, T, U = T> = OwningRef<'u, Arc<T>, U>;
1245
1246pub type RefRef<'a, T, U = T> = OwningRef<'a, Ref<'a, T>, U>;
1248pub type RefMutRef<'a, T, U = T> = OwningRef<'a, RefMut<'a, T>, U>;
1250pub type MutexGuardRef<'a, T, U = T> = OwningRef<'a, MutexGuard<'a, T>, U>;
1252pub type RwLockReadGuardRef<'a, T, U = T> = OwningRef<'a, RwLockReadGuard<'a, T>, U>;
1254pub type RwLockWriteGuardRef<'a, T, U = T> = OwningRef<'a, RwLockWriteGuard<'a, T>, U>;
1256
1257pub type BoxRefMut<'u, T, U = T> = OwningRefMut<'u, Box<T>, U>;
1259pub type VecRefMut<'u, T, U = T> = OwningRefMut<'u, Vec<T>, U>;
1261pub type StringRefMut<'u, > = OwningRefMut<'u, String, str>;
1263
1264pub type RefMutRefMut<'a, T, U = T> = OwningRefMut<'a, RefMut<'a, T>, U>;
1266pub type MutexGuardRefMut<'a, T, U = T> = OwningRefMut<'a, MutexGuard<'a, T>, U>;
1268pub type RwLockWriteGuardRefMut<'a, T, U = T> = OwningRefMut<'a, RwLockWriteGuard<'a, T>, U>;
1270
1271unsafe impl<'a, T: 'a> IntoErased<'a> for Box<T> {
1272 type Erased = Box<dyn Erased + 'a>;
1273 fn into_erased(self) -> Self::Erased {
1274 self
1275 }
1276}
1277unsafe impl<'a, T: 'a> IntoErased<'a> for Rc<T> {
1278 type Erased = Rc<dyn Erased + 'a>;
1279 fn into_erased(self) -> Self::Erased {
1280 self
1281 }
1282}
1283unsafe impl<'a, T: 'a> IntoErased<'a> for Arc<T> {
1284 type Erased = Arc<dyn Erased + 'a>;
1285 fn into_erased(self) -> Self::Erased {
1286 self
1287 }
1288}
1289
1290pub type ErasedBoxRef<'u, U> = OwningRef<'u, Box<dyn Erased>, U>;
1292pub type ErasedRcRef<'u, U> = OwningRef<'u, Rc<dyn Erased>, U>;
1294pub type ErasedArcRef<'u, U> = OwningRef<'u, Arc<dyn Erased>, U>;
1296
1297pub type ErasedBoxRefMut<'u, U> = OwningRefMut<'u, Box<dyn Erased>, U>;
1299
1300#[cfg(test)]
1301mod tests {
1302 mod owning_ref {
1303 use super::super::OwningRef;
1304 use super::super::{RcRef, BoxRef, Erased, ErasedBoxRef};
1305 use std::cmp::{PartialEq, Ord, PartialOrd, Ordering};
1306 use std::hash::{Hash, Hasher};
1307 use std::collections::hash_map::DefaultHasher;
1308 use std::collections::HashMap;
1309 use std::rc::Rc;
1310
1311 #[derive(Debug, PartialEq)]
1312 struct Example(u32, String, [u8; 3]);
1313 fn example() -> Example {
1314 Example(42, "hello world".to_string(), [1, 2, 3])
1315 }
1316
1317 #[test]
1318 fn new_deref() {
1319 let or: OwningRef<'_, Box<()>, ()> = OwningRef::new(Box::new(()));
1320 assert_eq!(&*or, &());
1321 }
1322
1323 #[test]
1324 fn into() {
1325 let or: OwningRef<'_, Box<()>, ()> = Box::new(()).into();
1326 assert_eq!(&*or, &());
1327 }
1328
1329 #[test]
1330 fn map_offset_ref() {
1331 let or: BoxRef<Example> = Box::new(example()).into();
1332 let or: BoxRef<_, u32> = or.map(|x| &x.0);
1333 assert_eq!(&*or, &42);
1334
1335 let or: BoxRef<Example> = Box::new(example()).into();
1336 let or: BoxRef<_, u8> = or.map(|x| &x.2[1]);
1337 assert_eq!(&*or, &2);
1338 }
1339
1340 #[test]
1341 fn map_heap_ref() {
1342 let or: BoxRef<Example> = Box::new(example()).into();
1343 let or: BoxRef<_, str> = or.map(|x| &x.1[..5]);
1344 assert_eq!(&*or, "hello");
1345 }
1346
1347 #[test]
1348 fn map_static_ref() {
1349 let or: BoxRef<()> = Box::new(()).into();
1350 let or: BoxRef<_, str> = or.map(|_| "hello");
1351 assert_eq!(&*or, "hello");
1352 }
1353
1354 #[test]
1355 fn map_chained() {
1356 let or: BoxRef<String> = Box::new(example().1).into();
1357 let or: BoxRef<_, str> = or.map(|x| &x[1..5]);
1358 let or: BoxRef<_, str> = or.map(|x| &x[..2]);
1359 assert_eq!(&*or, "el");
1360 }
1361
1362 #[test]
1363 fn map_chained_inference() {
1364 let or = BoxRef::new(Box::new(example().1))
1365 .map(|x| &x[..5])
1366 .map(|x| &x[1..3]);
1367 assert_eq!(&*or, "el");
1368 }
1369
1370 #[test]
1371 fn as_owner() {
1372 let or: BoxRef<String> = Box::new(example().1).into();
1373 let or = or.map(|x| &x[..5]);
1374 assert_eq!(&*or, "hello");
1375 assert_eq!(&**or.as_owner(), "hello world");
1376 }
1377
1378 #[test]
1379 fn into_owner() {
1380 let or: BoxRef<String> = Box::new(example().1).into();
1381 let or = or.map(|x| &x[..5]);
1382 assert_eq!(&*or, "hello");
1383 let s = *or.into_owner();
1384 assert_eq!(&s, "hello world");
1385 }
1386
1387 #[test]
1388 fn fmt_debug() {
1389 let or: BoxRef<String> = Box::new(example().1).into();
1390 let or = or.map(|x| &x[..5]);
1391 let s = format!("{:?}", or);
1392 assert_eq!(&s, "OwningRef { owner: \"hello world\", reference: \"hello\" }");
1393 }
1394
1395 #[test]
1396 fn erased_owner() {
1397 let o1: BoxRef<Example, str> = BoxRef::new(Box::new(example()))
1398 .map(|x| &x.1[..]);
1399
1400 let o2: BoxRef<String, str> = BoxRef::new(Box::new(example().1))
1401 .map(|x| &x[..]);
1402
1403 let os: Vec<ErasedBoxRef<str>> = vec![o1.erase_owner(), o2.erase_owner()];
1404 assert!(os.iter().all(|e| &e[..] == "hello world"));
1405 }
1406
1407 #[test]
1408 fn non_static_erased_owner() {
1409 let foo = [413, 612];
1410 let bar = &foo;
1411
1412 fn borrow<'a>(a: &'a &[i32; 2]) -> &'a i32 {
1416 &a[0]
1417 }
1418
1419 let o: BoxRef<&[i32; 2]> = Box::new(bar).into();
1420 let o: BoxRef<&[i32; 2], i32> = o.map(borrow);
1421 let o: BoxRef<dyn Erased, i32> = o.erase_owner();
1422
1423 assert_eq!(*o, 413);
1424 }
1425
1426 #[test]
1427 fn raii_locks() {
1428 use super::super::{RefRef, RefMutRef};
1429 use std::cell::RefCell;
1430 use super::super::{MutexGuardRef, RwLockReadGuardRef, RwLockWriteGuardRef};
1431 use std::sync::{Mutex, RwLock};
1432
1433 {
1434 let a = RefCell::new(1);
1435 let a = {
1436 let a = RefRef::new(a.borrow());
1437 assert_eq!(*a, 1);
1438 a
1439 };
1440 assert_eq!(*a, 1);
1441 drop(a);
1442 }
1443 {
1444 let a = RefCell::new(1);
1445 let a = {
1446 let a = RefMutRef::new(a.borrow_mut());
1447 assert_eq!(*a, 1);
1448 a
1449 };
1450 assert_eq!(*a, 1);
1451 drop(a);
1452 }
1453 {
1454 let a = Mutex::new(1);
1455 let a = {
1456 let a = MutexGuardRef::new(a.lock().unwrap());
1457 assert_eq!(*a, 1);
1458 a
1459 };
1460 assert_eq!(*a, 1);
1461 drop(a);
1462 }
1463 {
1464 let a = RwLock::new(1);
1465 let a = {
1466 let a = RwLockReadGuardRef::new(a.read().unwrap());
1467 assert_eq!(*a, 1);
1468 a
1469 };
1470 assert_eq!(*a, 1);
1471 drop(a);
1472 }
1473 {
1474 let a = RwLock::new(1);
1475 let a = {
1476 let a = RwLockWriteGuardRef::new(a.write().unwrap());
1477 assert_eq!(*a, 1);
1478 a
1479 };
1480 assert_eq!(*a, 1);
1481 drop(a);
1482 }
1483 }
1484
1485 #[test]
1486 fn eq() {
1487 let or1: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
1488 let or2: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
1489 assert_eq!(or1.eq(&or2), true);
1490 }
1491
1492 #[test]
1493 fn cmp() {
1494 let or1: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
1495 let or2: BoxRef<[u8]> = BoxRef::new(vec![4, 5, 6].into_boxed_slice());
1496 assert_eq!(or1.cmp(&or2), Ordering::Less);
1497 }
1498
1499 #[test]
1500 fn partial_cmp() {
1501 let or1: BoxRef<[u8]> = BoxRef::new(vec![4, 5, 6].into_boxed_slice());
1502 let or2: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
1503 assert_eq!(or1.partial_cmp(&or2), Some(Ordering::Greater));
1504 }
1505
1506 #[test]
1507 fn hash() {
1508 let mut h1 = DefaultHasher::new();
1509 let mut h2 = DefaultHasher::new();
1510
1511 let or1: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
1512 let or2: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
1513
1514 or1.hash(&mut h1);
1515 or2.hash(&mut h2);
1516
1517 assert_eq!(h1.finish(), h2.finish());
1518 }
1519
1520 #[test]
1521 fn borrow() {
1522 let mut hash = HashMap::new();
1523 let key = RcRef::<String>::new(Rc::new("foo-bar".to_string())).map(|s| &s[..]);
1524
1525 hash.insert(key.clone().map(|s| &s[..3]), 42);
1526 hash.insert(key.clone().map(|s| &s[4..]), 23);
1527
1528 assert_eq!(hash.get("foo"), Some(&42));
1529 assert_eq!(hash.get("bar"), Some(&23));
1530 }
1531
1532 #[test]
1533 fn total_erase() {
1534 let a: OwningRef<'_, Vec<u8>, [u8]>
1535 = OwningRef::new(vec![]).map(|x| &x[..]);
1536 let b: OwningRef<'_, Box<[u8]>, [u8]>
1537 = OwningRef::new(vec![].into_boxed_slice()).map(|x| &x[..]);
1538
1539 let c: OwningRef<'_, Rc<Vec<u8>>, [u8]> = unsafe {a.map_owner(Rc::new)};
1540 let d: OwningRef<'_, Rc<Box<[u8]>>, [u8]> = unsafe {b.map_owner(Rc::new)};
1541
1542 let e: OwningRef<'_, Rc<dyn Erased>, [u8]> = c.erase_owner();
1543 let f: OwningRef<'_, Rc<dyn Erased>, [u8]> = d.erase_owner();
1544
1545 let _g = e.clone();
1546 let _h = f.clone();
1547 }
1548
1549 #[test]
1550 fn total_erase_box() {
1551 let a: OwningRef<'_, Vec<u8>, [u8]>
1552 = OwningRef::new(vec![]).map(|x| &x[..]);
1553 let b: OwningRef<'_, Box<[u8]>, [u8]>
1554 = OwningRef::new(vec![].into_boxed_slice()).map(|x| &x[..]);
1555
1556 let c: OwningRef<'_, Box<Vec<u8>>, [u8]> = a.map_owner_box();
1557 let d: OwningRef<'_, Box<Box<[u8]>>, [u8]> = b.map_owner_box();
1558
1559 let _e: OwningRef<'_, Box<dyn Erased>, [u8]> = c.erase_owner();
1560 let _f: OwningRef<'_, Box<dyn Erased>, [u8]> = d.erase_owner();
1561 }
1562
1563 #[test]
1564 fn try_map1() {
1565 use std::any::Any;
1566
1567 let x = Box::new(123_i32);
1568 let y: Box<dyn Any> = x;
1569
1570 OwningRef::new(y).try_map(|x| x.downcast_ref::<i32>().ok_or(())).unwrap();
1571 }
1572
1573 #[test]
1574 fn try_map2() {
1575 use std::any::Any;
1576
1577 let x = Box::new(123_u32);
1578 let y: Box<dyn Any> = x;
1579
1580 OwningRef::new(y).try_map(|x| x.downcast_ref::<i32>().ok_or(())).unwrap_err();
1581 }
1582
1583 #[test]
1584 fn map_with_owner() {
1585 let owning_ref: BoxRef<Example> = Box::new(example()).into();
1586 let owning_ref = owning_ref.map(|owner| &owner.1);
1587
1588 owning_ref.map_with_owner(|owner, ref_field| {
1589 assert_eq!(owner.1, *ref_field);
1590 ref_field
1591 });
1592 }
1593
1594 #[test]
1595 fn try_map_with_owner_ok() {
1596 let owning_ref: BoxRef<Example> = Box::new(example()).into();
1597 let owning_ref = owning_ref.map(|owner| &owner.1);
1598
1599 owning_ref.try_map_with_owner(|owner, ref_field| {
1600 assert_eq!(owner.1, *ref_field);
1601 Ok(ref_field) as Result<_, ()>
1602 }).unwrap();
1603 }
1604
1605 #[test]
1606 fn try_map_with_owner_err() {
1607 let owning_ref: BoxRef<Example> = Box::new(example()).into();
1608 let owning_ref = owning_ref.map(|owner| &owner.1);
1609
1610 owning_ref.try_map_with_owner(|owner, ref_field| {
1611 assert_eq!(owner.1, *ref_field);
1612 Err(()) as Result<&(), _>
1613 }).unwrap_err();
1614 }
1615 }
1616
1617 mod owning_handle {
1618 use super::super::OwningHandle;
1619 use super::super::RcRef;
1620 use std::rc::Rc;
1621 use std::cell::RefCell;
1622 use std::sync::Arc;
1623 use std::sync::RwLock;
1624
1625 #[test]
1626 fn owning_handle() {
1627 use std::cell::RefCell;
1628 let cell = Rc::new(RefCell::new(2));
1629 let cell_ref = RcRef::new(cell);
1630 let mut handle = OwningHandle::new_with_fn(cell_ref, |x| unsafe { x.as_ref() }.unwrap().borrow_mut());
1631 assert_eq!(*handle, 2);
1632 *handle = 3;
1633 assert_eq!(*handle, 3);
1634 }
1635
1636 #[test]
1637 fn try_owning_handle_ok() {
1638 use std::cell::RefCell;
1639 let cell = Rc::new(RefCell::new(2));
1640 let cell_ref = RcRef::new(cell);
1641 let mut handle = OwningHandle::try_new::<_, ()>(cell_ref, |x| {
1642 Ok(unsafe {
1643 x.as_ref()
1644 }.unwrap().borrow_mut())
1645 }).unwrap();
1646 assert_eq!(*handle, 2);
1647 *handle = 3;
1648 assert_eq!(*handle, 3);
1649 }
1650
1651 #[test]
1652 fn try_owning_handle_err() {
1653 use std::cell::RefCell;
1654 let cell = Rc::new(RefCell::new(2));
1655 let cell_ref = RcRef::new(cell);
1656 let handle = OwningHandle::try_new::<_, ()>(cell_ref, |x| {
1657 if false {
1658 return Ok(unsafe {
1659 x.as_ref()
1660 }.unwrap().borrow_mut())
1661 }
1662 Err(())
1663 });
1664 assert!(handle.is_err());
1665 }
1666
1667 #[test]
1668 fn nested() {
1669 use std::cell::RefCell;
1670 use std::sync::{Arc, RwLock};
1671
1672 let result = {
1673 let complex = Rc::new(RefCell::new(Arc::new(RwLock::new("someString"))));
1674 let curr = RcRef::new(complex);
1675 let curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().borrow_mut());
1676 let mut curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().try_write().unwrap());
1677 assert_eq!(*curr, "someString");
1678 *curr = "someOtherString";
1679 curr
1680 };
1681 assert_eq!(*result, "someOtherString");
1682 }
1683
1684 #[test]
1685 fn owning_handle_safe() {
1686 use std::cell::RefCell;
1687 let cell = Rc::new(RefCell::new(2));
1688 let cell_ref = RcRef::new(cell);
1689 let handle = OwningHandle::new(cell_ref);
1690 assert_eq!(*handle, 2);
1691 }
1692
1693 #[test]
1694 fn owning_handle_mut_safe() {
1695 use std::cell::RefCell;
1696 let cell = Rc::new(RefCell::new(2));
1697 let cell_ref = RcRef::new(cell);
1698 let mut handle = OwningHandle::new_mut(cell_ref);
1699 assert_eq!(*handle, 2);
1700 *handle = 3;
1701 assert_eq!(*handle, 3);
1702 }
1703
1704 #[test]
1705 fn owning_handle_safe_2() {
1706 let result = {
1707 let complex = Rc::new(RefCell::new(Arc::new(RwLock::new("someString"))));
1708 let curr = RcRef::new(complex);
1709 let curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().borrow_mut());
1710 let mut curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().try_write().unwrap());
1711 assert_eq!(*curr, "someString");
1712 *curr = "someOtherString";
1713 curr
1714 };
1715 assert_eq!(*result, "someOtherString");
1716 }
1717 }
1718
1719 mod owning_ref_mut {
1720 use super::super::{OwningRefMut, BoxRefMut, Erased, ErasedBoxRefMut};
1721 use super::super::BoxRef;
1722 use std::cmp::{PartialEq, Ord, PartialOrd, Ordering};
1723 use std::hash::{Hash, Hasher};
1724 use std::collections::hash_map::DefaultHasher;
1725 use std::collections::HashMap;
1726
1727 #[derive(Debug, PartialEq)]
1728 struct Example(u32, String, [u8; 3]);
1729 fn example() -> Example {
1730 Example(42, "hello world".to_string(), [1, 2, 3])
1731 }
1732
1733 #[test]
1734 fn new_deref() {
1735 let or: OwningRefMut<'_, Box<()>, ()> = OwningRefMut::new(Box::new(()));
1736 assert_eq!(&*or, &());
1737 }
1738
1739 #[test]
1740 fn new_deref_mut() {
1741 let mut or: OwningRefMut<'_, Box<()>, ()> = OwningRefMut::new(Box::new(()));
1742 assert_eq!(&mut *or, &mut ());
1743 }
1744
1745 #[test]
1746 fn mutate() {
1747 let mut or: OwningRefMut<'_, Box<usize>, usize> = OwningRefMut::new(Box::new(0));
1748 assert_eq!(&*or, &0);
1749 *or = 1;
1750 assert_eq!(&*or, &1);
1751 }
1752
1753 #[test]
1754 fn into() {
1755 let or: OwningRefMut<'_, Box<()>, ()> = Box::new(()).into();
1756 assert_eq!(&*or, &());
1757 }
1758
1759 #[test]
1760 fn map_offset_ref() {
1761 let or: BoxRefMut<Example> = Box::new(example()).into();
1762 let or: BoxRefMut<_, u32> = or.map_mut(|x| &mut x.0);
1763 assert_eq!(&*or, &42);
1764
1765 let or: BoxRefMut<Example> = Box::new(example()).into();
1766 let or: BoxRefMut<_, u8> = or.map_mut(|x| &mut x.2[1]);
1767 assert_eq!(&*or, &2);
1768 }
1769
1770 #[test]
1771 fn map_heap_ref() {
1772 let or: BoxRefMut<Example> = Box::new(example()).into();
1773 let or: BoxRefMut<_, str> = or.map_mut(|x| &mut x.1[..5]);
1774 assert_eq!(&*or, "hello");
1775 }
1776
1777 #[test]
1778 fn map_static_ref() {
1779 let or: BoxRefMut<()> = Box::new(()).into();
1780 let or: BoxRef<_, str> = unsafe { or.map(|_| "hello") };
1781 assert_eq!(&*or, "hello");
1782 }
1783
1784 #[test]
1785 fn map_mut_offset_ref() {
1786 let or: BoxRefMut<Example> = Box::new(example()).into();
1787 let or: BoxRefMut<_, u32> = or.map_mut(|x| &mut x.0);
1788 assert_eq!(&*or, &42);
1789
1790 let or: BoxRefMut<Example> = Box::new(example()).into();
1791 let or: BoxRefMut<_, u8> = or.map_mut(|x| &mut x.2[1]);
1792 assert_eq!(&*or, &2);
1793 }
1794
1795 #[test]
1796 fn map_mut_heap_ref() {
1797 let or: BoxRefMut<Example> = Box::new(example()).into();
1798 let or: BoxRefMut<_, str> = or.map_mut(|x| &mut x.1[..5]);
1799 assert_eq!(&*or, "hello");
1800 }
1801
1802 #[test]
1803 fn map_mut_static_ref() {
1804 static mut MUT_S: [u8; 5] = *b"hello";
1805
1806 let mut_s: &'static mut [u8] = unsafe { &mut MUT_S };
1807
1808 let or: BoxRefMut<()> = Box::new(()).into();
1809 let or: BoxRefMut<_, [u8]> = or.map_mut(move |_| mut_s);
1810 assert_eq!(&*or, b"hello");
1811 }
1812
1813 #[test]
1814 fn map_mut_chained() {
1815 let or: BoxRefMut<String> = Box::new(example().1).into();
1816 let or: BoxRefMut<_, str> = or.map_mut(|x| &mut x[1..5]);
1817 let or: BoxRefMut<_, str> = or.map_mut(|x| &mut x[..2]);
1818 assert_eq!(&*or, "el");
1819 }
1820
1821 #[test]
1822 fn map_chained_inference() {
1823 let or = BoxRefMut::new(Box::new(example().1))
1824 .map_mut(|x| &mut x[..5])
1825 .map_mut(|x| &mut x[1..3]);
1826 assert_eq!(&*or, "el");
1827 }
1828
1829 #[test]
1830 fn try_map_mut() {
1831 let or: BoxRefMut<String> = Box::new(example().1).into();
1832 let or: Result<BoxRefMut<_, str>, ()> = or.try_map_mut(|x| Ok(&mut x[1..5]));
1833 assert_eq!(&*or.unwrap(), "ello");
1834
1835 let or: BoxRefMut<String> = Box::new(example().1).into();
1836 let or: Result<BoxRefMut<_, str>, ()> = or.try_map_mut(|_| Err(()));
1837 assert!(or.is_err());
1838 }
1839
1840 #[test]
1841 fn as_owner() {
1842 let or: BoxRefMut<String> = Box::new(example().1).into();
1843 let or = or.map_mut(|x| &mut x[..5]);
1844 assert_eq!(&*or, "hello");
1845 assert_eq!(&** unsafe { or.as_owner() }, "hello world");
1846 }
1847
1848 #[test]
1849 fn into_owner() {
1850 let or: BoxRefMut<String> = Box::new(example().1).into();
1851 let or = or.map_mut(|x| &mut x[..5]);
1852 assert_eq!(&*or, "hello");
1853 let s = *or.into_owner();
1854 assert_eq!(&s, "hello world");
1855 }
1856
1857 #[test]
1858 fn fmt_debug() {
1859 let or: BoxRefMut<String> = Box::new(example().1).into();
1860 let or = or.map_mut(|x| &mut x[..5]);
1861 let s = format!("{:?}", or);
1862 assert_eq!(&s,
1863 "OwningRefMut { owner: _, reference: \"hello\" }");
1864 }
1865
1866 #[test]
1867 fn erased_owner() {
1868 let o1: BoxRefMut<Example, str> = BoxRefMut::new(Box::new(example()))
1869 .map_mut(|x| &mut x.1[..]);
1870
1871 let o2: BoxRefMut<String, str> = BoxRefMut::new(Box::new(example().1))
1872 .map_mut(|x| &mut x[..]);
1873
1874 let os: Vec<ErasedBoxRefMut<str>> = vec![o1.erase_owner(), o2.erase_owner()];
1875 assert!(os.iter().all(|e| &e[..] == "hello world"));
1876 }
1877
1878 #[test]
1879 fn non_static_erased_owner() {
1880 let mut foo = [413, 612];
1881 let bar = &mut foo;
1882
1883 fn borrow<'a>(a: &'a mut &mut [i32; 2]) -> &'a mut i32 {
1887 &mut a[0]
1888 }
1889
1890 let o: BoxRefMut<&mut [i32; 2]> = Box::new(bar).into();
1891 let o: BoxRefMut<&mut [i32; 2], i32> = o.map_mut(borrow);
1892 let o: BoxRefMut<dyn Erased, i32> = o.erase_owner();
1893
1894 assert_eq!(*o, 413);
1895 }
1896
1897 #[test]
1898 fn raii_locks() {
1899 use super::super::RefMutRefMut;
1900 use std::cell::RefCell;
1901 use super::super::{MutexGuardRefMut, RwLockWriteGuardRefMut};
1902 use std::sync::{Mutex, RwLock};
1903
1904 {
1905 let a = RefCell::new(1);
1906 let a = {
1907 let a = RefMutRefMut::new(a.borrow_mut());
1908 assert_eq!(*a, 1);
1909 a
1910 };
1911 assert_eq!(*a, 1);
1912 drop(a);
1913 }
1914 {
1915 let a = Mutex::new(1);
1916 let a = {
1917 let a = MutexGuardRefMut::new(a.lock().unwrap());
1918 assert_eq!(*a, 1);
1919 a
1920 };
1921 assert_eq!(*a, 1);
1922 drop(a);
1923 }
1924 {
1925 let a = RwLock::new(1);
1926 let a = {
1927 let a = RwLockWriteGuardRefMut::new(a.write().unwrap());
1928 assert_eq!(*a, 1);
1929 a
1930 };
1931 assert_eq!(*a, 1);
1932 drop(a);
1933 }
1934 }
1935
1936 #[test]
1937 fn eq() {
1938 let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
1939 let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
1940 assert_eq!(or1.eq(&or2), true);
1941 }
1942
1943 #[test]
1944 fn cmp() {
1945 let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
1946 let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![4, 5, 6].into_boxed_slice());
1947 assert_eq!(or1.cmp(&or2), Ordering::Less);
1948 }
1949
1950 #[test]
1951 fn partial_cmp() {
1952 let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![4, 5, 6].into_boxed_slice());
1953 let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
1954 assert_eq!(or1.partial_cmp(&or2), Some(Ordering::Greater));
1955 }
1956
1957 #[test]
1958 fn hash() {
1959 let mut h1 = DefaultHasher::new();
1960 let mut h2 = DefaultHasher::new();
1961
1962 let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
1963 let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
1964
1965 or1.hash(&mut h1);
1966 or2.hash(&mut h2);
1967
1968 assert_eq!(h1.finish(), h2.finish());
1969 }
1970
1971 #[test]
1972 fn borrow() {
1973 let mut hash = HashMap::new();
1974 let key1 = BoxRefMut::<String>::new(Box::new("foo".to_string())).map_mut(|s| &mut s[..]);
1975 let key2 = BoxRefMut::<String>::new(Box::new("bar".to_string())).map_mut(|s| &mut s[..]);
1976
1977 hash.insert(key1, 42);
1978 hash.insert(key2, 23);
1979
1980 assert_eq!(hash.get("foo"), Some(&42));
1981 assert_eq!(hash.get("bar"), Some(&23));
1982 }
1983
1984 #[test]
1985 fn total_erase() {
1986 let a: OwningRefMut<'_, Vec<u8>, [u8]>
1987 = OwningRefMut::new(vec![]).map_mut(|x| &mut x[..]);
1988 let b: OwningRefMut<'_, Box<[u8]>, [u8]>
1989 = OwningRefMut::new(vec![].into_boxed_slice()).map_mut(|x| &mut x[..]);
1990
1991 let c: OwningRefMut<'_, Box<Vec<u8>>, [u8]> = unsafe {a.map_owner(Box::new)};
1992 let d: OwningRefMut<'_, Box<Box<[u8]>>, [u8]> = unsafe {b.map_owner(Box::new)};
1993
1994 let _e: OwningRefMut<'_, Box<dyn Erased>, [u8]> = c.erase_owner();
1995 let _f: OwningRefMut<'_, Box<dyn Erased>, [u8]> = d.erase_owner();
1996 }
1997
1998 #[test]
1999 fn total_erase_box() {
2000 let a: OwningRefMut<'_, Vec<u8>, [u8]>
2001 = OwningRefMut::new(vec![]).map_mut(|x| &mut x[..]);
2002 let b: OwningRefMut<'_, Box<[u8]>, [u8]>
2003 = OwningRefMut::new(vec![].into_boxed_slice()).map_mut(|x| &mut x[..]);
2004
2005 let c: OwningRefMut<'_, Box<Vec<u8>>, [u8]> = a.map_owner_box();
2006 let d: OwningRefMut<'_, Box<Box<[u8]>>, [u8]> = b.map_owner_box();
2007
2008 let _e: OwningRefMut<'_, Box<dyn Erased>, [u8]> = c.erase_owner();
2009 let _f: OwningRefMut<'_, Box<dyn Erased>, [u8]> = d.erase_owner();
2010 }
2011
2012 #[test]
2013 fn try_map1() {
2014 use std::any::Any;
2015
2016 let x = Box::new(123_i32);
2017 let y: Box<dyn Any> = x;
2018
2019 OwningRefMut::new(y).try_map_mut(|x| x.downcast_mut::<i32>().ok_or(())).unwrap();
2020 }
2021
2022 #[test]
2023 fn try_map2() {
2024 use std::any::Any;
2025
2026 let x = Box::new(123_u32);
2027 let y: Box<dyn Any> = x;
2028
2029 OwningRefMut::new(y).try_map_mut(|x| x.downcast_mut::<i32>().ok_or(())).unwrap_err();
2030 }
2031
2032 #[test]
2033 fn try_map3() {
2034 use std::any::Any;
2035
2036 let x = Box::new(123_i32);
2037 let y: Box<dyn Any> = x;
2038
2039 OwningRefMut::new(y).try_map_mut(|x| x.downcast_mut::<i32>().ok_or(())).unwrap();
2040 }
2041
2042 #[test]
2043 fn try_map4() {
2044 use std::any::Any;
2045
2046 let x = Box::new(123_u32);
2047 let y: Box<dyn Any> = x;
2048
2049 OwningRefMut::new(y).try_map_mut(|x| x.downcast_mut::<i32>().ok_or(())).unwrap_err();
2050 }
2051
2052 #[test]
2053 fn into_owning_ref() {
2054 use super::super::BoxRef;
2055
2056 let or: BoxRefMut<()> = Box::new(()).into();
2057 let or: BoxRef<()> = unsafe { or.map(|x| x) };
2058 assert_eq!(&*or, &());
2059 }
2060
2061 struct Foo {
2062 u: u32,
2063 }
2064 struct Bar {
2065 f: Foo,
2066 }
2067
2068 #[test]
2069 fn ref_mut() {
2070 use std::cell::RefCell;
2071
2072 let a = RefCell::new(Bar { f: Foo { u: 42 } });
2073 let mut b = OwningRefMut::new(a.borrow_mut());
2074 assert_eq!(b.f.u, 42);
2075 b.f.u = 43;
2076 let mut c = b.map_mut(|x| &mut x.f);
2077 assert_eq!(c.u, 43);
2078 c.u = 44;
2079 let mut d = c.map_mut(|x| &mut x.u);
2080 assert_eq!(*d, 44);
2081 *d = 45;
2082 assert_eq!(*d, 45);
2083 }
2084 }
2085
2086 #[test]
2088 fn noalias_test() {
2089 use super::OwningRef;
2090 use std::cell::Cell;
2091
2092 fn helper(owning_ref: OwningRef<Box<Cell<u8>>, Cell<u8>>) -> u8 {
2093 owning_ref.set(20);
2094 owning_ref.as_owner().get() }
2096
2097 let val: Box<Cell<u8>> = Box::new(Cell::new(25));
2098 let owning_ref = OwningRef::new(val);
2099 let res = helper(owning_ref);
2100 assert_eq!(res, 20);
2101 }
2102}