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
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::default::Default;
use std::cmp::Ordering::{self, Less, Equal, Greater};
use std::fmt::{self, Debug};
use std::iter::{self, IntoIterator};
use std::mem::{replace, swap};
use std::ops;
use std::ops::Deref;
use std::ptr;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;

use compare::{Compare, Natural, natural};

use super::Bound;

/// This is implemented as an AA tree, which is a simplified variation of
/// a red-black tree where red (horizontal) nodes can only be added
/// as a right child. The time complexity is the same, and re-balancing
/// operations are more frequent but also cheaper.
///
/// # Examples
///
/// ```rust
/// use stable_bst::TreeMap;
///
/// let mut map = TreeMap::new();
///
/// map.insert(2, "bar");
/// map.insert(1, "foo");
/// map.insert(3, "quux");
///
/// // In ascending order by keys
/// for (key, value) in map.iter() {
///     println!("{}: {}", key, value);
/// }
///
/// // Prints 1, 2, 3
/// for key in map.keys() {
///     println!("{}", key);
/// }
///
/// // Prints `foo`, `bar`, `quux`
/// for value in map.values() {
///     println!("{}", value);
/// }
///
/// map.remove(&1);
/// assert_eq!(map.len(), 2);
///
/// if !map.contains_key(&1) {
///     println!("1 is no more");
/// }
///
/// for key in 0..4 {
///     match map.get(&key) {
///         Some(value) => println!("{} has a value: {}", key, value),
///         None => println!("{} not in map", key),
///     }
/// }
///
/// map.clear();
/// assert!(map.is_empty());
/// ```
///
/// A `TreeMap` can also be used with a custom ordering:
///
/// ```rust

/// use stable_bst::TreeMap;
///
/// struct Troll<'a> {
///     name: &'a str,
///     level: u32,
/// }
///
/// // Use a map to store trolls, sorted by level, and track a list of
/// // heroes slain.
/// let mut trolls = TreeMap::with_comparator(|l: &Troll, r: &Troll| l.level.cmp(&r.level));
///
/// trolls.insert(Troll { name: "Orgarr", level: 2 },
///               vec!["King Karl"]);
/// trolls.insert(Troll { name: "Blargarr", level: 3 },
///               vec!["Odd"]);
/// trolls.insert(Troll { name: "Kron the Smelly One", level: 4 },
///               vec!["Omar the Brave", "Peter: Slayer of Trolls"]);
/// trolls.insert(Troll { name: "Wartilda", level: 1 },
///               vec![]);
///
/// println!("You are facing {} trolls!", trolls.len());
///
/// // Print the trolls, ordered by level with smallest level first
/// for (troll, heroes) in trolls.iter() {
///     let what = if heroes.len() == 1 { "hero" }
///                else { "heroes" };
///
///     println!("level {}: '{}' has slain {} {}",
///              troll.level, troll.name, heroes.len(), what);
/// }
///
/// // Kill all trolls
/// trolls.clear();
/// assert_eq!(trolls.len(), 0);
/// ```
// Future improvements:
//
// range search - O(log n) retrieval of an iterator from some key
//
// (possibly) implement the overloads Python does for sets:
//   * intersection: &
//   * difference: -
//   * symmetric difference: ^
//   * union: |
// These would be convenient since the methods work like `each`
#[derive(Clone)]
pub struct TreeMap<K, V, C: Compare<K> = Natural<K>> {
    root: Option<Box<TreeNode<K, V>>>,
    length: usize,
    cmp: C,
}

// FIXME: determine what `PartialEq` means for comparator-based `TreeMap`s
impl<K: PartialEq + Ord, V: PartialEq> PartialEq for TreeMap<K, V> {
    #[inline]
    fn eq(&self, other: &TreeMap<K, V>) -> bool {
        self.iter().eq(other)
    }
}

// FIXME: determine what `Eq` means for comparator-based `TreeMap`s
impl<K: Eq + Ord, V: Eq> Eq for TreeMap<K, V> {}

// FIXME: determine what `PartialOrd` means for comparator-based `TreeMap`s
impl<K: Ord, V: PartialOrd> PartialOrd for TreeMap<K, V> {
    #[inline]
    fn partial_cmp(&self, other: &TreeMap<K, V>) -> Option<Ordering> {
        self.iter().partial_cmp(other)
    }
}

// FIXME: determine what `Ord` means for comparator-based `TreeMap`s
impl<K: Ord, V: Ord> Ord for TreeMap<K, V> {
    #[inline]
    fn cmp(&self, other: &TreeMap<K, V>) -> Ordering {
        self.iter().cmp(other)
    }
}

impl<K: Debug, V: Debug, C> Debug for TreeMap<K, V, C>
    where C: Compare<K>
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "{{"));

        for (i, (k, v)) in self.iter().enumerate() {
            if i != 0 {
                try!(write!(f, ", "));
            }
            try!(write!(f, "{:?}: {:?}", *k, *v));
        }

        write!(f, "}}")
    }
}

impl<K, V, C> Default for TreeMap<K, V, C>
    where C: Compare<K> + Default
{
    #[inline]
    fn default() -> TreeMap<K, V, C> {
        TreeMap::with_comparator(Default::default())
    }
}

impl<'a, K, V, C, Q: ?Sized> ops::Index<&'a Q> for TreeMap<K, V, C>
    where C: Compare<K> + Compare<Q, K>
{
    type Output = V;
    #[inline]
    fn index(&self, i: &'a Q) -> &V {
        self.get(i).expect("no entry found for key")
    }
}

impl<'a, K, V, C, Q: ?Sized> ops::IndexMut<&'a Q> for TreeMap<K, V, C>
    where C: Compare<K> + Compare<Q, K>
{
    #[inline]
    fn index_mut(&mut self, i: &'a Q) -> &mut V {
        self.get_mut(i).expect("no entry found for key")
    }
}

impl<K: Ord, V> TreeMap<K, V> {
    /// Creates an empty `TreeMap` ordered according to the natural order of its keys.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stable_bst::TreeMap;
    /// let mut map: TreeMap<&str, i32> = TreeMap::new();
    /// ```
    pub fn new() -> TreeMap<K, V> {
        TreeMap::with_comparator(natural())
    }
}

