1#![warn(missing_docs)]
2
3extern crate stable_deref_trait;
247pub use stable_deref_trait::{StableDeref as StableAddress, CloneStableDeref as CloneStableAddress};
248
249pub struct OwningRef<O, T: ?Sized> {
259 owner: O,
260 reference: *const T,
261}
262
263pub struct OwningRefMut<O, T: ?Sized> {
273 owner: O,
274 reference: *mut T,
275}
276
277pub trait Erased {}
281impl<T> Erased for T {}
282
283pub unsafe trait IntoErased<'a> {
287 type Erased;
289 fn into_erased(self) -> Self::Erased;
291}
292
293impl<O, T: ?Sized> OwningRef<O, T> {
298 pub fn new(o: O) -> Self
312 where O: StableAddress,
313 O: Deref<Target = T>,
314 {
315 OwningRef {
316 reference: &*o,
317 owner: o,
318 }
319 }
320
321 pub unsafe fn new_assert_stable_address(o: O) -> Self
327 where O: Deref<Target = T>,
328 {
329 OwningRef {
330 reference: &*o,
331 owner: o,
332 }
333 }
334
335 pub fn map<F, U: ?Sized>(self, f: F) -> OwningRef<O, U>
356 where O: StableAddress,
357 F: FnOnce(&T) -> &U
358 {
359 OwningRef {
360 reference: f(&self),
361 owner: self.owner,
362 }
363 }
364
365 pub fn map_with_owner<F, U: ?Sized>(self, f: F) -> OwningRef<O, U>
388 where O: StableAddress,
389 F: for<'a> FnOnce(&'a O, &'a T) -> &'a U
390 {
391 OwningRef {
392 reference: f(&self.owner, &self),
393 owner: self.owner,
394 }
395 }
396
397 pub fn try_map<F, U: ?Sized, E>(self, f: F) -> Result<OwningRef<O, U>, E>
420 where O: StableAddress,
421 F: FnOnce(&T) -> Result<&U, E>
422 {
423 Ok(OwningRef {
424 reference: f(&self)?,
425 owner: self.owner,
426 })
427 }
428
429 pub fn try_map_with_owner<F, U: ?Sized, E>(self, f: F) -> Result<OwningRef<O, U>, E>
453 where O: StableAddress,
454 F: for<'a> FnOnce(&'a O, &'a T) -> Result<&'a U, E>
455 {
456 Ok(OwningRef {
457 reference: f(&self.owner, &self)?,
458 owner: self.owner,
459 })
460 }
461
462 pub unsafe fn map_owner<F, P>(self, f: F) -> OwningRef<P, T>
468 where O: StableAddress,
469 P: StableAddress,
470 F: FnOnce(O) -> P
471 {
472 OwningRef {
473 reference: self.reference,
474 owner: f(self.owner),
475 }
476 }
477
478 pub fn map_owner_box(self) -> OwningRef<Box<O>, T> {
484 OwningRef {
485 reference: self.reference,
486 owner: Box::new(self.owner),
487 }
488 }
489
490 pub fn erase_owner<'a>(self) -> OwningRef<O::Erased, T>
523 where O: IntoErased<'a>,
524 {
525 OwningRef {
526 reference: self.reference,
527 owner: self.owner.into_erased(),
528 }
529 }
530
531 pub fn as_owner(&self) -> &O {
535 &self.owner
536 }
537
538 pub fn into_owner(self) -> O {
540 self.owner
541 }
542}
543
544impl<O, T: ?Sized> OwningRefMut<O, T> {
545 pub fn new(mut o: O) -> Self
559 where O: StableAddress,
560 O: DerefMut<Target = T>,
561 {
562 OwningRefMut {
563 reference: &mut *o,
564 owner: o,
565 }
566 }
567
568 pub unsafe fn new_assert_stable_address(mut o: O) -> Self
574 where O: DerefMut<Target = T>,
575 {
576 OwningRefMut {
577 reference: &mut *o,
578 owner: o,
579 }
580 }
581
582 pub fn map<F, U: ?Sized>(mut self, f: F) -> OwningRef<O, U>
603 where O: StableAddress,
604 F: FnOnce(&mut T) -> &U
605 {
606 OwningRef {
607 reference: f(&mut self),
608 owner: self.owner,
609 }
610 }
611
612 pub fn map_mut<F, U: ?Sized>(mut self, f: F) -> OwningRefMut<O, U>
633 where O: StableAddress,
634 F: FnOnce(&mut T) -> &mut U
635 {
636 OwningRefMut {
637 reference: f(&mut self),
638 owner: self.owner,
639 }
640 }
641
642 pub fn try_map<F, U: ?Sized, E>(mut self, f: F) -> Result<OwningRef<O, U>, E>
665 where O: StableAddress,
666 F: FnOnce(&mut T) -> Result<&U, E>
667 {
668 Ok(OwningRef {
669 reference: f(&mut self)?,
670 owner: self.owner,
671 })
672 }
673
674 pub fn try_map_mut<F, U: ?Sized, E>(mut self, f: F) -> Result<OwningRefMut<O, U>, E>
697 where O: StableAddress,
698 F: FnOnce(&mut T) -> Result<&mut U, E>
699 {
700 Ok(OwningRefMut {
701 reference: f(&mut self)?,
702 owner: self.owner,
703 })
704 }
705
706 pub unsafe fn map_owner<F, P>(self, f: F) -> OwningRefMut<P, T>
712 where O: StableAddress,
713 P: StableAddress,
714 F: FnOnce(O) -> P
715 {
716 OwningRefMut {
717 reference: self.reference,
718 owner: f(self.owner),
719 }
720 }
721
722 pub fn map_owner_box(self) -> OwningRefMut<Box<O>, T> {
728 OwningRefMut {
729 reference: self.reference,
730 owner: Box::new(self.owner),
731 }
732 }
733
734 pub fn erase_owner<'a>(self) -> OwningRefMut<O::Erased, T>
767 where O: IntoErased<'a>,
768 {
769 OwningRefMut {
770 reference: self.reference,
771 owner: self.owner.into_erased(),
772 }
773 }
774
775 pub fn as_owner(&self) -> &O {
779 &self.owner
780 }
781
782 pub fn as_owner_mut(&mut self) -> &mut O {
784 &mut self.owner
785 }
786
787 pub fn into_owner(self) -> O {
789 self.owner
790 }
791}
792
793use std::ops::{Deref, DerefMut};
798use std::future::Future;
799
800pub struct OwningHandle<O, H>
820 where O: StableAddress, H: Deref,
821{
822 handle: H,
823 _owner: O,
824}
825
826impl<O, H> Deref for OwningHandle<O, H>
827 where O: StableAddress, H: Deref,
828{
829 type Target = H::Target;
830 fn deref(&self) -> &H::Target {
831 self.handle.deref()
832 }
833}
834
835unsafe impl<O, H> StableAddress for OwningHandle<O, H>
836 where O: StableAddress, H: StableAddress,
837{}
838
839impl<O, H> DerefMut for OwningHandle<O, H>
840 where O: StableAddress, H: DerefMut,
841{
842 fn deref_mut(&mut self) -> &mut H::Target {
843 self.handle.deref_mut()
844 }
845}
846
847pub trait ToHandle {
849 type Handle: Deref;
851
852 unsafe fn to_handle(x: *const Self) -> Self::Handle;
855}
856
857pub trait ToHandleMut {
859 type HandleMut: DerefMut;
861
862 unsafe fn to_handle_mut(x: *const Self) -> Self::HandleMut;
865}
866
867impl<O, H> OwningHandle<O, H>
868 where O: StableAddress, O::Target: ToHandle<Handle = H>, H: Deref,
869{
870 pub fn new(o: O) -> Self {
874 OwningHandle::new_with_fn(o, |x| unsafe { O::Target::to_handle(x) })
875 }
876}
877
878impl<O, H> OwningHandle<O, H>
879 where O: StableAddress, O::Target: ToHandleMut<HandleMut = H>, H: DerefMut,
880{
881 pub fn new_mut(o: O) -> Self {
883 OwningHandle::new_with_fn(o, |x| unsafe { O::Target::to_handle_mut(x) })
884 }
885}
886
887impl<O, H> OwningHandle<O, H>
888 where O: StableAddress, H: Deref,
889{
890 pub fn new_with_fn<F>(o: O, f: F) -> Self
895 where F: FnOnce(*const O::Target) -> H
896 {
897 let h: H;
898 {
899 h = f(o.deref() as *const O::Target);
900 }
901
902 OwningHandle {
903 handle: h,
904 _owner: o,
905 }
906 }
907
908 pub async fn new_with_async_fn<F, T>(o: O, f: F) -> Self
913 where
914 F: FnOnce(*const O::Target) -> T,
915 T: Future<Output = H>,
916 {
917 let h: H;
918 {
919 let r = f(o.deref() as *const O::Target);
920 h = r.await;
921 }
922
923 OwningHandle {
924 handle: h,
925 _owner: o,
926 }
927 }
928
929 pub fn try_new<F, E>(o: O, f: F) -> Result<Self, E>
934 where F: FnOnce(*const O::Target) -> Result<H, E>
935 {
936 let h: H;
937 {
938 h = f(o.deref() as *const O::Target)?;
939 }
940
941 Ok(OwningHandle {
942 handle: h,
943 _owner: o,
944 })
945 }
946
947 pub async fn try_new_async<F, E, T>(o: O, f: F) -> Result<Self, E>
952 where
953 F: FnOnce(*const O::Target) -> T,
954 T: Future<Output = Result<H, E>>,
955 {
956 let h: H;
957 {
958 let r = f(o.deref() as *const O::Target);
959 h = r.await?;
960 }
961
962 Ok(OwningHandle {
963 handle: h,
964 _owner: o,
965 })
966 }
967
968 pub fn map<F, N: Deref>(self, f: F) -> OwningHandle<O, N>
973 where F: FnOnce(H) -> N
974 {
975 OwningHandle {
976 handle: f(self.handle),
977 _owner: self._owner,
978 }
979 }
980
981 pub fn as_owner(&self) -> &O {
983 &self._owner
984 }
985
986 pub fn into_owner(self) -> O {
988 self._owner
989 }
990}
991
992use std::convert::From;
997use std::fmt::{self, Debug};
998use std::marker::{Send, Sync};
999use std::cmp::{Eq, PartialEq, Ord, PartialOrd, Ordering};
1000use std::hash::{Hash, Hasher};
1001use std::borrow::Borrow;
1002
1003impl<O, T: ?Sized> Deref for OwningRef<O, T> {
1004 type Target = T;
1005
1006 fn deref(&self) -> &T {
1007 unsafe {
1008 &*self.reference
1009 }
1010 }
1011}
1012
1013impl<O, T: ?Sized> Deref for OwningRefMut<O, T> {
1014 type Target = T;
1015
1016 fn deref(&self) -> &T {
1017 unsafe {
1018 &*self.reference
1019 }
1020 }
1021}
1022
1023impl<O, T: ?Sized> DerefMut for OwningRefMut<O, T> {
1024 fn deref_mut(&mut self) -> &mut T {
1025 unsafe {
1026 &mut *self.reference
1027 }
1028 }
1029}
1030
1031unsafe impl<O, T: ?Sized> StableAddress for OwningRef<O, T> {}
1032
1033unsafe impl<O, T: ?Sized> StableAddress for OwningRefMut<O, T> {}
1034
1035impl<O, T: ?Sized> AsRef<T> for OwningRef<O, T> {
1036 fn as_ref(&self) -> &T {
1037 &*self
1038 }
1039}
1040
1041impl<O, T: ?Sized> AsRef<T> for OwningRefMut<O, T> {
1042 fn as_ref(&self) -> &T {
1043 &*self
1044 }
1045}
1046
1047impl<O, T: ?Sized> AsMut<T> for OwningRefMut<O, T> {
1048 fn as_mut(&mut self) -> &mut T {
1049 &mut *self
1050 }
1051}
1052
1053impl<O, T: ?Sized> Borrow<T> for OwningRef<O, T> {
1054 fn borrow(&self) -> &T {
1055 &*self
1056 }
1057}
1058
1059impl<O, T: ?Sized> From<O> for OwningRef<O, T>
1060 where O: StableAddress,
1061 O: Deref<Target = T>,
1062{
1063 fn from(owner: O) -> Self {
1064 OwningRef::new(owner)
1065 }
1066}
1067
1068impl<O, T: ?Sized> From<O> for OwningRefMut<O, T>
1069 where O: StableAddress,
1070 O: DerefMut<Target = T>
1071{
1072 fn from(owner: O) -> Self {
1073 OwningRefMut::new(owner)
1074 }
1075}
1076
1077impl<O, T: ?Sized> From<OwningRefMut<O, T>> for OwningRef<O, T>
1078 where O: StableAddress,
1079 O: DerefMut<Target = T>
1080{
1081 fn from(other: OwningRefMut<O, T>) -> Self {
1082 OwningRef {
1083 owner: other.owner,
1084 reference: other.reference,
1085 }
1086 }
1087}
1088
1089impl<O, T: ?Sized> Debug for OwningRef<O, T>
1092 where O: Debug,
1093 T: Debug,
1094{
1095 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1096 write!(f,
1097 "OwningRef {{ owner: {:?}, reference: {:?} }}",
1098 self.as_owner(),
1099 &**self)
1100 }
1101}
1102
1103impl<O, T: ?Sized> Debug for OwningRefMut<O, T>
1104 where O: Debug,
1105 T: Debug,
1106{
1107 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1108 write!(f,
1109 "OwningRefMut {{ owner: {:?}, reference: {:?} }}",
1110 self.as_owner(),
1111 &**self)
1112 }
1113}
1114
1115impl<O, T: ?Sized> Clone for OwningRef<O, T>
1116 where O: CloneStableAddress,
1117{
1118 fn clone(&self) -> Self {
1119 OwningRef {
1120 owner: self.owner.clone(),
1121 reference: self.reference,
1122 }
1123 }
1124}
1125
1126unsafe impl<O, T: ?Sized> CloneStableAddress for OwningRef<O, T>
1127 where O: CloneStableAddress {}
1128
1129unsafe impl<O, T: ?Sized> Send for OwningRef<O, T>
1130 where O: Send, for<'a> (&'a T): Send {}
1131unsafe impl<O, T: ?Sized> Sync for OwningRef<O, T>
1132 where O: Sync, for<'a> (&'a T): Sync {}
1133
1134unsafe impl<O, T: ?Sized> Send for OwningRefMut<O, T>
1135 where O: Send, for<'a> (&'a mut T): Send {}
1136unsafe impl<O, T: ?Sized> Sync for OwningRefMut<O, T>
1137 where O: Sync, for<'a> (&'a mut T): Sync {}
1138
1139impl Debug for dyn Erased {
1140 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
1141 write!(f, "<dyn Erased>",)
1142 }
1143}
1144
1145impl<O, T: ?Sized> PartialEq for OwningRef<O, T> where T: PartialEq {
1146 fn eq(&self, other: &Self) -> bool {
1147 (&*self as &T).eq(&*other as &T)
1148 }
1149}
1150
1151impl<O, T: ?Sized> Eq for OwningRef<O, T> where T: Eq {}
1152
1153impl<O, T: ?Sized> PartialOrd for OwningRef<O, T> where T: PartialOrd {
1154 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1155 (&*self as &T).partial_cmp(&*other as &T)
1156 }
1157}
1158
1159impl<O, T: ?Sized> Ord for OwningRef<O, T> where T: Ord {
1160 fn cmp(&self, other: &Self) -> Ordering {
1161 (&*self as &T).cmp(&*other as &T)
1162 }
1163}
1164
1165impl<O, T: ?Sized> Hash for OwningRef<O, T> where T: Hash {
1166 fn hash<H: Hasher>(&self, state: &mut H) {
1167 (&*self as &T).hash(state);
1168 }
1169}
1170
1171impl<O, T: ?Sized> PartialEq for OwningRefMut<O, T> where T: PartialEq {
1172 fn eq(&self, other: &Self) -> bool {
1173 (&*self as &T).eq(&*other as &T)
1174 }
1175}
1176
1177impl<O, T: ?Sized> Eq for OwningRefMut<O, T> where T: Eq {}
1178
1179impl<O, T: ?Sized> PartialOrd for OwningRefMut<O, T> where T: PartialOrd {
1180 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1181 (&*self as &T).partial_cmp(&*other as &T)
1182 }
1183}
1184
1185impl<O, T: ?Sized> Ord for OwningRefMut<O, T> where T: Ord {
1186 fn cmp(&self, other: &Self) -> Ordering {
1187 (&*self as &T).cmp(&*other as &T)
1188 }
1189}
1190
1191impl<O, T: ?Sized> Hash for OwningRefMut<O, T> where T: Hash {
1192 fn hash<H: Hasher>(&self, state: &mut H) {
1193 (&*self as &T).hash(state);
1194 }
1195}
1196
1197use std::boxed::Box;
1202use std::rc::Rc;
1203use std::sync::Arc;
1204use std::sync::{MutexGuard, RwLockReadGuard, RwLockWriteGuard};
1205use std::cell::{Ref, RefCell, RefMut};
1206
1207impl<T: 'static> ToHandle for RefCell<T> {
1208 type Handle = Ref<'static, T>;
1209 unsafe fn to_handle(x: *const Self) -> Self::Handle { (*x).borrow() }
1210}
1211
1212impl<T: 'static> ToHandleMut for RefCell<T> {
1213 type HandleMut = RefMut<'static, T>;
1214 unsafe fn to_handle_mut(x: *const Self) -> Self::HandleMut { (*x).borrow_mut() }
1215}
1216
1217pub type BoxRef<T, U = T> = OwningRef<Box<T>, U>;
1223pub type VecRef<T, U = T> = OwningRef<Vec<T>, U>;
1225pub type StringRef = OwningRef<String, str>;
1227
1228pub type RcRef<T, U = T> = OwningRef<Rc<T>, U>;
1230pub type ArcRef<T, U = T> = OwningRef<Arc<T>, U>;
1232
1233pub type RefRef<'a, T, U = T> = OwningRef<Ref<'a, T>, U>;
1235pub type RefMutRef<'a, T, U = T> = OwningRef<RefMut<'a, T>, U>;
1237pub type MutexGuardRef<'a, T, U = T> = OwningRef<MutexGuard<'a, T>, U>;
1239pub type RwLockReadGuardRef<'a, T, U = T> = OwningRef<RwLockReadGuard<'a, T>, U>;
1241pub type RwLockWriteGuardRef<'a, T, U = T> = OwningRef<RwLockWriteGuard<'a, T>, U>;
1243
1244pub type BoxRefMut<T, U = T> = OwningRefMut<Box<T>, U>;
1246pub type VecRefMut<T, U = T> = OwningRefMut<Vec<T>, U>;
1248pub type StringRefMut = OwningRefMut<String, str>;
1250
1251pub type RefMutRefMut<'a, T, U = T> = OwningRefMut<RefMut<'a, T>, U>;
1253pub type MutexGuardRefMut<'a, T, U = T> = OwningRefMut<MutexGuard<'a, T>, U>;
1255pub type RwLockWriteGuardRefMut<'a, T, U = T> = OwningRefMut<RwLockWriteGuard<'a, T>, U>;
1257
1258unsafe impl<'a, T: 'a> IntoErased<'a> for Box<T> {
1259 type Erased = Box<dyn Erased + 'a>;
1260 fn into_erased(self) -> Self::Erased {
1261 self
1262 }
1263}
1264unsafe impl<'a, T: 'a> IntoErased<'a> for Rc<T> {
1265 type Erased = Rc<dyn Erased + 'a>;
1266 fn into_erased(self) -> Self::Erased {
1267 self
1268 }
1269}
1270unsafe impl<'a, T: 'a> IntoErased<'a> for Arc<T> {
1271 type Erased = Arc<dyn Erased + 'a>;
1272 fn into_erased(self) -> Self::Erased {
1273 self
1274 }
1275}
1276
1277pub type ErasedBoxRef<U> = OwningRef<Box<dyn Erased>, U>;
1279pub type ErasedRcRef<U> = OwningRef<Rc<dyn Erased>, U>;
1281pub type ErasedArcRef<U> = OwningRef<Arc<dyn Erased>, U>;
1283
1284pub type ErasedBoxRefMut<U> = OwningRefMut<Box<dyn Erased>, U>;
1286
1287#[cfg(test)]
1288mod tests {
1289 mod owning_ref {
1290 use super::super::OwningRef;
1291 use super::super::{RcRef, BoxRef, Erased, ErasedBoxRef};
1292 use std::cmp::{PartialEq, Ord, PartialOrd, Ordering};
1293 use std::hash::{Hash, Hasher};
1294 use std::collections::hash_map::DefaultHasher;
1295 use std::collections::HashMap;
1296 use std::rc::Rc;
1297
1298 #[derive(Debug, PartialEq)]
1299 struct Example(u32, String, [u8; 3]);
1300 fn example() -> Example {
1301 Example(42, "hello world".to_string(), [1, 2, 3])
1302 }
1303
1304 #[test]
1305 fn new_deref() {
1306 let or: OwningRef<Box<()>, ()> = OwningRef::new(Box::new(()));
1307 assert_eq!(&*or, &());
1308 }
1309
1310 #[test]
1311 fn into() {
1312 let or: OwningRef<Box<()>, ()> = Box::new(()).into();
1313 assert_eq!(&*or, &());
1314 }
1315
1316 #[test]
1317 fn map_offset_ref() {
1318 let or: BoxRef<Example> = Box::new(example()).into();
1319 let or: BoxRef<_, u32> = or.map(|x| &x.0);
1320 assert_eq!(&*or, &42);
1321
1322 let or: BoxRef<Example> = Box::new(example()).into();
1323 let or: BoxRef<_, u8> = or.map(|x| &x.2[1]);
1324 assert_eq!(&*or, &2);
1325 }
1326
1327 #[test]
1328 fn map_heap_ref() {
1329 let or: BoxRef<Example> = Box::new(example()).into();
1330 let or: BoxRef<_, str> = or.map(|x| &x.1[..5]);
1331 assert_eq!(&*or, "hello");
1332 }
1333
1334 #[test]
1335 fn map_static_ref() {
1336 let or: BoxRef<()> = Box::new(()).into();
1337 let or: BoxRef<_, str> = or.map(|_| "hello");
1338 assert_eq!(&*or, "hello");
1339 }
1340
1341 #[test]
1342 fn map_chained() {
1343 let or: BoxRef<String> = Box::new(example().1).into();
1344 let or: BoxRef<_, str> = or.map(|x| &x[1..5]);
1345 let or: BoxRef<_, str> = or.map(|x| &x[..2]);
1346 assert_eq!(&*or, "el");
1347 }
1348
1349 #[test]
1350 fn map_chained_inference() {
1351 let or = BoxRef::new(Box::new(example().1))
1352 .map(|x| &x[..5])
1353 .map(|x| &x[1..3]);
1354 assert_eq!(&*or, "el");
1355 }
1356
1357 #[test]
1358 fn as_owner() {
1359 let or: BoxRef<String> = Box::new(example().1).into();
1360 let or = or.map(|x| &x[..5]);
1361 assert_eq!(&*or, "hello");
1362 assert_eq!(&**or.as_owner(), "hello world");
1363 }
1364
1365 #[test]
1366 fn into_owner() {
1367 let or: BoxRef<String> = Box::new(example().1).into();
1368 let or = or.map(|x| &x[..5]);
1369 assert_eq!(&*or, "hello");
1370 let s = *or.into_owner();
1371 assert_eq!(&s, "hello world");
1372 }
1373
1374 #[test]
1375 fn fmt_debug() {
1376 let or: BoxRef<String> = Box::new(example().1).into();
1377 let or = or.map(|x| &x[..5]);
1378 let s = format!("{:?}", or);
1379 assert_eq!(&s, "OwningRef { owner: \"hello world\", reference: \"hello\" }");
1380 }
1381
1382 #[test]
1383 fn erased_owner() {
1384 let o1: BoxRef<Example, str> = BoxRef::new(Box::new(example()))
1385 .map(|x| &x.1[..]);
1386
1387 let o2: BoxRef<String, str> = BoxRef::new(Box::new(example().1))
1388 .map(|x| &x[..]);
1389
1390 let os: Vec<ErasedBoxRef<str>> = vec![o1.erase_owner(), o2.erase_owner()];
1391 assert!(os.iter().all(|e| &e[..] == "hello world"));
1392 }
1393
1394 #[test]
1395 fn non_static_erased_owner() {
1396 let foo = [413, 612];
1397 let bar = &foo;
1398
1399 fn borrow<'a>(a: &'a &[i32; 2]) -> &'a i32 {
1403 &a[0]
1404 }
1405
1406 let o: BoxRef<&[i32; 2]> = Box::new(bar).into();
1407 let o: BoxRef<&[i32; 2], i32> = o.map(borrow);
1408 let o: BoxRef<dyn Erased, i32> = o.erase_owner();
1409
1410 assert_eq!(*o, 413);
1411 }
1412
1413 #[test]
1414 fn raii_locks() {
1415 use super::super::{RefRef, RefMutRef};
1416 use std::cell::RefCell;
1417 use super::super::{MutexGuardRef, RwLockReadGuardRef, RwLockWriteGuardRef};
1418 use std::sync::{Mutex, RwLock};
1419
1420 {
1421 let a = RefCell::new(1);
1422 let a = {
1423 let a = RefRef::new(a.borrow());
1424 assert_eq!(*a, 1);
1425 a
1426 };
1427 assert_eq!(*a, 1);
1428 drop(a);
1429 }
1430 {
1431 let a = RefCell::new(1);
1432 let a = {
1433 let a = RefMutRef::new(a.borrow_mut());
1434 assert_eq!(*a, 1);
1435 a
1436 };
1437 assert_eq!(*a, 1);
1438 drop(a);
1439 }
1440 {
1441 let a = Mutex::new(1);
1442 let a = {
1443 let a = MutexGuardRef::new(a.lock().unwrap());
1444 assert_eq!(*a, 1);
1445 a
1446 };
1447 assert_eq!(*a, 1);
1448 drop(a);
1449 }
1450 {
1451 let a = RwLock::new(1);
1452 let a = {
1453 let a = RwLockReadGuardRef::new(a.read().unwrap());
1454 assert_eq!(*a, 1);
1455 a
1456 };
1457 assert_eq!(*a, 1);
1458 drop(a);
1459 }
1460 {
1461 let a = RwLock::new(1);
1462 let a = {
1463 let a = RwLockWriteGuardRef::new(a.write().unwrap());
1464 assert_eq!(*a, 1);
1465 a
1466 };
1467 assert_eq!(*a, 1);
1468 drop(a);
1469 }
1470 }
1471
1472 #[test]
1473 fn eq() {
1474 let or1: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
1475 let or2: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
1476 assert_eq!(or1.eq(&or2), true);
1477 }
1478
1479 #[test]
1480 fn cmp() {
1481 let or1: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
1482 let or2: BoxRef<[u8]> = BoxRef::new(vec![4, 5, 6].into_boxed_slice());
1483 assert_eq!(or1.cmp(&or2), Ordering::Less);
1484 }
1485
1486 #[test]
1487 fn partial_cmp() {
1488 let or1: BoxRef<[u8]> = BoxRef::new(vec![4, 5, 6].into_boxed_slice());
1489 let or2: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
1490 assert_eq!(or1.partial_cmp(&or2), Some(Ordering::Greater));
1491 }
1492
1493 #[test]
1494 fn hash() {
1495 let mut h1 = DefaultHasher::new();
1496 let mut h2 = DefaultHasher::new();
1497
1498 let or1: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
1499 let or2: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice());
1500
1501 or1.hash(&mut h1);
1502 or2.hash(&mut h2);
1503
1504 assert_eq!(h1.finish(), h2.finish());
1505 }
1506
1507 #[test]
1508 fn borrow() {
1509 let mut hash = HashMap::new();
1510 let key = RcRef::<String>::new(Rc::new("foo-bar".to_string())).map(|s| &s[..]);
1511
1512 hash.insert(key.clone().map(|s| &s[..3]), 42);
1513 hash.insert(key.clone().map(|s| &s[4..]), 23);
1514
1515 assert_eq!(hash.get("foo"), Some(&42));
1516 assert_eq!(hash.get("bar"), Some(&23));
1517 }
1518
1519 #[test]
1520 fn total_erase() {
1521 let a: OwningRef<Vec<u8>, [u8]>
1522 = OwningRef::new(vec![]).map(|x| &x[..]);
1523 let b: OwningRef<Box<[u8]>, [u8]>
1524 = OwningRef::new(vec![].into_boxed_slice()).map(|x| &x[..]);
1525
1526 let c: OwningRef<Rc<Vec<u8>>, [u8]> = unsafe {a.map_owner(Rc::new)};
1527 let d: OwningRef<Rc<Box<[u8]>>, [u8]> = unsafe {b.map_owner(Rc::new)};
1528
1529 let e: OwningRef<Rc<dyn Erased>, [u8]> = c.erase_owner();
1530 let f: OwningRef<Rc<dyn Erased>, [u8]> = d.erase_owner();
1531
1532 let _g = e.clone();
1533 let _h = f.clone();
1534 }
1535
1536 #[test]
1537 fn total_erase_box() {
1538 let a: OwningRef<Vec<u8>, [u8]>
1539 = OwningRef::new(vec![]).map(|x| &x[..]);
1540 let b: OwningRef<Box<[u8]>, [u8]>
1541 = OwningRef::new(vec![].into_boxed_slice()).map(|x| &x[..]);
1542
1543 let c: OwningRef<Box<Vec<u8>>, [u8]> = a.map_owner_box();
1544 let d: OwningRef<Box<Box<[u8]>>, [u8]> = b.map_owner_box();
1545
1546 let _e: OwningRef<Box<dyn Erased>, [u8]> = c.erase_owner();
1547 let _f: OwningRef<Box<dyn Erased>, [u8]> = d.erase_owner();
1548 }
1549
1550 #[test]
1551 fn try_map1() {
1552 use std::any::Any;
1553
1554 let x = Box::new(123_i32);
1555 let y: Box<dyn Any> = x;
1556
1557 OwningRef::new(y).try_map(|x| x.downcast_ref::<i32>().ok_or(())).unwrap();
1558 }
1559
1560 #[test]
1561 fn try_map2() {
1562 use std::any::Any;
1563
1564 let x = Box::new(123_u32);
1565 let y: Box<dyn Any> = x;
1566
1567 OwningRef::new(y).try_map(|x| x.downcast_ref::<i32>().ok_or(())).unwrap_err();
1568 }
1569
1570 #[test]
1571 fn map_with_owner() {
1572 let owning_ref: BoxRef<Example> = Box::new(example()).into();
1573 let owning_ref = owning_ref.map(|owner| &owner.1);
1574
1575 owning_ref.map_with_owner(|owner, ref_field| {
1576 assert_eq!(owner.1, *ref_field);
1577 ref_field
1578 });
1579 }
1580
1581 #[test]
1582 fn try_map_with_owner_ok() {
1583 let owning_ref: BoxRef<Example> = Box::new(example()).into();
1584 let owning_ref = owning_ref.map(|owner| &owner.1);
1585
1586 owning_ref.try_map_with_owner(|owner, ref_field| {
1587 assert_eq!(owner.1, *ref_field);
1588 Ok(ref_field) as Result<_, ()>
1589 }).unwrap();
1590 }
1591
1592 #[test]
1593 fn try_map_with_owner_err() {
1594 let owning_ref: BoxRef<Example> = Box::new(example()).into();
1595 let owning_ref = owning_ref.map(|owner| &owner.1);
1596
1597 owning_ref.try_map_with_owner(|owner, ref_field| {
1598 assert_eq!(owner.1, *ref_field);
1599 Err(()) as Result<&(), _>
1600 }).unwrap_err();
1601 }
1602 }
1603
1604 mod owning_handle {
1605 use super::super::OwningHandle;
1606 use super::super::RcRef;
1607 use std::rc::Rc;
1608 use std::cell::RefCell;
1609 use std::sync::Arc;
1610 use std::sync::RwLock;
1611
1612 #[test]
1613 fn owning_handle() {
1614 use std::cell::RefCell;
1615 let cell = Rc::new(RefCell::new(2));
1616 let cell_ref = RcRef::new(cell);
1617 let mut handle = OwningHandle::new_with_fn(cell_ref, |x| unsafe { x.as_ref() }.unwrap().borrow_mut());
1618 assert_eq!(*handle, 2);
1619 *handle = 3;
1620 assert_eq!(*handle, 3);
1621 }
1622
1623 #[tokio::test]
1624 async fn owning_handle_async() {
1625 use std::cell::RefCell;
1626 let cell = Rc::new(RefCell::new(2));
1627 let cell_ref = RcRef::new(cell);
1628 let mut handle = OwningHandle::new_with_async_fn(cell_ref, |x| async move { unsafe { x.as_ref() }.unwrap().borrow_mut() }).await;
1629 assert_eq!(*handle, 2);
1630 *handle = 3;
1631 assert_eq!(*handle, 3);
1632 }
1633
1634 #[test]
1635 fn owning_handle_map() {
1636 use std::cell::{Ref, RefCell};
1637 let cell = Rc::new(RefCell::new(('a', 'b')));
1638 let cell_ref = RcRef::new(cell);
1639 let handle = OwningHandle::new_with_fn(cell_ref, |x| unsafe { x.as_ref() }.unwrap().borrow());
1640 assert_eq!(*handle, ('a', 'b'));
1641 let handle_map = handle.map(|r| Ref::map(r, |i| &i.0));
1642 assert_eq!(*handle_map, 'a');
1643 }
1644
1645 #[test]
1646 fn try_owning_handle_ok() {
1647 use std::cell::RefCell;
1648 let cell = Rc::new(RefCell::new(2));
1649 let cell_ref = RcRef::new(cell);
1650 let mut handle = OwningHandle::try_new::<_, ()>(cell_ref, |x| {
1651 Ok(unsafe {
1652 x.as_ref()
1653 }.unwrap().borrow_mut())
1654 }).unwrap();
1655 assert_eq!(*handle, 2);
1656 *handle = 3;
1657 assert_eq!(*handle, 3);
1658 }
1659
1660 #[tokio::test]
1661 async fn try_owning_handle_ok_async() {
1662 use std::cell::RefCell;
1663 let cell = Rc::new(RefCell::new(2));
1664 let cell_ref = RcRef::new(cell);
1665 let mut handle = OwningHandle::try_new_async::<_, (), _>(cell_ref, |x| async move {
1666 Ok(unsafe {
1667 x.as_ref()
1668 }.unwrap().borrow_mut())
1669 }).await.unwrap();
1670 assert_eq!(*handle, 2);
1671 *handle = 3;
1672 assert_eq!(*handle, 3);
1673 }
1674
1675 #[test]
1676 fn try_owning_handle_err() {
1677 use std::cell::RefCell;
1678 let cell = Rc::new(RefCell::new(2));
1679 let cell_ref = RcRef::new(cell);
1680 let handle = OwningHandle::try_new::<_, ()>(cell_ref, |x| {
1681 if false {
1682 return Ok(unsafe {
1683 x.as_ref()
1684 }.unwrap().borrow_mut())
1685 }
1686 Err(())
1687 });
1688 assert!(handle.is_err());
1689 }
1690
1691 #[tokio::test]
1692 async fn try_owning_handle_err_async() {
1693 use std::cell::RefCell;
1694 let cell = Rc::new(RefCell::new(2));
1695 let cell_ref = RcRef::new(cell);
1696 let handle = OwningHandle::try_new_async::<_, (), _>(cell_ref, |x| async move {
1697 if false {
1698 return Ok(unsafe {
1699 x.as_ref()
1700 }.unwrap().borrow_mut())
1701 }
1702 Err(())
1703 }).await;
1704 assert!(handle.is_err());
1705 }
1706
1707 #[test]
1708 fn nested() {
1709 use std::cell::RefCell;
1710 use std::sync::{Arc, RwLock};
1711
1712 let result = {
1713 let complex = Rc::new(RefCell::new(Arc::new(RwLock::new("someString"))));
1714 let curr = RcRef::new(complex);
1715 let curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().borrow_mut());
1716 let mut curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().try_write().unwrap());
1717 assert_eq!(*curr, "someString");
1718 *curr = "someOtherString";
1719 curr
1720 };
1721 assert_eq!(*result, "someOtherString");
1722 }
1723
1724 #[tokio::test]
1725 async fn nested_async() {
1726 use std::cell::RefCell;
1727 use std::sync::{Arc, RwLock};
1728
1729 let result = {
1730 let complex = Rc::new(RefCell::new(Arc::new(RwLock::new("someString"))));
1731 let curr = RcRef::new(complex);
1732 let curr = OwningHandle::new_with_async_fn(curr, |x| async move {unsafe { x.as_ref() }.unwrap().borrow_mut()}).await;
1733 let mut curr = OwningHandle::new_with_async_fn(curr, |x| async move {unsafe { x.as_ref() }.unwrap().try_write().unwrap()}).await;
1734 assert_eq!(*curr, "someString");
1735 *curr = "someOtherString";
1736 curr
1737 };
1738 assert_eq!(*result, "someOtherString");
1739 }
1740
1741 #[test]
1742 fn owning_handle_safe() {
1743 use std::cell::RefCell;
1744 let cell = Rc::new(RefCell::new(2));
1745 let cell_ref = RcRef::new(cell);
1746 let handle = OwningHandle::new(cell_ref);
1747 assert_eq!(*handle, 2);
1748 }
1749
1750 #[test]
1751 fn owning_handle_mut_safe() {
1752 use std::cell::RefCell;
1753 let cell = Rc::new(RefCell::new(2));
1754 let cell_ref = RcRef::new(cell);
1755 let mut handle = OwningHandle::new_mut(cell_ref);
1756 assert_eq!(*handle, 2);
1757 *handle = 3;
1758 assert_eq!(*handle, 3);
1759 }
1760
1761 #[test]
1762 fn owning_handle_safe_2() {
1763 let result = {
1764 let complex = Rc::new(RefCell::new(Arc::new(RwLock::new("someString"))));
1765 let curr = RcRef::new(complex);
1766 let curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().borrow_mut());
1767 let mut curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().try_write().unwrap());
1768 assert_eq!(*curr, "someString");
1769 *curr = "someOtherString";
1770 curr
1771 };
1772 assert_eq!(*result, "someOtherString");
1773 }
1774
1775 #[tokio::test]
1776 async fn owning_handle_safe_2_async() {
1777 let result = {
1778 let complex = Rc::new(RefCell::new(Arc::new(RwLock::new("someString"))));
1779 let curr = RcRef::new(complex);
1780 let curr = OwningHandle::new_with_async_fn(curr, |x| async move { unsafe { x.as_ref() }.unwrap().borrow_mut()}).await;
1781 let mut curr = OwningHandle::new_with_async_fn(curr, |x| async move { unsafe { x.as_ref() }.unwrap().try_write().unwrap()}).await;
1782 assert_eq!(*curr, "someString");
1783 *curr = "someOtherString";
1784 curr
1785 };
1786 assert_eq!(*result, "someOtherString");
1787 }
1788 }
1789
1790 mod owning_ref_mut {
1791 use super::super::{OwningRefMut, BoxRefMut, Erased, ErasedBoxRefMut};
1792 use super::super::BoxRef;
1793 use std::cmp::{PartialEq, Ord, PartialOrd, Ordering};
1794 use std::hash::{Hash, Hasher};
1795 use std::collections::hash_map::DefaultHasher;
1796 use std::collections::HashMap;
1797
1798 #[derive(Debug, PartialEq)]
1799 struct Example(u32, String, [u8; 3]);
1800 fn example() -> Example {
1801 Example(42, "hello world".to_string(), [1, 2, 3])
1802 }
1803
1804 #[test]
1805 fn new_deref() {
1806 let or: OwningRefMut<Box<()>, ()> = OwningRefMut::new(Box::new(()));
1807 assert_eq!(&*or, &());
1808 }
1809
1810 #[test]
1811 fn new_deref_mut() {
1812 let mut or: OwningRefMut<Box<()>, ()> = OwningRefMut::new(Box::new(()));
1813 assert_eq!(&mut *or, &mut ());
1814 }
1815
1816 #[test]
1817 fn mutate() {
1818 let mut or: OwningRefMut<Box<usize>, usize> = OwningRefMut::new(Box::new(0));
1819 assert_eq!(&*or, &0);
1820 *or = 1;
1821 assert_eq!(&*or, &1);
1822 }
1823
1824 #[test]
1825 fn into() {
1826 let or: OwningRefMut<Box<()>, ()> = Box::new(()).into();
1827 assert_eq!(&*or, &());
1828 }
1829
1830 #[test]
1831 fn map_offset_ref() {
1832 let or: BoxRefMut<Example> = Box::new(example()).into();
1833 let or: BoxRef<_, u32> = or.map(|x| &mut x.0);
1834 assert_eq!(&*or, &42);
1835
1836 let or: BoxRefMut<Example> = Box::new(example()).into();
1837 let or: BoxRef<_, u8> = or.map(|x| &mut x.2[1]);
1838 assert_eq!(&*or, &2);
1839 }
1840
1841 #[test]
1842 fn map_heap_ref() {
1843 let or: BoxRefMut<Example> = Box::new(example()).into();
1844 let or: BoxRef<_, str> = or.map(|x| &mut x.1[..5]);
1845 assert_eq!(&*or, "hello");
1846 }
1847
1848 #[test]
1849 fn map_static_ref() {
1850 let or: BoxRefMut<()> = Box::new(()).into();
1851 let or: BoxRef<_, str> = or.map(|_| "hello");
1852 assert_eq!(&*or, "hello");
1853 }
1854
1855 #[test]
1856 fn map_mut_offset_ref() {
1857 let or: BoxRefMut<Example> = Box::new(example()).into();
1858 let or: BoxRefMut<_, u32> = or.map_mut(|x| &mut x.0);
1859 assert_eq!(&*or, &42);
1860
1861 let or: BoxRefMut<Example> = Box::new(example()).into();
1862 let or: BoxRefMut<_, u8> = or.map_mut(|x| &mut x.2[1]);
1863 assert_eq!(&*or, &2);
1864 }
1865
1866 #[test]
1867 fn map_mut_heap_ref() {
1868 let or: BoxRefMut<Example> = Box::new(example()).into();
1869 let or: BoxRefMut<_, str> = or.map_mut(|x| &mut x.1[..5]);
1870 assert_eq!(&*or, "hello");
1871 }
1872
1873 #[test]
1874 fn map_mut_static_ref() {
1875 static mut MUT_S: [u8; 5] = *b"hello";
1876
1877 let mut_s: &'static mut [u8] = unsafe { &mut MUT_S };
1878
1879 let or: BoxRefMut<()> = Box::new(()).into();
1880 let or: BoxRefMut<_, [u8]> = or.map_mut(move |_| mut_s);
1881 assert_eq!(&*or, b"hello");
1882 }
1883
1884 #[test]
1885 fn map_mut_chained() {
1886 let or: BoxRefMut<String> = Box::new(example().1).into();
1887 let or: BoxRefMut<_, str> = or.map_mut(|x| &mut x[1..5]);
1888 let or: BoxRefMut<_, str> = or.map_mut(|x| &mut x[..2]);
1889 assert_eq!(&*or, "el");
1890 }
1891
1892 #[test]
1893 fn map_chained_inference() {
1894 let or = BoxRefMut::new(Box::new(example().1))
1895 .map_mut(|x| &mut x[..5])
1896 .map_mut(|x| &mut x[1..3]);
1897 assert_eq!(&*or, "el");
1898 }
1899
1900 #[test]
1901 fn try_map_mut() {
1902 let or: BoxRefMut<String> = Box::new(example().1).into();
1903 let or: Result<BoxRefMut<_, str>, ()> = or.try_map_mut(|x| Ok(&mut x[1..5]));
1904 assert_eq!(&*or.unwrap(), "ello");
1905
1906 let or: BoxRefMut<String> = Box::new(example().1).into();
1907 let or: Result<BoxRefMut<_, str>, ()> = or.try_map_mut(|_| Err(()));
1908 assert!(or.is_err());
1909 }
1910
1911 #[test]
1912 fn as_owner() {
1913 let or: BoxRefMut<String> = Box::new(example().1).into();
1914 let or = or.map_mut(|x| &mut x[..5]);
1915 assert_eq!(&*or, "hello");
1916 assert_eq!(&**or.as_owner(), "hello world");
1917 }
1918
1919 #[test]
1920 fn into_owner() {
1921 let or: BoxRefMut<String> = Box::new(example().1).into();
1922 let or = or.map_mut(|x| &mut x[..5]);
1923 assert_eq!(&*or, "hello");
1924 let s = *or.into_owner();
1925 assert_eq!(&s, "hello world");
1926 }
1927
1928 #[test]
1929 fn fmt_debug() {
1930 let or: BoxRefMut<String> = Box::new(example().1).into();
1931 let or = or.map_mut(|x| &mut x[..5]);
1932 let s = format!("{:?}", or);
1933 assert_eq!(&s,
1934 "OwningRefMut { owner: \"hello world\", reference: \"hello\" }");
1935 }
1936
1937 #[test]
1938 fn erased_owner() {
1939 let o1: BoxRefMut<Example, str> = BoxRefMut::new(Box::new(example()))
1940 .map_mut(|x| &mut x.1[..]);
1941
1942 let o2: BoxRefMut<String, str> = BoxRefMut::new(Box::new(example().1))
1943 .map_mut(|x| &mut x[..]);
1944
1945 let os: Vec<ErasedBoxRefMut<str>> = vec![o1.erase_owner(), o2.erase_owner()];
1946 assert!(os.iter().all(|e| &e[..] == "hello world"));
1947 }
1948
1949 #[test]
1950 fn non_static_erased_owner() {
1951 let mut foo = [413, 612];
1952 let bar = &mut foo;
1953
1954 fn borrow<'a>(a: &'a mut &mut [i32; 2]) -> &'a mut i32 {
1958 &mut a[0]
1959 }
1960
1961 let o: BoxRefMut<&mut [i32; 2]> = Box::new(bar).into();
1962 let o: BoxRefMut<&mut [i32; 2], i32> = o.map_mut(borrow);
1963 let o: BoxRefMut<dyn Erased, i32> = o.erase_owner();
1964
1965 assert_eq!(*o, 413);
1966 }
1967
1968 #[test]
1969 fn raii_locks() {
1970 use super::super::RefMutRefMut;
1971 use std::cell::RefCell;
1972 use super::super::{MutexGuardRefMut, RwLockWriteGuardRefMut};
1973 use std::sync::{Mutex, RwLock};
1974
1975 {
1976 let a = RefCell::new(1);
1977 let a = {
1978 let a = RefMutRefMut::new(a.borrow_mut());
1979 assert_eq!(*a, 1);
1980 a
1981 };
1982 assert_eq!(*a, 1);
1983 drop(a);
1984 }
1985 {
1986 let a = Mutex::new(1);
1987 let a = {
1988 let a = MutexGuardRefMut::new(a.lock().unwrap());
1989 assert_eq!(*a, 1);
1990 a
1991 };
1992 assert_eq!(*a, 1);
1993 drop(a);
1994 }
1995 {
1996 let a = RwLock::new(1);
1997 let a = {
1998 let a = RwLockWriteGuardRefMut::new(a.write().unwrap());
1999 assert_eq!(*a, 1);
2000 a
2001 };
2002 assert_eq!(*a, 1);
2003 drop(a);
2004 }
2005 }
2006
2007 #[test]
2008 fn eq() {
2009 let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
2010 let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
2011 assert_eq!(or1.eq(&or2), true);
2012 }
2013
2014 #[test]
2015 fn cmp() {
2016 let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
2017 let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![4, 5, 6].into_boxed_slice());
2018 assert_eq!(or1.cmp(&or2), Ordering::Less);
2019 }
2020
2021 #[test]
2022 fn partial_cmp() {
2023 let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![4, 5, 6].into_boxed_slice());
2024 let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
2025 assert_eq!(or1.partial_cmp(&or2), Some(Ordering::Greater));
2026 }
2027
2028 #[test]
2029 fn hash() {
2030 let mut h1 = DefaultHasher::new();
2031 let mut h2 = DefaultHasher::new();
2032
2033 let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
2034 let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice());
2035
2036 or1.hash(&mut h1);
2037 or2.hash(&mut h2);
2038
2039 assert_eq!(h1.finish(), h2.finish());
2040 }
2041
2042 #[test]
2043 fn borrow() {
2044 let mut hash = HashMap::new();
2045 let key1 = BoxRefMut::<String>::new(Box::new("foo".to_string())).map(|s| &s[..]);
2046 let key2 = BoxRefMut::<String>::new(Box::new("bar".to_string())).map(|s| &s[..]);
2047
2048 hash.insert(key1, 42);
2049 hash.insert(key2, 23);
2050
2051 assert_eq!(hash.get("foo"), Some(&42));
2052 assert_eq!(hash.get("bar"), Some(&23));
2053 }
2054
2055 #[test]
2056 fn total_erase() {
2057 let a: OwningRefMut<Vec<u8>, [u8]>
2058 = OwningRefMut::new(vec![]).map_mut(|x| &mut x[..]);
2059 let b: OwningRefMut<Box<[u8]>, [u8]>
2060 = OwningRefMut::new(vec![].into_boxed_slice()).map_mut(|x| &mut x[..]);
2061
2062 let c: OwningRefMut<Box<Vec<u8>>, [u8]> = unsafe {a.map_owner(Box::new)};
2063 let d: OwningRefMut<Box<Box<[u8]>>, [u8]> = unsafe {b.map_owner(Box::new)};
2064
2065 let _e: OwningRefMut<Box<dyn Erased>, [u8]> = c.erase_owner();
2066 let _f: OwningRefMut<Box<dyn Erased>, [u8]> = d.erase_owner();
2067 }
2068
2069 #[test]
2070 fn total_erase_box() {
2071 let a: OwningRefMut<Vec<u8>, [u8]>
2072 = OwningRefMut::new(vec![]).map_mut(|x| &mut x[..]);
2073 let b: OwningRefMut<Box<[u8]>, [u8]>
2074 = OwningRefMut::new(vec![].into_boxed_slice()).map_mut(|x| &mut x[..]);
2075
2076 let c: OwningRefMut<Box<Vec<u8>>, [u8]> = a.map_owner_box();
2077 let d: OwningRefMut<Box<Box<[u8]>>, [u8]> = b.map_owner_box();
2078
2079 let _e: OwningRefMut<Box<dyn Erased>, [u8]> = c.erase_owner();
2080 let _f: OwningRefMut<Box<dyn Erased>, [u8]> = d.erase_owner();
2081 }
2082
2083 #[test]
2084 fn try_map1() {
2085 use std::any::Any;
2086
2087 let x = Box::new(123_i32);
2088 let y: Box<dyn Any> = x;
2089
2090 OwningRefMut::new(y).try_map_mut(|x| x.downcast_mut::<i32>().ok_or(())).unwrap();
2091 }
2092
2093 #[test]
2094 fn try_map2() {
2095 use std::any::Any;
2096
2097 let x = Box::new(123_u32);
2098 let y: Box<dyn Any> = x;
2099
2100 OwningRefMut::new(y).try_map_mut(|x| x.downcast_mut::<i32>().ok_or(())).unwrap_err();
2101 }
2102
2103 #[test]
2104 fn try_map3() {
2105 use std::any::Any;
2106
2107 let x = Box::new(123_i32);
2108 let y: Box<dyn Any> = x;
2109
2110 OwningRefMut::new(y).try_map(|x| x.downcast_ref::<i32>().ok_or(())).unwrap();
2111 }
2112
2113 #[test]
2114 fn try_map4() {
2115 use std::any::Any;
2116
2117 let x = Box::new(123_u32);
2118 let y: Box<dyn Any> = x;
2119
2120 OwningRefMut::new(y).try_map(|x| x.downcast_ref::<i32>().ok_or(())).unwrap_err();
2121 }
2122
2123 #[test]
2124 fn into_owning_ref() {
2125 use super::super::BoxRef;
2126
2127 let or: BoxRefMut<()> = Box::new(()).into();
2128 let or: BoxRef<()> = or.into();
2129 assert_eq!(&*or, &());
2130 }
2131
2132 struct Foo {
2133 u: u32,
2134 }
2135 struct Bar {
2136 f: Foo,
2137 }
2138
2139 #[test]
2140 fn ref_mut() {
2141 use std::cell::RefCell;
2142
2143 let a = RefCell::new(Bar { f: Foo { u: 42 } });
2144 let mut b = OwningRefMut::new(a.borrow_mut());
2145 assert_eq!(b.f.u, 42);
2146 b.f.u = 43;
2147 let mut c = b.map_mut(|x| &mut x.f);
2148 assert_eq!(c.u, 43);
2149 c.u = 44;
2150 let mut d = c.map_mut(|x| &mut x.u);
2151 assert_eq!(*d, 44);
2152 *d = 45;
2153 assert_eq!(*d, 45);
2154 }
2155 }
2156}