Skip to content

Commit 2fbbd54

Browse files
committed
Auto merge of #26122 - bluss:borrow-box, r=alexcrichton
Implement Borrow<T> and BorrowMut<T> for Box<T: ?Sized>
2 parents fbb1354 + 4fdb4cf commit 2fbbd54

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

src/libcollections/borrow.rs

+9-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use core::ops::Deref;
2121
use core::option::Option;
2222

2323
use fmt;
24-
use alloc::{rc, arc};
24+
use alloc::{boxed, rc, arc};
2525

2626
use self::Cow::*;
2727

@@ -116,6 +116,14 @@ impl<'a, T: ?Sized> BorrowMut<T> for &'a mut T {
116116
fn borrow_mut(&mut self) -> &mut T { &mut **self }
117117
}
118118

119+
impl<T: ?Sized> Borrow<T> for boxed::Box<T> {
120+
fn borrow(&self) -> &T { &**self }
121+
}
122+
123+
impl<T: ?Sized> BorrowMut<T> for boxed::Box<T> {
124+
fn borrow_mut(&mut self) -> &mut T { &mut **self }
125+
}
126+
119127
impl<T: ?Sized> Borrow<T> for rc::Rc<T> {
120128
fn borrow(&self) -> &T { &**self }
121129
}

src/libcollectionstest/btree/map.rs

+29
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ use std::collections::BTreeMap;
1212
use std::collections::Bound::{Excluded, Included, Unbounded, self};
1313
use std::collections::btree_map::Entry::{Occupied, Vacant};
1414
use std::iter::range_inclusive;
15+
use std::rc::Rc;
1516

1617
#[test]
1718
fn test_basic_large() {
@@ -198,6 +199,34 @@ fn test_range() {
198199
}
199200
}
200201

202+
#[test]
203+
fn test_borrow() {
204+
// make sure these compile -- using the Borrow trait
205+
{
206+
let mut map = BTreeMap::new();
207+
map.insert("0".to_string(), 1);
208+
assert_eq!(map["0"], 1);
209+
}
210+
211+
{
212+
let mut map = BTreeMap::new();
213+
map.insert(Box::new(0), 1);
214+
assert_eq!(map[&0], 1);
215+
}
216+
217+
{
218+
let mut map = BTreeMap::new();
219+
map.insert(Box::new([0, 1]) as Box<[i32]>, 1);
220+
assert_eq!(map[&[0, 1][..]], 1);
221+
}
222+
223+
{
224+
let mut map = BTreeMap::new();
225+
map.insert(Rc::new(0), 1);
226+
assert_eq!(map[&0], 1);
227+
}
228+
}
229+
201230
#[test]
202231
fn test_entry(){
203232
let xs = [(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)];

0 commit comments

Comments
 (0)