impl<K, V, C> TreeMap<K, V, C>
    where C: Compare<K>
{
    /// Creates an empty `TreeMap` ordered according to the given comparator.
    pub fn with_comparator(cmp: C) -> TreeMap<K, V, C> {
        TreeMap {
            root: None,
            length: 0,
            cmp: cmp,
        }
    }

    /// Returns the comparator according to which the `TreeMap` is ordered.
    pub fn comparator(&self) -> &C {
        &self.cmp
    }

    /// Gets a lazy iterator over the keys in the map, in ascending order.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stable_bst::TreeMap;
    /// let mut map = TreeMap::new();
    /// map.insert("a", 1);
    /// map.insert("c", 3);
    /// map.insert("b", 2);
    ///
    /// // Print "a", "b", "c" in order.
    /// for x in map.keys() {
    ///     println!("{}", x);
    /// }
    /// ```
    pub fn keys<'a>(&'a self) -> Keys<'a, K, V> {
        fn first<A, B>((a, _): (A, B)) -> A {
            a
        }
        let first: fn((&'a K, &'a V)) -> &'a K = first; // coerce to fn pointer

        Keys(self.iter().map(first))
    }

    /// Gets a lazy iterator over the values in the map, in ascending order
    /// with respect to the corresponding keys.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stable_bst::TreeMap;
    /// let mut map = TreeMap::new();
    /// map.insert("a", 1);
    /// map.insert("c", 3);
    /// map.insert("b", 2);
    ///
    /// // Print 1, 2, 3 ordered by keys.
    /// for x in map.values() {
    ///     println!("{}", x);
    /// }
    /// ```
    pub fn values<'a>(&'a self) -> Values<'a, K, V> {
        fn second<A, B>((_, b): (A, B)) -> B {
            b
        }
        let second: fn((&'a K, &'a V)) -> &'a V = second; // coerce to fn pointer

        Values(self.iter().map(second))
    }

    /// Gets a lazy iterator over the key-value pairs in the map, in ascending order.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stable_bst::TreeMap;
    /// let mut map = TreeMap::new();
    /// map.insert("a", 1);
    /// map.insert("c", 3);
    /// map.insert("b", 2);
    ///
    /// // Print contents in ascending order
    /// for (key, value) in map.iter() {
    ///     println!("{}: {}", key, value);
    /// }
    /// ```
    pub fn iter(&self) -> Iter<K, V, Forward> {
        Iter { iter_mut: (unsafe { &mut *(self as *const Self as *mut Self) }).iter_mut() }
    }

    fn iter_mut_dir<D: Direction>(&mut self) -> IterMut<K, V, D> {
        IterMut {
            stack: vec![],
            node: deref_mut(&mut self.root),
            direction: PhantomData,
        }
    }

    /// Gets a lazy forward iterator over the key-value pairs in the
    /// map, with the values being mutable.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stable_bst::TreeMap;
    /// let mut map = TreeMap::new();
    /// map.insert("a", 1);
    /// map.insert("c", 3);
    /// map.insert("b", 2);
    ///
    /// // Add 10 until we find "b"
    /// for (key, value) in map.iter_mut() {
    ///     *value += 10;
    ///     if key == &"b" { break }
    /// }
    ///
    /// assert_eq!(map.get(&"a"), Some(&11));
    /// assert_eq!(map.get(&"b"), Some(&12));
    /// assert_eq!(map.get(&"c"), Some(&3));
    /// ```
    pub fn iter_mut(&mut self) -> IterMut<K, V, Forward> {
        self.iter_mut_dir()
    }

    /// Gets a lazy iterator that consumes the treemap.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stable_bst::TreeMap;
    /// let mut map = TreeMap::new();
    /// map.insert("a", 1);
    /// map.insert("c", 3);
    /// map.insert("b", 2);
    ///
    /// // Not possible with a regular `.iter()`
    /// let vec: Vec<(&str, i32)> = map.into_iter().collect();
    /// assert_eq!(vec, vec![("a", 1), ("b", 2), ("c", 3)]);
    /// ```
    pub fn into_iter(self) -> IntoIter<K, V> {
        let TreeMap { root, length, .. } = self;
        let stk = match root {
            None => vec![],
            Some(b) => vec![*b],
        };
        IntoIter {
            stack: stk,
            remaining: length,
        }
    }

    /// Return the number of elements in the map.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stable_bst::TreeMap;
    ///
    /// let mut a = TreeMap::new();
    /// assert_eq!(a.len(), 0);
    /// a.insert(1, "a");
    /// assert_eq!(a.len(), 1);
    /// ```
    pub fn len(&self) -> usize {
        self.length
    }

    /// Return true if the map contains no elements.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stable_bst::TreeMap;
    ///
    /// let mut a = TreeMap::new();
    /// assert!(a.is_empty());
    /// a.insert(1, "a");
    /// assert!(!a.is_empty());
    /// ```
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Clears the map, removing all values.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stable_bst::TreeMap;
    ///
    /// let mut a = TreeMap::new();
    /// a.insert(1, "a");
    /// a.clear();
    /// assert!(a.is_empty());
    /// ```
    pub fn clear(&mut self) {
        self.root = None;
        self.length = 0
    }

    /// Returns a reference to the value corresponding to the key.
    ///
    /// The key may be any borrowed form of the map's key type, but the ordering
    /// on the borrowed form *must* match the ordering on the key type.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stable_bst::TreeMap;
    ///
    /// let mut map = TreeMap::new();
    /// map.insert(1, "a");
    /// assert_eq!(map.get(&1), Some(&"a"));
    /// assert_eq!(map.get(&2), None);
    /// ```
    #[inline]
    pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
        where C: Compare<Q, K>
    {
        // FIXME: redundant, but a bug in method-level where clauses requires it
        fn f<'r, K, V, C, Q: ?Sized>(node: &'r Option<Box<TreeNode<K, V>>>,
                                     cmp: &C,
                                     key: &Q)
                                     -> Option<&'r V>
            where C: Compare<Q, K>
        {
            tree_find_with(node, |k| cmp.compare(key, k))
        }

        f(&self.root, &self.cmp, key)
    }

    /// Returns true if the map contains a value for the specified key.
    ///
    /// The key may be any borrowed form of the map's key type, but the ordering
    /// on the borrowed form *must* match the ordering on the key type.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stable_bst::TreeMap;
    ///
    /// let mut map = TreeMap::new();
    /// map.insert(1, "a");
    /// assert_eq!(map.contains_key(&1), true);
    /// assert_eq!(map.contains_key(&2), false);
    /// ```
    #[inline]
    pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
        where C: Compare<Q, K>
    {
        self.get(key).is_some()
    }

    /// Returns a mutable reference to the value corresponding to the key.
    ///
    /// The key may be any borrowed form of the map's key type, but the ordering
    /// on the borrowed form *must* match the ordering on the key type.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stable_bst::TreeMap;
    ///
    /// let mut map = TreeMap::new();
    /// map.insert(1, "a");
    /// match map.get_mut(&1) {
    ///     Some(x) => *x = "b",
    ///     None => (),
    /// }
    /// assert_eq!(map[&1], "b");
    /// ```
    #[inline]
    pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
        where C: Compare<Q, K>
    {
        // FIXME: redundant, but a bug in method-level where clauses requires it
        fn f<'r, K, V, C, Q: ?Sized>(node: &'r mut Option<Box<TreeNode<K, V>>>,
                                     cmp: &C,
                                     key: &Q)
                                     -> Option<&'r mut V>
            where C: Compare<Q, K>
        {
            tree_find_with_mut(node, |k| cmp.compare(key, k))
        }

        f(&mut self.root, &self.cmp, key)
    }

    /// Inserts a key-value pair from the map. If the key already had a value
    /// present in the map, that value is returned. Otherwise, `None` is returned.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stable_bst::TreeMap;
    ///
    /// let mut map = TreeMap::new();
    /// assert_eq!(map.insert(37, "a"), None);
    /// assert_eq!(map.is_empty(), false);
    ///
    /// map.insert(37, "b");
    /// assert_eq!(map.insert(37, "c"), Some("b"));
    /// assert_eq!(map[&37], "c");
    /// ```
    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
        let ret = insert(&mut self.root, key, value, &self.cmp);
        if ret.is_none() {
            self.length += 1
        }
        ret
    }

    /// Removes a key from the map, returning the value at the key if the key
    /// was previously in the map.
    ///
    /// The key may be any borrowed form of the map's key type, but the ordering
    /// on the borrowed form *must* match the ordering on the key type.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stable_bst::TreeMap;
    ///
    /// let mut map = TreeMap::new();
    /// map.insert(1, "a");
    /// assert_eq!(map.remove(&1), Some("a"));
    /// assert_eq!(map.remove(&1), None);
    /// ```
    pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
        where C: Compare<Q, K>
    {
        let ret = remove(&mut self.root, key, &self.cmp);
        if ret.is_some() {
            self.length -= 1
        }
        ret
    }

    /// Returns the value for which `f(key)` returns `Equal`. `f` is invoked
    /// with current key and guides tree navigation. That means `f` should
    /// be aware of natural ordering of the tree.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use stable_bst::TreeMap;
    ///
    /// fn get_headers() -> TreeMap<&'static str, &'static str> {
    ///     let mut result = TreeMap::new();
    ///     result.insert("Content-Type", "application/xml");
    ///     result.insert("User-Agent", "Curl-Rust/0.1");
    ///     result
    /// }
    ///
    /// let headers = get_headers();
    /// let ua_key = "User-Agent";
    /// let ua = headers.find_with(|&k| {
    ///    ua_key.cmp(k)
    /// });
    ///
    /// assert_eq!(*ua.unwrap(), "Curl-Rust/0.1");
    /// ```
    #[inline]
    pub fn find_with<F>(&self, f: F) -> Option<&V>
        where F: FnMut(&K) -> Ordering
    {
        tree_find_with(&self.root, f)
    }

    /// Returns the value for which `f(key)` returns `Equal`. `f` is invoked
    /// with current key and guides tree navigation. That means `f` should
    /// be aware of natural ordering of the tree.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let mut t = stable_bst::TreeMap::new();
    /// t.insert("Content-Type", "application/xml");
    /// t.insert("User-Agent", "Curl-Rust/0.1");
    ///
    /// let new_ua = "Safari/156.0";
    /// match t.find_with_mut(|&k| "User-Agent".cmp(k)) {
    ///    Some(x) => *x = new_ua,
    ///    None => panic!(),
    /// }
    ///
    /// assert_eq!(t.get(&"User-Agent"), Some(&new_ua));
    /// ```
    #[inline]
    pub fn find_with_mut<F>(&mut self, f: F) -> Option<&mut V>
        where F: FnMut(&K) -> Ordering
    {
        tree_find_with_mut(&mut self.root, f)
    }
}

