@@ -1554,6 +1554,12 @@ impl<'a, K, V> Entry<'a, K, V> {
1554
1554
}
1555
1555
1556
1556
impl < ' a , K , V > OccupiedEntry < ' a , K , V > {
1557
+ /// Gets a reference to the key in the entry.
1558
+ #[ unstable( feature = "map_entry_keys" , issue = "32281" ) ]
1559
+ pub fn key ( & self ) -> & K {
1560
+ self . elem . read ( ) . 0
1561
+ }
1562
+
1557
1563
/// Gets a reference to the value in the entry.
1558
1564
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
1559
1565
pub fn get ( & self ) -> & V {
@@ -1589,6 +1595,13 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> {
1589
1595
}
1590
1596
1591
1597
impl < ' a , K : ' a , V : ' a > VacantEntry < ' a , K , V > {
1598
+ /// Gets a reference to the key that would be used when inserting a value
1599
+ /// through the VacantEntry.
1600
+ #[ unstable( feature = "map_entry_keys" , issue = "32281" ) ]
1601
+ pub fn key ( & self ) -> & K {
1602
+ & self . key
1603
+ }
1604
+
1592
1605
/// Sets the value of the entry with the VacantEntry's key,
1593
1606
/// and returns a mutable reference to it
1594
1607
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
@@ -2434,4 +2447,40 @@ mod test_map {
2434
2447
a. insert ( item, 0 ) ;
2435
2448
assert ! ( a. capacity( ) > a. len( ) ) ;
2436
2449
}
2450
+
2451
+ #[ test]
2452
+ fn test_occupied_entry_key ( ) {
2453
+ let mut a = HashMap :: new ( ) ;
2454
+ let key = "hello there" ;
2455
+ let value = "value goes here" ;
2456
+ assert ! ( a. is_empty( ) ) ;
2457
+ a. insert ( key. clone ( ) , value. clone ( ) ) ;
2458
+ assert_eq ! ( a. len( ) , 1 ) ;
2459
+ assert_eq ! ( a[ key] , value) ;
2460
+
2461
+ match a. entry ( key. clone ( ) ) {
2462
+ Vacant ( _) => panic ! ( ) ,
2463
+ Occupied ( e) => assert_eq ! ( key, * e. key( ) ) ,
2464
+ }
2465
+ assert_eq ! ( a. len( ) , 1 ) ;
2466
+ assert_eq ! ( a[ key] , value) ;
2467
+ }
2468
+
2469
+ #[ test]
2470
+ fn test_vacant_entry_key ( ) {
2471
+ let mut a = HashMap :: new ( ) ;
2472
+ let key = "hello there" ;
2473
+ let value = "value goes here" ;
2474
+
2475
+ assert ! ( a. is_empty( ) ) ;
2476
+ match a. entry ( key. clone ( ) ) {
2477
+ Occupied ( _) => panic ! ( ) ,
2478
+ Vacant ( e) => {
2479
+ assert_eq ! ( key, * e. key( ) ) ;
2480
+ e. insert ( value. clone ( ) ) ;
2481
+ } ,
2482
+ }
2483
+ assert_eq ! ( a. len( ) , 1 ) ;
2484
+ assert_eq ! ( a[ key] , value) ;
2485
+ }
2437
2486
}
0 commit comments