// range iterators.

impl<K, V, C> TreeMap<K, V, C>
    where C: Compare<K>
{
    fn compare_bound<D, Q: ?Sized>(&self, bound: Bound<&Q>, key: &K) -> Ordering
        where C: Compare<Q, K>,
              D: Direction
    {
        if D::forward() {
            match bound {
                Bound::Unbounded => Less,
                Bound::Included(k) => self.cmp.compare(k, key),
                Bound::Excluded(k) => {
                    match self.cmp.compare(k, key) {
                        Less => Less,
                        Greater | Equal => Greater,
                    }
                }
            }
        } else {
            match bound {
                Bound::Unbounded => Greater,
                Bound::Included(k) => self.cmp.compare(k, key),
                Bound::Excluded(k) => {
                    match self.cmp.compare(k, key) {
                        Less | Equal => Less,
                        Greater => Greater,
                    }
                }
            }
        }
    }

    fn bound_setup<'a, D, Q: ?Sized>(&self,
                                     mut iter: IterMut<'a, K, V, D>,
                                     bound: Bound<&Q>)
                                     -> IterMut<'a, K, V, D>
        where C: Compare<Q, K>,
              D: Direction
    {
        loop {
            if !iter.node.is_null() {
                let node_k = unsafe { &(*iter.node).key };
                match self.compare_bound::<D, Q>(bound, node_k) {
                    Less => iter.traverse_before(),
                    Greater => iter.traverse_after(),
                    Equal => {
                        iter.traverse_complete();
                        return iter;
                    }
                }
            } else {
                iter.traverse_complete();
                return iter;
            }
        }
    }

    /// Constructs a mutable double-ended iterator over a sub-range of elements in the map, starting
    /// at min, and ending at max. If min is `Unbounded`, then it will be treated as "negative
    /// infinity", and if max is `Unbounded`, then it will be treated as "positive infinity".
    /// Thus range(Unbounded, Unbounded) will yield the whole collection.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use stable_bst::TreeMap;
    /// use stable_bst::Bound::{Included, Excluded};
    ///
    /// let mut map: TreeMap<&str, i32> = ["Alice", "Bob", "Carol", "Cheryl"].iter()
    ///                                                                      .map(|&s| (s, 0))
    ///                                                                      .collect();
    /// for (_, balance) in map.range_mut(Included(&"B"), Excluded(&"Cheryl")) {
    ///     *balance += 100;
    /// }
    /// for (name, balance) in &map {
    ///     println!("{} => {}", name, balance);
    /// }
    /// ```
    pub fn range_mut<'a, Min: ?Sized, Max: ?Sized>(&'a mut self,
                                                   min: Bound<&Min>,
                                                   max: Bound<&Max>)
                                                   -> RangeMut<'a, K, V>
        where C: Compare<Min, K> + Compare<Max, K>
    {
        let none = None;
        let mut node = &self.root;
        loop {
            match node {
                &None => {
                    return RangeMut {
                        start: (unsafe { &mut *(self as *const Self as *mut Self) }).iter_mut_dir(),
                        end: (unsafe { &mut *(self as *const Self as *mut Self) }).iter_mut_dir(),
                        empty: true,
                    }
                }
                &Some(ref n) => {
                    match (self.compare_bound::<Forward, Min>(min, &n.key),
                           self.compare_bound::<Backward, Max>(max, &n.key)) {
                        // If both endpoints are in the same subtree, descend into that subtree
                        (Less, Less) => node = &n.left,
                        (Greater, Greater) => node = &n.right,
                        // If start endpoint is actually > the end endpoint, return empty iterator
                        (Equal, Less) | (Greater, Less) | (Greater, Equal) => node = &none,
                        (Less, Equal) | (Less, Greater) | (Equal, Equal) | (Equal, Greater) => {
                            // We now know that the iterator will be non-empty.
                            // Populate the iterators.
                            let start: IterMut<K, V, Forward> = IterMut {
                                stack: vec![],
                                node: n.deref() as *const TreeNode<K, V> as *mut TreeNode<K, V>,
                                direction: PhantomData,
                            };
                            let end: IterMut<K, V, Backward> = IterMut {
                                stack: vec![],
                                node: n.deref() as *const TreeNode<K, V> as *mut TreeNode<K, V>,
                                direction: PhantomData,
                            };
                            return RangeMut {
                                start: self.bound_setup(start, min),
                                end: self.bound_setup(end, max),
                                empty: false,
                            };
                        }
                    };
                }
            }
        }
    }

    /// Constructs a double-ended iterator over a sub-range of elements in the map, starting
    /// at min, and ending at max. If min is `Unbounded`, then it will be treated as "negative
    /// infinity", and if max is `Unbounded`, then it will be treated as "positive infinity".
    /// Thus range(Unbounded, Unbounded) will yield the whole collection.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// use stable_bst::TreeMap;
    /// use stable_bst::Bound::{Included, Unbounded};
    ///
    /// let mut map = TreeMap::new();
    /// map.insert(3, "a");
    /// map.insert(5, "b");
    /// map.insert(8, "c");
    /// for (&key, &value) in map.range(Included(&4), Included(&8)) {
    ///     println!("{}: {}", key, value);
    /// }
    /// assert_eq!(Some((&5, &"b")), map.range(Included(&4), Unbounded).next());
    /// ```
    pub fn range<'a, Min: ?Sized, Max: ?Sized>(&'a self,
                                               min: Bound<&Min>,
                                               max: Bound<&Max>)
                                               -> Range<'a, K, V>
        where C: Compare<Min, K> + Compare<Max, K>
    {
        Range { range: (unsafe { &mut *(self as *const Self as *mut Self) }).range_mut(min, max) }
    }
}

pub struct RangeMut<'a, K: 'a, V: 'a> {
    start: IterMut<'a, K, V, Forward>,
    end: IterMut<'a, K, V, Backward>,
    empty: bool,
}

pub struct Range<'a, K: 'a, V: 'a> {
    range: RangeMut<'a, K, V>,
}

pub trait Direction {
    fn forward() -> bool;
}

pub enum Forward {}

impl Direction for Forward {
    fn forward() -> bool {
        true
    }
}

pub enum Backward {}

impl Direction for Backward {
    fn forward() -> bool {
        false
    }
}

/// Lazy forward iterator over a map
pub struct Iter<'a, K: 'a, V: 'a, D: Direction> {
    iter_mut: IterMut<'a, K, V, D>,
}

/// Lazy forward iterator over a map that allows for the mutation of
/// the values.
pub struct IterMut<'a, K: 'a, V: 'a, D: Direction> {
    stack: Vec<&'a mut TreeNode<K, V>>,
    // Unfortunately, we require some unsafe-ness to get around the
    // fact that we would be storing a reference *into* one of the
    // nodes in the stack.
    //
    // As far as the compiler knows, this would let us invalidate the
    // reference by assigning a new value to this node's position in
    // its parent, which would cause this current one to be
    // deallocated so this reference would be invalid. (i.e. the
    // compilers complaints are 100% correct.)
    //
    // However, as far as you humans reading this code know (or are
    // about to know, if you haven't read far enough down yet), we are
    // only reading from the TreeNode.{left,right} fields. the only
    // thing that is ever mutated is the .value field (although any
    // actual mutation that happens is done externally, by the
    // iterator consumer). So, don't be so concerned, rustc, we've got
    // it under control.
    //
    // (This field can legitimately be null.)
    node: *mut TreeNode<K, V>,
    direction: PhantomData<D>,
}

/// TreeMap keys iterator.
pub struct Keys<'a, K: 'a, V: 'a>(iter::Map<Iter<'a, K, V, Forward>, fn((&'a K, &'a V)) -> &'a K>);

/// TreeMap values iterator.
pub struct Values<'a, K: 'a, V: 'a>(iter::Map<Iter<'a, K, V, Forward>,
                                              fn((&'a K, &'a V)) -> &'a V>);

impl<'a, K, V, D: Direction> IterMut<'a, K, V, D> {
    #[inline(always)]
    fn next_(&mut self) -> Option<(&'a K, &'a mut V)> {
        self.normalize();
        self.next_node()
    }

    fn normalize(&mut self) {
        while !self.node.is_null() {
            let node = unsafe { &mut *self.node };
            {
                let next_node = if D::forward() {
                    &mut node.left
                } else {
                    &mut node.right
                };
                self.node = deref_mut(next_node);
            }
            self.stack.push(node);
        }
    }

    fn next_node(&mut self) -> Option<(&'a K, &'a mut V)> {
        return self.stack.pop().map(|node| {
            let next_node = if D::forward() {
                &mut node.right
            } else {
                &mut node.left
            };
            self.node = deref_mut(next_node);
            (&node.key, &mut node.value)
        });
    }

    #[inline]
    fn traverse_before(&mut self) {
        let node = unsafe { &mut *self.node };
        self.node = deref_mut(&mut node.left);
        if D::forward() {
            self.stack.push(node);
        }
    }

    #[inline]
    fn traverse_after(&mut self) {
        let node = unsafe { &mut *self.node };
        self.node = deref_mut(&mut node.right);
        if !D::forward() {
            self.stack.push(node);
        }
    }

    #[inline]
    fn traverse_complete(&mut self) {
        if !self.node.is_null() {
            unsafe {
                self.stack.push(&mut *self.node);
            }
            self.node = ptr::null_mut();
        }
    }
}

impl<'a, K, V, D: Direction> Iterator for IterMut<'a, K, V, D> {
    type Item = (&'a K, &'a mut V);
    /// Advances the iterator to the next node (in order) and return a
    /// tuple with a reference to the key and value. If there are no
    /// more nodes, return `None`.
    fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
        self.next_()
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, None)
    }
}

impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
    type Item = (&'a K, &'a mut V);
    fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
        if self.empty {
            return None;
        }
        self.start.normalize();
        self.end.normalize();
        self.empty = match (self.start.stack.last(), self.end.stack.last()) {
            (None, _) | (_, None) => true,
            (Some(n1), Some(n2)) => *n1 as *const TreeNode<K, V> == *n2 as *const TreeNode<K, V>,
        };
        self.start.next_node()
    }
}

impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
    fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
        if self.empty {
            return None;
        }
        self.start.normalize();
        self.end.normalize();
        self.empty = match (self.start.stack.last(), self.end.stack.last()) {
            (None, _) | (_, None) => true,
            (Some(n1), Some(n2)) => *n1 as *const TreeNode<K, V> == *n2 as *const TreeNode<K, V>,
        };
        self.end.next_node()
    }
}

impl<'a, K, V> Iterator for Range<'a, K, V> {
    type Item = (&'a K, &'a V);
    fn next(&mut self) -> Option<(&'a K, &'a V)> {
        self.range.next().map(|o| match o {
            (k, v) => (k, &*v),
        })
    }
}

impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> {
    fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
        self.range.next_back().map(|o| match o {
            (k, v) => (k, &*v),
        })
    }
}

impl<'a, K, V, D: Direction> Iterator for Iter<'a, K, V, D> {
    type Item = (&'a K, &'a V);
    fn next(&mut self) -> Option<(&'a K, &'a V)> {
        self.iter_mut.next_().map(|o| match o {
            (k, v) => (k, &*v),
        })
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, None)
    }
}

fn deref_mut<K, V>(x: &mut Option<Box<TreeNode<K, V>>>) -> *mut TreeNode<K, V> {
    match *x {
        Some(ref mut n) => &mut **n,
        None => ptr::null_mut(),
    }
}

/// Lazy forward iterator over a map that consumes the map while iterating
pub struct IntoIter<K, V> {
    stack: Vec<TreeNode<K, V>>,
    remaining: usize,
}

impl<K, V> Iterator for IntoIter<K, V> {
    type Item = (K, V);
    #[inline]
    fn next(&mut self) -> Option<(K, V)> {
        while !self.stack.is_empty() {
            let TreeNode { key, value, left, right, level } = self.stack.pop().unwrap();

            match left {
                Some(b_left) => {
                    let n = TreeNode {
                        key: key,
                        value: value,
                        left: None,
                        right: right,
                        level: level,
                    };
                    self.stack.push(n);
                    self.stack.push(*b_left);
                }
                None => {
                    match right {
                        Some(b_right) => self.stack.push(*b_right),
                        None => (),
                    }
                    self.remaining -= 1;
                    return Some((key, value));
                }
            }
        }
        None
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.remaining, Some(self.remaining))
    }
}

impl<'a, K, V> Iterator for Keys<'a, K, V> {
    type Item = &'a K;
    #[inline]
    fn next(&mut self) -> Option<&'a K> {
        self.0.next()
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl<'a, K, V> Iterator for Values<'a, K, V> {
    type Item = &'a V;
    #[inline]
    fn next(&mut self) -> Option<&'a V> {
        self.0.next()
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}


// Nodes keep track of their level in the tree, starting at 1 in the
// leaves and with a red child sharing the level of the parent.
#[derive(Clone)]
struct TreeNode<K, V> {
    key: K,
    value: V,
    left: Option<Box<TreeNode<K, V>>>,
    right: Option<Box<TreeNode<K, V>>>,
    level: usize,
}

impl<K, V> TreeNode<K, V> {
    /// Creates a new tree node.
    #[inline]
    pub fn new(key: K, value: V) -> TreeNode<K, V> {
        TreeNode {
            key: key,
            value: value,
            left: None,
            right: None,
            level: 1,
        }
    }
}

// Remove left horizontal link by rotating right
fn skew<K, V>(node: &mut Box<TreeNode<K, V>>) {
    if node.left.as_ref().map_or(false, |x| x.level == node.level) {
        let mut save = node.left.take().unwrap();
        swap(&mut node.left, &mut save.right); // save.right now None
        swap(node, &mut save);
        node.right = Some(save);
    }
}

// Remove dual horizontal link by rotating left and increasing level of
// the parent
fn split<K, V>(node: &mut Box<TreeNode<K, V>>) {
    if node.right.as_ref().map_or(false,
                                  |x| x.right.as_ref().map_or(false, |y| y.level == node.level)) {
        let mut save = node.right.take().unwrap();
        swap(&mut node.right, &mut save.left); // save.left now None
        save.level += 1;
        swap(node, &mut save);
        node.left = Some(save);
    }
}

// Next 2 functions have the same convention: comparator gets
// at input current key and returns search_key cmp cur_key
// (i.e. search_key.cmp(&cur_key))
fn tree_find_with<K, V, F>(node: &Option<Box<TreeNode<K, V>>>, mut f: F) -> Option<&V>
    where F: FnMut(&K) -> Ordering
{
    let mut current = node;
    loop {
        match *current {
            Some(ref r) => {
                match f(&r.key) {
                    Less => current = &r.left,
                    Greater => current = &r.right,
                    Equal => return Some(&r.value),
                }
            }
            None => return None,
        }
    }
}

// See comments above tree_find_with
fn tree_find_with_mut<K, V, F>(node: &mut Option<Box<TreeNode<K, V>>>, mut f: F) -> Option<&mut V>
    where F: FnMut(&K) -> Ordering
{

    let mut current = node;
    loop {
        let temp = current; // hack to appease borrowck
        match *temp {
            Some(ref mut r) => {
                match f(&r.key) {
                    Less => current = &mut r.left,
                    Greater => current = &mut r.right,
                    Equal => return Some(&mut r.value),
                }
            }
            None => return None,
        }
    }
}

fn insert<K, V, C>(node: &mut Option<Box<TreeNode<K, V>>>, key: K, value: V, cmp: &C) -> Option<V>
    where C: Compare<K>
{

    match *node {
        Some(ref mut save) => {
            match cmp.compare(&key, &save.key) {
                Less => {
                    let inserted = insert(&mut save.left, key, value, cmp);
                    skew(save);
                    split(save);
                    inserted
                }
                Greater => {
                    let inserted = insert(&mut save.right, key, value, cmp);
                    skew(save);
                    split(save);
                    inserted
                }
                Equal => Some(replace(&mut save.value, value)),
            }
        }
        None => {
            *node = Some(Box::new(TreeNode::new(key, value)));
            None
        }
    }
}

fn remove<K, V, C, Q: ?Sized>(node: &mut Option<Box<TreeNode<K, V>>>, key: &Q, cmp: &C) -> Option<V>
    where C: Compare<Q, K>
{

    fn heir_swap<K, V>(node: &mut Box<TreeNode<K, V>>, child: &mut Option<Box<TreeNode<K, V>>>) {
        // *could* be done without recursion, but it won't borrow check
        for x in child.iter_mut() {
            if x.right.is_some() {
                heir_swap(node, &mut x.right);
            } else {
                swap(&mut node.key, &mut x.key);
                swap(&mut node.value, &mut x.value);
            }
        }
    }

    match *node {
        None => {
            return None; // bottom of tree
        }
        Some(ref mut save) => {
            let (ret, rebalance) = match cmp.compare(key, &save.key) {
                Less => (remove(&mut save.left, key, cmp), true),
                Greater => (remove(&mut save.right, key, cmp), true),
                Equal => {
                    if save.left.is_some() {
                        if save.right.is_some() {
                            let mut left = save.left.take().unwrap();
                            if left.right.is_some() {
                                heir_swap(save, &mut left.right);
                            } else {
                                swap(&mut save.key, &mut left.key);
                                swap(&mut save.value, &mut left.value);
                            }
                            save.left = Some(left);
                            (remove(&mut save.left, key, cmp), true)
                        } else {
                            let new = save.left.take().unwrap();
                            let TreeNode { value, .. } = *replace(save, new);
                            *save = save.left.take().unwrap();
                            (Some(value), true)
                        }
                    } else if save.right.is_some() {
                        let new = save.right.take().unwrap();
                        let TreeNode { value, .. } = *replace(save, new);
                        (Some(value), true)
                    } else {
                        (None, false)
                    }
                }
            };

            if rebalance {
                let left_level = save.left.as_ref().map_or(0, |x| x.level);
                let right_level = save.right.as_ref().map_or(0, |x| x.level);

                // re-balance, if necessary
                if left_level < save.level - 1 || right_level < save.level - 1 {
                    save.level -= 1;

                    if right_level > save.level {
                        let save_level = save.level;
                        for x in save.right.iter_mut() {
                            x.level = save_level
                        }
                    }

                    skew(save);

                    for right in save.right.iter_mut() {
                        skew(right);
                        for x in right.right.iter_mut() {
                            skew(x)
                        }
                    }

                    split(save);
                    for x in save.right.iter_mut() {
                        split(x)
                    }
                }

                return ret;
            }
        }
    }
    return match node.take() {
        Some(b) => {
            let TreeNode { value, .. } = *b;
            Some(value)
        }
        None => panic!(),
    };
}

impl<K, V, C> iter::FromIterator<(K, V)> for TreeMap<K, V, C>
    where C: Compare<K> + Default
{
    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> TreeMap<K, V, C> {
        let mut map: TreeMap<K, V, C> = Default::default();
        map.extend(iter);
        map
    }
}

impl<K, V, C> Extend<(K, V)> for TreeMap<K, V, C>
    where C: Compare<K>
{
    #[inline]
    fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
        for (k, v) in iter {
            self.insert(k, v);
        }
    }
}

impl<K: Hash, V: Hash, C> Hash for TreeMap<K, V, C>
    where C: Compare<K>
{
    fn hash<H: Hasher>(&self, state: &mut H) {
        for elt in self.iter() {
            elt.hash(state);
        }
    }
}

impl<'a, K, V, C> IntoIterator for &'a TreeMap<K, V, C>
    where C: Compare<K>
{
    type Item = (&'a K, &'a V);
    type IntoIter = Iter<'a, K, V, Forward>;
    fn into_iter(self) -> Iter<'a, K, V, Forward> {
        self.iter()
    }
}

impl<'a, K, V, C> IntoIterator for &'a mut TreeMap<K, V, C>
    where C: Compare<K>
{
    type Item = (&'a K, &'a mut V);
    type IntoIter = IterMut<'a, K, V, Forward>;
    fn into_iter(self) -> IterMut<'a, K, V, Forward> {
        self.iter_mut()
    }
}

impl<K, V, C> IntoIterator for TreeMap<K, V, C>
    where C: Compare<K>
{
    type Item = (K, V);
    type IntoIter = IntoIter<K, V>;
    fn into_iter(self) -> IntoIter<K, V> {
        self.into_iter()
    }
}

#[cfg(feature="ordered_iter")]
impl<'a, K, V> ::ordered_iter::OrderedMapIterator for Iter<'a, K, V, Forward> {
    type Key = &'a K;
    type Val = &'a V;
}

#[cfg(test)]
mod test_treemap {
    use rand::{self, Rng};

    use super::{TreeMap, TreeNode, Range, RangeMut};
    use super::super::Bound;

    #[test]
    fn find_empty() {
        let m: TreeMap<i32, i32> = TreeMap::new();
        assert!(m.get(&5) == None);
    }

    #[test]
    fn find_not_found() {
        let mut m = TreeMap::new();
        assert!(m.insert(1, 2).is_none());
        assert!(m.insert(5, 3).is_none());
        assert!(m.insert(9, 3).is_none());
        assert_eq!(m.get(&2), None);
    }

    #[test]
    fn find_with_empty() {
        let m: TreeMap<&'static str, i32> = TreeMap::new();
        assert!(m.find_with(|&k| "test".cmp(k)) == None);
    }

    #[test]
    fn find_with_not_found() {
        let mut m = TreeMap::new();
        assert!(m.insert("test1", 2).is_none());
        assert!(m.insert("test2", 3).is_none());
        assert!(m.insert("test3", 3).is_none());
        assert_eq!(m.find_with(|&k| "test4".cmp(k)), None);
    }

    #[test]
    fn find_with_found() {
        let mut m = TreeMap::new();
        assert!(m.insert("test1", 2).is_none());
        assert!(m.insert("test2", 3).is_none());
        assert!(m.insert("test3", 4).is_none());
        assert_eq!(m.find_with(|&k| "test2".cmp(k)), Some(&3));
    }

    #[test]
    fn test_find_mut() {
        let mut m = TreeMap::new();
        assert!(m.insert(1, 12).is_none());
        assert!(m.insert(2, 8).is_none());
        assert!(m.insert(5, 14).is_none());
        let new = 100;
        match m.get_mut(&5) {
            None => panic!(),
            Some(x) => *x = new,
        }
        assert_eq!(m.get(&5), Some(&new));
    }

    #[test]
    fn test_find_with_mut() {
        let mut m = TreeMap::new();
        assert!(m.insert("t1", 12).is_none());
        assert!(m.insert("t2", 8).is_none());
        assert!(m.insert("t5", 14).is_none());
        let new = 100;

        match m.find_with_mut(|&k| "t5".cmp(k)) {
            None => panic!(),
            Some(x) => *x = new,
        }
        assert_eq!(m.find_with(|&k| "t5".cmp(k)), Some(&new));
    }

    #[test]
    fn insert_replace() {
        let mut m = TreeMap::new();
        assert!(m.insert(5, 2).is_none());
        assert!(m.insert(2, 9).is_none());
        assert!(!m.insert(2, 11).is_none());
        assert_eq!(m.get(&2).unwrap(), &11);
    }

    #[test]
    fn test_clear() {
        let mut m = TreeMap::new();
        m.clear();
        assert!(m.insert(5, 11).is_none());
        assert!(m.insert(12, -3).is_none());
        assert!(m.insert(19, 2).is_none());
        m.clear();
        assert!(m.get(&5).is_none());
        assert!(m.get(&12).is_none());
        assert!(m.get(&19).is_none());
        assert!(m.is_empty());
    }

    #[test]
    fn u8_map() {
        let mut m = TreeMap::new();

        let k1 = "foo".as_bytes();
        let k2 = "bar".as_bytes();
        let v1 = "baz".as_bytes();
        let v2 = "foobar".as_bytes();

        m.insert(k1.clone(), v1.clone());
        m.insert(k2.clone(), v2.clone());

        assert_eq!(m.get(&k2), Some(&v2));
        assert_eq!(m.get(&k1), Some(&v1));
    }

    fn check_equal<K: PartialEq + Ord, V: PartialEq>(ctrl: &[(K, V)], map: &TreeMap<K, V>) {
        assert_eq!(ctrl.is_empty(), map.is_empty());
        for x in ctrl.iter() {
            let &(ref k, ref v) = x;
            assert!(map.get(k).unwrap() == v)
        }
        for (map_k, map_v) in map.iter() {
            let mut found = false;
            for x in ctrl.iter() {
                let &(ref ctrl_k, ref ctrl_v) = x;
                if *map_k == *ctrl_k {
                    assert!(*map_v == *ctrl_v);
                    found = true;
                    break;
                }
            }
            assert!(found);
        }
    }

    fn check_left<K: Ord, V>(node: &Option<Box<TreeNode<K, V>>>, parent: &Box<TreeNode<K, V>>) {
        match *node {
            Some(ref r) => {
                assert_eq!(r.key.cmp(&parent.key), ::std::cmp::Ordering::Less);
                assert!(r.level == parent.level - 1); // left is black
                check_left(&r.left, r);
                check_right(&r.right, r, false);
            }
            None => assert!(parent.level == 1), // parent is leaf
        }
    }

    fn check_right<K: Ord, V>(node: &Option<Box<TreeNode<K, V>>>,
                              parent: &Box<TreeNode<K, V>>,
                              parent_red: bool) {
        match *node {
            Some(ref r) => {
                assert_eq!(r.key.cmp(&parent.key), ::std::cmp::Ordering::Greater);
                let red = r.level == parent.level;
                if parent_red {
                    assert!(!red)
                } // no dual horizontal links
            // Right red or black
                assert!(red || r.level == parent.level - 1);
                check_left(&r.left, r);
                check_right(&r.right, r, red);
            }
            None => assert!(parent.level == 1), // parent is leaf
        }
    }

    fn check_structure<K: Ord, V>(map: &TreeMap<K, V>) {
        match map.root {
            Some(ref r) => {
                check_left(&r.left, r);
                check_right(&r.right, r, false);
            }
            None => (),
        }
    }

    #[test]
    fn test_rand_int() {
        let mut map: TreeMap<i32, i32> = TreeMap::new();
        let mut ctrl = vec![];

        check_equal(&ctrl, &map);
        assert!(map.get(&5).is_none());

        let seed: &[_] = &[42];
        let mut rng: rand::IsaacRng = rand::SeedableRng::from_seed(seed);

        for _ in 0..3 {
            for _ in 0..90 {
                let k = rng.gen();
                let v = rng.gen();
                if !ctrl.iter().any(|x| x == &(k, v)) {
                    assert!(map.insert(k, v).is_none());
                    ctrl.push((k, v));
                    check_structure(&map);
                    check_equal(&ctrl, &map);
                }
            }

            for _ in 0..30 {
                let r = rng.gen_range(0, ctrl.len());
                let (key, _) = ctrl.remove(r);
                assert!(map.remove(&key).is_some());
                check_structure(&map);
                check_equal(&ctrl, &map);
            }
        }
    }

    #[test]
    fn test_len() {
        let mut m = TreeMap::new();
        assert!(m.insert(3, 6).is_none());
        assert_eq!(m.len(), 1);
        assert!(m.insert(0, 0).is_none());
        assert_eq!(m.len(), 2);
        assert!(m.insert(4, 8).is_none());
        assert_eq!(m.len(), 3);
        assert!(m.remove(&3).is_some());
        assert_eq!(m.len(), 2);
        assert!(!m.remove(&5).is_some());
        assert_eq!(m.len(), 2);
        assert!(m.insert(2, 4).is_none());
        assert_eq!(m.len(), 3);
        assert!(m.insert(1, 2).is_none());
        assert_eq!(m.len(), 4);
    }

    #[test]
    fn test_iterator() {
        let mut m = TreeMap::new();

        assert!(m.insert(3, 6).is_none());
        assert!(m.insert(0, 0).is_none());
        assert!(m.insert(4, 8).is_none());
        assert!(m.insert(2, 4).is_none());
        assert!(m.insert(1, 2).is_none());

        let mut n = 0;
        for (k, v) in m.iter() {
            assert_eq!(*k, n);
            assert_eq!(*v, n * 2);
            n += 1;
        }
        assert_eq!(n, 5);
    }

    #[test]
    fn test_interval_iteration() {
        let mut m = TreeMap::new();
        for i in 1..100 {
            assert!(m.insert(i * 2, i * 4).is_none());
        }

        for i in 1..198 {
            let mut lb_it = m.range(Bound::Included(&i), Bound::Unbounded);
            let (&k, &v) = lb_it.next().unwrap();
            let lb = i + i % 2;
            assert_eq!(lb, k);
            assert_eq!(lb * 2, v);

            let mut ub_it = m.range(Bound::Excluded(&i), Bound::Unbounded);
            let (&k, &v) = ub_it.next().unwrap();
            let ub = i + 2 - i % 2;
            assert_eq!(ub, k);
            assert_eq!(ub * 2, v);
        }
        let mut end_it = m.range(Bound::Included(&199), Bound::Unbounded);
        assert_eq!(end_it.next(), None);
    }

    #[test]
    fn test_mut_iter() {
        let mut m = TreeMap::new();
        for i in 0..10 {
            assert!(m.insert(i, 100 * i).is_none());
        }

        for (i, (&k, v)) in m.iter_mut().enumerate() {
            *v += k * 10 + i; // 000 + 00 + 0, 100 + 10 + 1, ...
        }

        for (&k, &v) in m.iter() {
            assert_eq!(v, 111 * k);
        }
    }

    #[test]
    fn test_mut_interval_iter() {
        let mut m_lower = TreeMap::new();
        let mut m_upper = TreeMap::new();
        for i in 1..100 {
            assert!(m_lower.insert(i * 2, i * 4).is_none());
            assert!(m_upper.insert(i * 2, i * 4).is_none());
        }

        for i in 1..199 {
            let mut lb_it = m_lower.range_mut(Bound::Included(&i), Bound::Unbounded);
            let (&k, v) = lb_it.next().unwrap();
            let lb = i + i % 2;
            assert_eq!(lb, k);
            *v -= k;
        }
        for i in 0..198 {
            let mut ub_it = m_upper.range_mut(Bound::Excluded(&i), Bound::Unbounded);
            let (&k, v) = ub_it.next().unwrap();
            let ub = i + 2 - i % 2;
            assert_eq!(ub, k);
            *v -= k;
        }

        assert!(m_lower.range_mut(Bound::Included(&199), Bound::Unbounded).next().is_none());

        assert!(m_upper.range_mut(Bound::Excluded(&199), Bound::Unbounded).next().is_none());

        assert!(m_lower.iter().all(|(_, &x)| x == 0));
        assert!(m_upper.iter().all(|(_, &x)| x == 0));
    }

    fn to_vec<K, V: Clone>(range: Range<K, V>) -> Vec<V> {
        range.map(|o| o.1.clone()).collect::<Vec<V>>()
    }

    fn skip<K, V>(mut range: Range<K, V>, mut f: u32, mut b: u32) -> Range<K, V> {
        while f > 0 {
            range.next();
            f -= 1;
        }
        while b > 0 {
            range.next_back();
            b -= 1;
        }
        range
    }

    #[test]
    fn test_range() {
        let mut m = TreeMap::new();
        for i in 0..10 {
            assert!(m.insert(i * 10, 100 * i).is_none());
        }

        assert_eq!(to_vec(m.range(Bound::Unbounded, Bound::Unbounded)),
                   vec![0, 100, 200, 300, 400, 500, 600, 700, 800, 900]);
        assert_eq!(to_vec(m.range(Bound::Included(&50), Bound::Unbounded)),
                   vec![500, 600, 700, 800, 900]);
        assert_eq!(to_vec(m.range(Bound::Excluded(&50), Bound::Unbounded)),
                   vec![600, 700, 800, 900]);

        assert_eq!(to_vec(m.range(Bound::Unbounded, Bound::Included(&70))),
                   vec![0, 100, 200, 300, 400, 500, 600, 700]);
        assert_eq!(to_vec(m.range(Bound::Unbounded, Bound::Excluded(&70))),
                   vec![0, 100, 200, 300, 400, 500, 600]);

        assert_eq!(to_vec(m.range(Bound::Included(&70), Bound::Included(&70))),
                   vec![700]);

        assert_eq!(to_vec(m.range(Bound::Included(&60), Bound::Excluded(&50))),
                   vec![]);
        assert_eq!(to_vec(m.range(Bound::Unbounded, Bound::Excluded(&0))),
                   vec![]);

        assert_eq!(m.range(Bound::Unbounded, Bound::Unbounded).next_back(),
                   Some((&90, &900)));
        assert_eq!(m.range(Bound::Unbounded, Bound::Included(&60)).next_back(),
                   Some((&60, &600)));
        assert_eq!(m.range(Bound::Unbounded, Bound::Excluded(&60)).next_back(),
                   Some((&50, &500)));

        assert_eq!(to_vec(skip(m.range(Bound::Unbounded, Bound::Unbounded), 3, 3)),
                   vec![300, 400, 500, 600]);
        assert_eq!(to_vec(skip(m.range(Bound::Unbounded, Bound::Unbounded), 5, 5)),
                   vec![]);
        assert_eq!(to_vec(skip(m.range(Bound::Unbounded, Bound::Unbounded), 3, 7)),
                   vec![]);
        assert_eq!(to_vec(skip(m.range(Bound::Unbounded, Bound::Unbounded), 7, 3)),
                   vec![]);
        assert_eq!(to_vec(skip(m.range(Bound::Unbounded, Bound::Unbounded), 8, 3)),
                   vec![]);
    }

    fn to_vec_mut<K, V: Clone>(range: RangeMut<K, V>) -> Vec<V> {
        range.map(|o| o.1.clone()).collect::<Vec<V>>()
    }

    fn skip_mut<K, V>(mut range: RangeMut<K, V>, mut f: u32, mut b: u32) -> RangeMut<K, V> {
        while f > 0 {
            range.next();
            f -= 1;
        }
        while b > 0 {
            range.next_back();
            b -= 1;
        }
        range
    }

    #[test]
    fn test_range_mut() {
        let mut m = TreeMap::new();
        for i in 0..10 {
            assert!(m.insert(i * 10, 20 * i).is_none());
        }
        for i in m.range_mut(Bound::Unbounded, Bound::Unbounded) {
            match i {
                (_, v) => *v *= 5,
            }
        }

        assert_eq!(to_vec_mut(m.range_mut(Bound::Unbounded, Bound::Unbounded)),
                   vec![0, 100, 200, 300, 400, 500, 600, 700, 800, 900]);
        assert_eq!(to_vec_mut(m.range_mut(Bound::Included(&50), Bound::Unbounded)),
                   vec![500, 600, 700, 800, 900]);
        assert_eq!(to_vec_mut(m.range_mut(Bound::Excluded(&50), Bound::Unbounded)),
                   vec![600, 700, 800, 900]);

        assert_eq!(to_vec_mut(m.range_mut(Bound::Unbounded, Bound::Included(&70))),
                   vec![0, 100, 200, 300, 400, 500, 600, 700]);
        assert_eq!(to_vec_mut(m.range_mut(Bound::Unbounded, Bound::Excluded(&70))),
                   vec![0, 100, 200, 300, 400, 500, 600]);

        assert_eq!(to_vec_mut(m.range_mut(Bound::Included(&70), Bound::Included(&70))),
                   vec![700]);

        assert_eq!(to_vec_mut(m.range_mut(Bound::Included(&60), Bound::Excluded(&50))),
                   vec![]);
        assert_eq!(to_vec_mut(m.range_mut(Bound::Unbounded, Bound::Excluded(&0))),
                   vec![]);

        assert_eq!(m.range_mut(Bound::Unbounded, Bound::Unbounded).next_back(),
                   Some((&90, &mut 900)));
        assert_eq!(m.range_mut(Bound::Unbounded, Bound::Included(&60)).next_back(),
                   Some((&60, &mut 600)));
        assert_eq!(m.range_mut(Bound::Unbounded, Bound::Excluded(&60)).next_back(),
                   Some((&50, &mut 500)));

        assert_eq!(to_vec_mut(skip_mut(m.range_mut(Bound::Unbounded, Bound::Unbounded), 3, 3)),
                   vec![300, 400, 500, 600]);
        assert_eq!(to_vec_mut(skip_mut(m.range_mut(Bound::Unbounded, Bound::Unbounded), 5, 5)),
                   vec![]);
        assert_eq!(to_vec_mut(skip_mut(m.range_mut(Bound::Unbounded, Bound::Unbounded), 3, 7)),
                   vec![]);
        assert_eq!(to_vec_mut(skip_mut(m.range_mut(Bound::Unbounded, Bound::Unbounded), 7, 3)),
                   vec![]);
        assert_eq!(to_vec_mut(skip_mut(m.range_mut(Bound::Unbounded, Bound::Unbounded), 8, 3)),
                   vec![]);
    }

    #[test]
    fn test_keys() {
        let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
        let map: TreeMap<i32, char> = vec.into_iter().collect();
        let keys: Vec<i32> = map.keys().map(|&k| k).collect();
        assert_eq!(keys, vec![1, 2, 3]);
    }

    #[test]
    fn test_values() {
        let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')];
        let map = vec.into_iter().collect::<TreeMap<i32, char>>();
        let values = map.values().map(|&v| v).collect::<Vec<char>>();
        assert_eq!(values, vec!['a', 'b', 'c']);
    }

    #[test]
    fn test_eq() {
        let mut a = TreeMap::new();
        let mut b = TreeMap::new();

        assert!(a == b);
        assert!(a.insert(0, 5).is_none());
        assert!(a != b);
        assert!(b.insert(0, 4).is_none());
        assert!(a != b);
        assert!(a.insert(5, 19).is_none());
        assert!(a != b);
        assert!(!b.insert(0, 5).is_none());
        assert!(a != b);
        assert!(b.insert(5, 19).is_none());
        assert!(a == b);
    }

    #[test]
    fn test_lt() {
        let mut a = TreeMap::new();
        let mut b = TreeMap::new();

        assert!(!(a < b) && !(b < a));
        assert!(b.insert(0, 5).is_none());
        assert!(a < b);
        assert!(a.insert(0, 7).is_none());
        assert!(!(a < b) && b < a);
        assert!(b.insert(-2, 0).is_none());
        assert!(b < a);
        assert!(a.insert(-5, 2).is_none());
        assert!(a < b);
        assert!(a.insert(6, 2).is_none());
        assert!(a < b && !(b < a));
    }

    #[test]
    fn test_ord() {
        let mut a = TreeMap::new();
        let mut b = TreeMap::new();

        assert!(a <= b && a >= b);
        assert!(a.insert(1, 1).is_none());
        assert!(a > b && a >= b);
        assert!(b < a && b <= a);
        assert!(b.insert(2, 2).is_none());
        assert!(b > a && b >= a);
        assert!(a < b && a <= b);
    }

    #[test]
    fn test_debug() {
        let mut map = TreeMap::new();
        let empty: TreeMap<i32, i32> = TreeMap::new();

        map.insert(1, 2);
        map.insert(3, 4);

        assert_eq!(format!("{:?}", map), "{1: 2, 3: 4}");
        assert_eq!(format!("{:?}", empty), "{}");
    }

    #[test]
    fn test_lazy_iterator() {
        let mut m = TreeMap::new();
        let (x1, y1) = (2, 5);
        let (x2, y2) = (9, 12);
        let (x3, y3) = (20, -3);
        let (x4, y4) = (29, 5);
        let (x5, y5) = (103, 3);

        assert!(m.insert(x1, y1).is_none());
        assert!(m.insert(x2, y2).is_none());
        assert!(m.insert(x3, y3).is_none());
        assert!(m.insert(x4, y4).is_none());
        assert!(m.insert(x5, y5).is_none());

        let m = m;
        let mut a = m.iter();

        assert_eq!(a.next().unwrap(), (&x1, &y1));
        assert_eq!(a.next().unwrap(), (&x2, &y2));
        assert_eq!(a.next().unwrap(), (&x3, &y3));
        assert_eq!(a.next().unwrap(), (&x4, &y4));
        assert_eq!(a.next().unwrap(), (&x5, &y5));

        assert!(a.next().is_none());

        let mut b = m.iter();

        let expected = [(&x1, &y1), (&x2, &y2), (&x3, &y3), (&x4, &y4), (&x5, &y5)];
        let mut i = 0;

        for x in b.by_ref() {
            assert_eq!(expected[i], x);
            i += 1;

            if i == 2 {
                break;
            }
        }

        for x in b {
            assert_eq!(expected[i], x);
            i += 1;
        }
    }

    #[test]
    fn test_from_iter() {
        let xs = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)];

        let map: TreeMap<i32, i32> = xs.iter().map(|&x| x).collect();

        for &(k, v) in xs.iter() {
            assert_eq!(map.get(&k), Some(&v));
        }
    }

    #[test]
    fn test_index() {
        let mut map: TreeMap<i32, i32> = TreeMap::new();

        map.insert(1, 2);
        map.insert(2, 1);
        map.insert(3, 4);

        assert_eq!(map[&2], 1);
    }

    #[test]
    #[should_panic]
    fn test_index_nonexistent() {
        let mut map: TreeMap<i32, i32> = TreeMap::new();

        map.insert(1, 2);
        map.insert(2, 1);
        map.insert(3, 4);

        map[&4];
    }

    #[test]
    fn test_swap() {
        let mut m = TreeMap::new();
        assert_eq!(m.insert(1, 2), None);
        assert_eq!(m.insert(1, 3), Some(2));
        assert_eq!(m.insert(1, 4), Some(3));
    }

    #[test]
    fn test_pop() {
        let mut m = TreeMap::new();
        m.insert(1, 2);
        assert_eq!(m.remove(&1), Some(2));
        assert_eq!(m.remove(&1), None);
    }

    #[test]
    fn test_comparator_iterator() {
        use compare::{Compare, natural};

        let mut m = TreeMap::with_comparator(natural().rev());

        assert!(m.insert(3, 6).is_none());
        assert!(m.insert(0, 0).is_none());
        assert!(m.insert(4, 8).is_none());
        assert!(m.insert(2, 4).is_none());
        assert!(m.insert(1, 2).is_none());

        let mut n = 5;
        for (k, v) in m.iter() {
            n -= 1;
            assert_eq!(*k, n);
            assert_eq!(*v, n * 2);
        }
        assert_eq!(n, 0);
    }

    #[test]
    fn test_comparator_borrowed() {
        use compare::{Compare, natural};

        let mut m = TreeMap::with_comparator(natural().borrowing());

        assert!(m.insert("a".to_string(), 1).is_none());

        assert!(m.contains_key("a"));
        assert!(m.contains_key(&"a"));
        assert!(m.contains_key(&"a".to_string()));

        assert_eq!(m.get("a"), Some(&1));
        assert_eq!(m.get(&"a"), Some(&1));
        assert_eq!(m.get(&"a".to_string()), Some(&1));

        m["a"] = 2;

        assert_eq!(m["a"], 2);
        assert_eq!(m[&"a".to_string()], 2);

        m[&"a".to_string()] = 3;

        assert_eq!(m.remove("a"), Some(3));
        assert!(m.remove(&"a").is_none());
        assert!(m.remove(&"a".to_string()).is_none());
    }
}

#[cfg(all(test, feature="bench"))]
mod bench {
    use rand::{weak_rng, Rng};
    use test::{Bencher, black_box};

    use super::TreeMap;

    map_insert_rand_bench!{insert_rand_100,    100,    TreeMap}
    map_insert_rand_bench!{insert_rand_10_000, 10_000, TreeMap}

    map_insert_seq_bench!{insert_seq_100,    100,    TreeMap}
    map_insert_seq_bench!{insert_seq_10_000, 10_000, TreeMap}

    map_find_rand_bench!{find_rand_100,    100,    TreeMap}
    map_find_rand_bench!{find_rand_10_000, 10_000, TreeMap}

    map_find_seq_bench!{find_seq_100,    100,    TreeMap}
    map_find_seq_bench!{find_seq_10_000, 10_000, TreeMap}

    fn bench_iter(b: &mut Bencher, size: usize) {
        let mut map = TreeMap::<u32, u32>::new();
        let mut rng = weak_rng();

        for _ in 0..size {
            map.insert(rng.gen(), rng.gen());
        }

        b.iter(|| {
            for entry in map.iter() {
                black_box(entry);
            }
        });
    }

    #[bench]
    pub fn iter_20(b: &mut Bencher) {
        bench_iter(b, 20);
    }

    #[bench]
    pub fn iter_1000(b: &mut Bencher) {
        bench_iter(b, 1000);
    }

    #[bench]
    pub fn iter_100000(b: &mut Bencher) {
        bench_iter(b, 100000);
    }
}