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
use std::collections::HashMap;
use std::hash::{BuildHasher, Hash};
use std::iter::FusedIterator;
use std::{any::Any, fmt::Debug, ops::Index};
use std::{collections::hash_map::RandomState, marker::PhantomData};

use crate::entry;
use crate::typedkey::{Key, TypedKey, TypedKeyRef};
use crate::typedvalue::TypedMapValue;

/// A trait that a key stored in the [`TypedMap`] must be implement.
/// Marker may be used to implement multiple key-value type mappings.
pub trait TypedMapKey<Marker = ()>: Eq + Hash {
    /// Type of a value associated with the Key type
    type Value: 'static;
}

const INVALID_KEY: &str = "Broken TypedMap: invalid key type";
const INVALID_VALUE: &str = "Broken TypedMap: invalid value type";

/// A map that can store keys of any type that implements [`TypedMapKey`] and values
/// of type defined by [`TypedMapKey::Value`]. One can use Marker to define multiple
/// "key-value" type mappings. Under the hood the [`std::collections::HashMap`] is used.
///
/// # Examples
/// ```
/// use typedmap::TypedMap;
/// use typedmap::TypedMapKey;
///
/// struct Configs;
/// struct Services;
///
/// #[derive(Hash, PartialEq, Eq)]
/// struct ServiceA(usize);
///
/// // Implement key-value mapping for Configs marker
/// impl TypedMapKey<Configs> for ServiceA {
///     type Value = usize;
/// }
///
/// // Implement key-value mapping for Services marker
/// impl TypedMapKey<Services> for ServiceA {
///     type Value = &'static str;
/// }
///
/// #[derive(Hash, PartialEq, Eq)]
/// struct ServiceB(&'static str);
///
/// // Implement key-value mapping for Configs marker
/// impl TypedMapKey<Configs> for ServiceB {
///     type Value = Vec<&'static str>;
/// }
///
/// // Implement key-value mapping for Services marker
/// impl TypedMapKey<Services> for ServiceB {
///     type Value = usize;
/// }
///
/// // Implement key-value mapping for default (i.e. ()) marker
/// impl TypedMapKey for ServiceB {
///     type Value = String;
/// }
///
/// let mut configs: TypedMap<Configs> = TypedMap::new();
/// let mut services: TypedMap<Services> = TypedMap::new();
/// let mut default: TypedMap = TypedMap::new();
///
/// configs.insert(ServiceA(0), 1);
/// services.insert(ServiceA(0), "one");
/// // Line below would not compile, because TypeMapKey<Marker=()>
/// // is not implemented for Key.
/// // default.insert(Key(0), 1);
///
/// // Line below would not compile, because SerivceA key defines
/// // type value as usize for Configs marker (not &'static str)
/// // configs.insert(ServiceA(0), "one");
///
/// configs.insert(ServiceB("zero"), vec!["one"]);
/// services.insert(ServiceB("zero"), 32);
/// default.insert(ServiceB("zero"), "one".to_owned());
///
/// assert_eq!(configs[&ServiceB("zero")], vec!["one"]);
/// assert_eq!(services[&ServiceB("zero")], 32);
/// assert_eq!(default[&ServiceB("zero")], "one".to_owned());
///
/// ```
pub struct TypedMap<Marker = (), S = RandomState> {
    state: HashMap<TypedKey, TypedMapValue, S>,
    _phantom: PhantomData<Marker>,
}

impl<Marker> TypedMap<Marker> {
    /// Creates a new TypedMap with specified marker type.
    ///
    /// # Examples:
    /// ```rust
    /// use typedmap::TypedMap;
    ///
    /// struct Configs;
    /// let map = TypedMap::<Configs>::new();
    /// ```
    pub fn new() -> Self {
        TypedMap {
            state: Default::default(),
            _phantom: PhantomData,
        }
    }

    /// Creates a new TypedMap with a specified capacity and specified marker type
    pub fn with_capacity(capacity: usize) -> Self {
        TypedMap {
            state: HashMap::with_capacity(capacity),
            _phantom: PhantomData,
        }
    }
}

impl<Marker, S> TypedMap<Marker, S>
where
    S: BuildHasher,
{
    /// Creates a new TypedMap with specified capacity, hasher and marker type.
    pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self {
        TypedMap {
            state: HashMap::with_capacity_and_hasher(capacity, hash_builder),
            _phantom: PhantomData,
        }
    }

    /// Creates a new TypedMap with specified hasher and marker type.
    pub fn with_hasher(hash_builder: S) -> Self {
        TypedMap {
            state: HashMap::with_hasher(hash_builder),
            _phantom: PhantomData,
        }
    }

    /// Inserts a key-value pair into the map.
    ///
    /// If the map did not have this key present, None is returned.
    ///
    /// If the map did have this key present, the value is updated, and the old value is returned.
    ///
    /// # Examples
    /// ```
    /// use typedmap::TypedMap;
    /// use typedmap::TypedMapKey;
    ///
    /// #[derive(Hash, PartialEq, Eq)]
    /// struct Key(usize);
    ///
    /// impl TypedMapKey for Key {
    ///     type Value = usize;
    /// }
    ///
    /// let mut map: TypedMap = TypedMap::with_capacity(10);
    /// map.insert(Key(3), 4);
    /// assert_eq!(map[&Key(3)], 4);
    /// ```
    pub fn insert<K: 'static + TypedMapKey<Marker>>(
        &mut self,
        key: K,
        value: K::Value,
    ) -> Option<K::Value> {
        let typed_key = TypedKey::from_key(key);
        let value = TypedMapValue::from_value(value);
        let old_value = self.state.insert(typed_key, value);
        old_value.and_then(|v| v.downcast::<K::Value>().ok())
    }

    /// Returns a reference to the value corresponding to the key.
    ///
    /// # Examples
    /// ```
    /// use typedmap::TypedMap;
    /// use typedmap::TypedMapKey;
    ///
    /// #[derive(Hash, PartialEq, Eq)]
    /// struct Key(usize);
    ///
    /// impl TypedMapKey for Key {
    ///     type Value = usize;
    /// }
    ///
    /// let mut map: TypedMap = TypedMap::with_capacity(10);
    /// map.insert(Key(3), 4);
    /// assert_eq!(map.get(&Key(3)), Some(&4));
    /// assert_eq!(map.get(&Key(4)), None);
    /// ```
    pub fn get<K: 'static + TypedMapKey<Marker>>(&self, key: &K) -> Option<&K::Value> {
        let typed_key = TypedKeyRef::from_key_ref(key);
        let value = self.state.get(&typed_key as &dyn Key)?;
        Some(value.downcast_ref::<K::Value>().expect(INVALID_VALUE))
    }

    /// Returns a mutable reference to the value corresponding to the key.
    ///
    /// # Examples
    /// ```
    /// use typedmap::TypedMap;
    /// use typedmap::TypedMapKey;
    ///
    /// #[derive(Hash, PartialEq, Eq)]
    /// struct Key(usize);
    ///
    /// impl TypedMapKey for Key {
    ///     type Value = usize;
    /// }
    ///
    /// let mut map: TypedMap = TypedMap::with_capacity(10);
    /// map.insert(Key(3), 4);
    ///
    /// let key = Key(3);
    /// if let Some(value) = map.get_mut(&key) {
    ///     *value += 1;
    /// }
    /// assert_eq!(map.get(&key), Some(&5));
    /// ```
    pub fn get_mut<K: 'static + TypedMapKey<Marker>>(&mut self, key: &K) -> Option<&mut K::Value> {
        let typed_key = TypedKeyRef::from_key_ref(key);
        let value = self.state.get_mut(&typed_key as &dyn Key)?;
        Some(value.downcast_mut::<K::Value>().expect(INVALID_VALUE))
    }

    /// Returns the key-value pair corresponding to the supplied key.
    ///
    /// # Examples
    /// ```
    /// use typedmap::TypedMap;
    /// use typedmap::TypedMapKey;
    ///
    /// #[derive(Hash, PartialEq, Eq, Debug)]
    /// struct Key(usize);
    ///
    /// impl TypedMapKey for Key {
    ///     type Value = usize;
    /// }
    ///
    /// let mut map: TypedMap = TypedMap::with_capacity(10);
    /// map.insert(Key(3), 4);
    /// assert_eq!(map.get_key_value(&Key(3)), Some((&Key(3), &4)));
    /// assert_eq!(map.get(&Key(4)), None);
    /// ```
    pub fn get_key_value<K: 'static + TypedMapKey<Marker>>(
        &self,
        key: &K,
    ) -> Option<(&K, &K::Value)> {
        let typed_key = TypedKeyRef::from_key_ref(key);
        let (key, value) = self.state.get_key_value(&typed_key as &dyn Key)?;

        Some((
            key.downcast_ref().expect(INVALID_KEY),
            value.downcast_ref().expect(INVALID_VALUE),
        ))
    }

    /// Removes a key from the map, returning the value at the key if the key was previously in the map.
    ///
    /// # Examples
    /// ```
    /// use typedmap::TypedMap;
    /// use typedmap::TypedMapKey;
    ///
    /// #[derive(Hash, PartialEq, Eq)]
    /// struct Key(usize);
    ///
    /// impl TypedMapKey for Key {
    ///     type Value = usize;
    /// }
    ///
    /// let mut map: TypedMap = TypedMap::with_capacity(10);
    /// map.insert(Key(3), 4);
    /// assert_eq!(map.remove(&Key(3)), Some(4));
    /// assert_eq!(map.get(&Key(3)), None);
    /// ```
    pub fn remove<K: 'static + TypedMapKey<Marker>>(&mut self, key: &K) -> Option<K::Value> {
        let typed_key = TypedKeyRef::from_key_ref(key);
        let value = self.state.remove(&typed_key as &dyn Key)?;
        Some(value.downcast::<K::Value>().ok().expect(INVALID_VALUE))
    }

    /// Removes a key from the map, returning the stored key and value if the key was previously in the map.
    ///
    /// # Examples
    /// ```
    /// use typedmap::TypedMap;
    /// use typedmap::TypedMapKey;
    ///
    /// #[derive(Hash, PartialEq, Eq, Debug)]
    /// struct Key(usize);
    ///
    /// impl TypedMapKey for Key {
    ///     type Value = usize;
    /// }
    ///
    /// let mut map: TypedMap = TypedMap::with_capacity(10);
    /// map.insert(Key(3), 4);
    /// assert_eq!(map.remove_entry(&Key(3)), Some((Key(3), 4)));
    /// assert_eq!(map.remove(&Key(3)), None);
    /// ```
    pub fn remove_entry<K: 'static + TypedMapKey<Marker>>(
        &mut self,
        key: &K,
    ) -> Option<(K, K::Value)> {
        let typed_key = TypedKeyRef::from_key_ref(key);
        let value = self.state.remove_entry(&typed_key as &dyn Key);
        value.map(|(k, v)| {
            let k = k.downcast::<K>().ok().expect(INVALID_KEY);
            let v = v.downcast::<K::Value>().ok().expect(INVALID_VALUE);
            (k, v)
        })
    }

    /// Gets the given key's corresponding entry in the map for in-place manipulation.
    ///
    /// # Examples
    /// ```
    /// use typedmap::TypedMap;
    /// use typedmap::TypedMapKey;
    ///
    /// #[derive(Hash, PartialEq, Eq)]
    /// struct Key(char);
    ///
    /// impl TypedMapKey for Key {
    ///     type Value = usize;
    /// }
    ///
    /// let mut letters: TypedMap = TypedMap::new();
    /// for ch in "a short treatise on fungi".chars() {
    ///    let counter = letters.entry(Key(ch)).or_insert(0);
    ///    *counter += 1;
    /// }
    /// assert_eq!(letters.get(&Key('s')), Some(&2));
    /// assert_eq!(letters.get(&Key('t')), Some(&3));
    /// assert_eq!(letters.get(&Key('u')), Some(&1));
    /// assert_eq!(letters.get(&Key('y')), None);
    /// ```
    pub fn entry<K: 'static + TypedMapKey<Marker>>(
        &mut self,
        key: K,
    ) -> entry::Entry<'_, K, Marker> {
        let typed_key = TypedKey::from_key(key);
        entry::map_entry(self.state.entry(typed_key))
    }

    /// Returns true if the map contains a value for the specified key.
    ///
    /// # Examples
    /// ```
    /// use typedmap::TypedMap;
    /// use typedmap::TypedMapKey;
    ///
    /// #[derive(Hash, PartialEq, Eq, Debug)]
    /// struct Key(usize);
    ///
    /// impl TypedMapKey for Key {
    ///     type Value = usize;
    /// }
    ///
    /// let mut map: TypedMap = TypedMap::with_capacity(10);
    /// map.insert(Key(3), 4);
    /// assert!(map.contains_key(&Key(3)));
    /// assert!(!map.contains_key(&Key(4)));
    /// ```
    pub fn contains_key<K: 'static + TypedMapKey<Marker>>(&self, key: &K) -> bool {
        self.get(key).is_some()
    }

    /// Returns the number of elements in the map.
    ///
    /// # Examples
    /// ```
    /// use typedmap::TypedMap;
    /// use typedmap::TypedMapKey;
    ///
    /// #[derive(Hash, PartialEq, Eq, Debug)]
    /// struct Key(usize);
    ///
    /// impl TypedMapKey for Key {
    ///     type Value = usize;
    /// }
    ///
    /// let mut map: TypedMap = TypedMap::with_capacity(10);
    /// assert_eq!(map.len(), 0);
    /// map.insert(Key(3), 4);
    /// assert_eq!(map.len(), 1);
    /// ```
    pub fn len(&self) -> usize {
        self.state.len()
    }

    /// Returns the number of elements the map can hold without reallocating.
    ///
    /// # Examples
    /// ```
    /// use typedmap::TypedMap;
    ///
    /// let map: TypedMap = TypedMap::with_capacity(10);
    /// assert!(map.capacity() >= 10);
    /// ```
    pub fn capacity(&self) -> usize {
        self.state.capacity()
    }

    /// Returns true if the map contains no elements.
    ///
    /// # Examples
    /// ```
    /// use typedmap::TypedMap;
    /// use typedmap::TypedMapKey;
    ///
    /// #[derive(Hash, PartialEq, Eq)]
    /// struct Key(usize);
    ///
    /// impl TypedMapKey for Key {
    ///     type Value = f32;
    /// }
    ///
    /// let mut map: TypedMap = TypedMap::with_capacity(10);
    /// assert!(map.is_empty());
    /// map.insert(Key(3), 4.0);
    /// assert!(!map.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.state.is_empty()
    }

    /// Clears the map, removing all key-value pairs. Keeps the allocated memory for reuse.
    ///
    /// # Examples:
    /// ```
    /// use typedmap::TypedMap;
    /// use typedmap::TypedMapKey;
    ///
    /// #[derive(Hash, PartialEq, Eq)]
    /// struct Key(usize);
    ///
    /// impl TypedMapKey for Key {
    ///     type Value = f32;
    /// }
    ///
    /// let mut map: TypedMap = TypedMap::new();
    /// map.insert(Key(3), 4.0);
    /// map.clear();
    /// assert!(map.is_empty());
    /// ```
    pub fn clear(&mut self) {
        self.state.clear();
    }

    /// Reserves capacity for at least additional more elements to be inserted in the HashMap. The
    /// collection may reserve more space to avoid frequent reallocations.
    ///
    /// # Panics
    /// Panics if the new allocation size overflows `usize`
    ///
    /// # Examples
    /// ```
    /// use typedmap::TypedMap;
    ///
    /// let mut map: TypedMap = TypedMap::new();
    /// map.reserve(1000);
    /// assert!(map.capacity() >= 1000);
    /// ```
    pub fn reserve(&mut self, additional: usize) {
        self.state.reserve(additional)
    }

    /// Shrinks the capacity of the underlying hash map as much as possible.
    ///
    /// # Examples
    /// ```
    /// use typedmap::TypedMap;
    ///
    /// let mut map: TypedMap = TypedMap::with_capacity(1000);
    /// map.shrink_to_fit();
    /// assert!(map.capacity() <= 16);
    /// ```
    pub fn shrink_to_fit(&mut self) {
        self.state.shrink_to_fit();
    }

    /// Returns a reference to the map's BuildHasher.
    pub fn hasher(&self) -> &S {
        self.state.hasher()
    }

    /// An iterator visiting all keys in arbitrary order. The iterator element type is `&'a dyn Any`.
    ///
    /// # Examples
    /// ```
    /// use typedmap::TypedMap;
    /// use typedmap::TypedMapKey;
    ///
    /// #[derive(Hash, PartialEq, Eq, Debug)]
    /// struct Key(usize);
    /// #[derive(Hash, PartialEq, Eq, Debug)]
    /// struct SKey(&'static str);
    ///
    /// impl TypedMapKey for Key {
    ///     type Value = u32;
    /// }
    ///
    /// impl TypedMapKey for SKey {
    ///     type Value = usize;
    /// }
    ///
    /// let mut map: TypedMap = TypedMap::new();
    /// map.insert(Key(3), 3);
    /// map.insert(SKey("four"), 4);
    ///
    /// for key in map.keys() {
    ///     let mut found = false;
    ///     if let Some(Key(number)) = key.downcast_ref::<Key>() {
    ///         assert_eq!(*number, 3);
    ///         found = true;
    ///     }
    ///     if let Some(SKey(a_str)) = key.downcast_ref::<SKey>() {
    ///         assert_eq!(*a_str, "four");
    ///         found = true;
    ///     }
    ///     assert!(found);
    /// }
    /// ```
    pub fn keys(&self) -> Keys<'_> {
        Keys(self.state.keys())
    }

    /// An iterator visiting all values in arbitrary order. The iterator element type is &'a dyn Any.
    ///
    /// # Examples
    /// ```
    /// use typedmap::TypedMap;
    /// use typedmap::TypedMapKey;
    ///
    /// #[derive(Hash, PartialEq, Eq, Debug)]
    /// struct Key(usize);
    /// #[derive(Hash, PartialEq, Eq, Debug)]
    /// struct SKey(&'static str);
    ///
    /// impl TypedMapKey for Key {
    ///     type Value = u32;
    /// }
    ///
    /// impl TypedMapKey for SKey {
    ///     type Value = usize;
    /// }
    ///
    /// let mut map: TypedMap = TypedMap::new();
    /// map.insert(Key(3), 3);
    /// map.insert(SKey("four"), 4);
    ///
    /// for value in map.values() {
    ///     let mut found = false;
    ///     if let Some(number) = value.downcast_ref::<u32>() {
    ///         assert_eq!(*number, 3);
    ///         found = true;
    ///     }
    ///     if let Some(number) = value.downcast_ref::<usize>() {
    ///         assert_eq!(*number, 4);
    ///         found = true;
    ///     }
    ///     assert!(found);
    /// }
    /// ```
    pub fn values(&self) -> Values<'_> {
        Values(self.state.values())
    }

    /// An iterator visiting all values mutably in arbitrary order. The iterator element type is &'a mut dyn Any.
    ///
    /// # Examples
    /// ```
    /// use typedmap::TypedMap;
    /// use typedmap::TypedMapKey;
    ///
    /// #[derive(Hash, PartialEq, Eq, Debug)]
    /// struct Key(usize);
    /// #[derive(Hash, PartialEq, Eq, Debug)]
    /// struct SKey(&'static str);
    ///
    /// impl TypedMapKey for Key {
    ///     type Value = u32;
    /// }
    ///
    /// impl TypedMapKey for SKey {
    ///     type Value = usize;
    /// }
    ///
    /// let mut map: TypedMap = TypedMap::new();
    /// map.insert(Key(3), 3);
    /// map.insert(SKey("four"), 4);
    ///
    /// for value in map.values_mut() {
    ///     let mut found = false;
    ///     if let Some(number) = value.downcast_mut::<u32>() {
    ///         *number += 1;
    ///         found = true;
    ///     }
    ///     if let Some(number) = value.downcast_mut::<usize>() {
    ///         *number += 2;
    ///         found = true;
    ///     }
    ///     assert!(found);
    /// }
    ///
    /// assert_eq!(map[&Key(3)], 4);
    /// assert_eq!(map[&SKey("four")], 6);
    /// ```
    pub fn values_mut(&mut self) -> ValuesMut<'_> {
        ValuesMut(self.state.values_mut())
    }

    /// Clears the map, returning all key-value pairs as an iterator. Keeps the allocated memory for reuse.
    ///
    /// # Examples
    /// ```
    /// use typedmap::TypedMap;
    /// use typedmap::TypedMapKey;
    ///
    /// #[derive(Hash, PartialEq, Eq, Debug)]
    /// struct Key(usize);
    /// #[derive(Hash, PartialEq, Eq, Debug)]
    /// struct SKey(&'static str);
    ///
    /// impl TypedMapKey for Key {
    ///     type Value = u32;
    /// }
    ///
    /// impl TypedMapKey for SKey {
    ///     type Value = usize;
    /// }
    ///
    /// let mut map: TypedMap = TypedMap::new();
    /// map.insert(Key(3), 3);
    /// map.insert(SKey("four"), 4);
    ///
    /// for key_value in map.drain() {
    ///     match key_value.downcast_pair::<Key>() {
    ///         Ok((key, value)) => {
    ///             assert_eq!(key, Key(3));
    ///             assert_eq!(value, 3u32);
    ///         }
    ///         Err(key_value) => {
    ///             let (key, value) = key_value.downcast_pair::<SKey>().unwrap();
    ///             assert_eq!(key, SKey("four"));
    ///             assert_eq!(value, 4usize);
    ///         }
    ///     }
    /// }
    /// ```
    pub fn drain(&mut self) -> Drain<'_, Marker> {
        Drain(self.state.drain(), PhantomData)
    }

    /// An iterator visiting all key-value pairs in arbitrary order.
    ///
    /// # Examples
    /// ```
    /// use typedmap::TypedMap;
    /// use typedmap::TypedMapKey;
    ///
    /// #[derive(Hash, PartialEq, Eq, Debug)]
    /// struct Key(usize);
    /// #[derive(Hash, PartialEq, Eq, Debug)]
    /// struct SKey(&'static str);
    ///
    /// impl TypedMapKey for Key {
    ///     type Value = u32;
    /// }
    ///
    /// impl TypedMapKey for SKey {
    ///     type Value = usize;
    /// }
    ///
    /// let mut map: TypedMap = TypedMap::new();
    /// map.insert(Key(3), 3);
    /// map.insert(SKey("four"), 4);
    ///
    /// for key_value in map.iter() {
    ///     if let Some((key, value)) = key_value.downcast_pair_ref::<Key>() {
    ///         assert_eq!(key, &Key(3));
    ///         assert_eq!(value, &3u32);
    ///     }
    ///
    ///     if let Some((key, value)) = key_value.downcast_pair_ref::<SKey>() {
    ///         assert_eq!(key, &SKey("four"));
    ///         assert_eq!(value, &4);
    ///     }
    /// }
    /// ```
    pub fn iter(&self) -> Iter<'_, Marker> {
        Iter(self.state.iter(), PhantomData)
    }

    /// An iterator visiting all key-value pairs in arbitrary order, with mutable references to the values.
    ///
    /// # Examples
    /// ```
    /// use typedmap::TypedMap;
    /// use typedmap::TypedMapKey;
    ///
    /// #[derive(Hash, PartialEq, Eq, Debug)]
    /// struct Key(usize);
    /// #[derive(Hash, PartialEq, Eq, Debug)]
    /// struct SKey(&'static str);
    ///
    /// impl TypedMapKey for Key {
    ///     type Value = u32;
    /// }
    ///
    /// impl TypedMapKey for SKey {
    ///     type Value = usize;
    /// }
    ///
    /// let mut map: TypedMap = TypedMap::new();
    /// map.insert(Key(3), 3);
    /// map.insert(SKey("four"), 4);
    ///
    /// for mut key_value in map.iter_mut() {
    ///     if let Some((key, value)) = key_value.downcast_pair_mut::<Key>() {
    ///         assert_eq!(key, &Key(3));
    ///         *value += 1;
    ///         assert_eq!(value, &4u32);
    ///     }
    ///     if let Some((key, value)) = key_value.downcast_pair_mut::<SKey>() {
    ///         assert_eq!(key, &SKey("four"));
    ///         *value += 1;
    ///         assert_eq!(value, &5);
    ///     }
    /// }
    ///
    /// assert_eq!(map[&Key(3)], 4);
    /// assert_eq!(map[&SKey("four")], 5);
    /// ```
    pub fn iter_mut(&mut self) -> IterMut<'_, Marker> {
        IterMut(self.state.iter_mut(), PhantomData)
    }

    /// Retains only the elements specified by the predicate.
    ///
    /// # Examples
    /// ```
    /// use typedmap::TypedMap;
    /// use typedmap::TypedMapKey;
    ///
    /// #[derive(Hash, PartialEq, Eq, Debug)]
    /// struct Key(usize);
    ///
    /// impl TypedMapKey for Key {
    ///     type Value = u32;
    /// }
    ///
    /// let mut map: TypedMap = TypedMap::new();
    /// map.insert(Key(3), 3);
    /// map.insert(Key(4), 4);
    /// map.insert(Key(5), 5);
    ///
    /// map.retain(|mut kv| *kv.downcast_value::<u32>().unwrap_or(&mut 0) % 2 == 1);
    ///
    /// assert_eq!(map.len(), 2);
    /// assert!(map.contains_key(&Key(5)));
    /// assert!(!map.contains_key(&Key(4)));
    ///
    /// map.retain(|mut kv| kv.downcast_key_ref::<Key>().unwrap().0 <= 3);
    /// assert!(map.contains_key(&Key(3)));
    /// assert!(!map.contains_key(&Key(5)));
    /// ```
    pub fn retain<F>(&mut self, mut f: F)
    where
        F: FnMut(TypedKeyValueMutRef<'_, Marker>) -> bool,
    {
        let g = move |key: &TypedKey, value: &mut TypedMapValue| {
            f(TypedKeyValueMutRef {
                key,
                value,
                _marker: PhantomData,
            })
        };
        self.state.retain(g)
    }
}

impl<Marker> Default for TypedMap<Marker> {
    fn default() -> Self {
        TypedMap::new()
    }
}

impl<Marker> IntoIterator for TypedMap<Marker> {
    type IntoIter = IntoIter<Marker>;
    type Item = TypedKeyValue<Marker>;

    fn into_iter(self) -> Self::IntoIter {
        IntoIter(self.state.into_iter(), PhantomData)
    }
}

impl<Marker, K: 'static + TypedMapKey<Marker>, S: BuildHasher> Index<&K> for TypedMap<Marker, S> {
    type Output = K::Value;

    fn index(&self, key: &K) -> &K::Value {
        self.get(key).expect("no entry found for key")
    }
}

/// An iterator over the entries of a TypedMap
///
/// This `struct` is created by ['iter'] method on ['TypedMap']. See its documentation for more.
///
/// ['iter']: TypedMap::iter
///
/// # Example
/// ```
/// use typedmap::TypedMap;
/// use typedmap::TypedMapKey;
///
/// #[derive(Hash, PartialEq, Eq, Debug)]
/// struct Key(usize);
///
/// impl TypedMapKey for Key {
///     type Value = u32;
/// }
///
/// let mut map: TypedMap = TypedMap::new();
/// map.insert(Key(3), 3);
/// let iter = map.iter();
///
#[derive(Clone)]
pub struct Iter<'a, Marker>(
    std::collections::hash_map::Iter<'a, TypedKey, TypedMapValue>,
    PhantomData<Marker>,
);

impl<'a, Marker> Iterator for Iter<'a, Marker> {
    type Item = TypedKeyValueRef<'a, Marker>;

    fn next(&mut self) -> Option<Self::Item> {
        let (key, value) = self.0.next()?;
        Some(TypedKeyValueRef {
            key,
            value,
            _marker: PhantomData,
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl<Marker> ExactSizeIterator for Iter<'_, Marker> {}
impl<Marker> FusedIterator for Iter<'_, Marker> {}

/// A mutable iterator over the entries of a TypedMap
///
/// This `struct` is created by ['iter_mut'] method on ['TypedMap']. See its documentation for more.
///
/// ['iter_mut']: TypedMap::iter_mut
///
/// # Example
/// ```
/// use typedmap::TypedMap;
/// use typedmap::TypedMapKey;
///
/// #[derive(Hash, PartialEq, Eq, Debug)]
/// struct Key(usize);
///
/// impl TypedMapKey for Key {
///     type Value = u32;
/// }
///
/// let mut map: TypedMap = TypedMap::new();
/// map.insert(Key(3), 3);
/// let iter = map.iter_mut();
/// ```
pub struct IterMut<'a, Marker>(
    std::collections::hash_map::IterMut<'a, TypedKey, TypedMapValue>,
    PhantomData<Marker>,
);

impl<'a, Marker> Iterator for IterMut<'a, Marker> {
    type Item = TypedKeyValueMutRef<'a, Marker>;

    fn next(&mut self) -> Option<Self::Item> {
        let (key, value) = self.0.next()?;
        Some(TypedKeyValueMutRef {
            key,
            value,
            _marker: PhantomData,
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl<Marker> ExactSizeIterator for IterMut<'_, Marker> {}
impl<Marker> FusedIterator for IterMut<'_, Marker> {}

/// An draining iterator over the entries of a `TypedMap`.
///
/// This `struct` is created by the [`drain`] method on [`TypedMap`].
/// See its documentation for more.
///
/// [`drain`]: TypedMap::drain
///
/// # Example
/// ```
/// use typedmap::TypedMap;
/// use typedmap::TypedMapKey;
///
/// #[derive(Hash, PartialEq, Eq, Debug)]
/// struct Key(usize);
///
/// impl TypedMapKey for Key {
///     type Value = u32;
/// }
///
/// let mut map: TypedMap = TypedMap::new();
/// map.insert(Key(3), 3);
/// let iter = map.into_iter();
/// ```
pub struct Drain<'a, Marker>(
    std::collections::hash_map::Drain<'a, TypedKey, TypedMapValue>,
    PhantomData<Marker>,
);

impl<'a, Marker> Iterator for Drain<'a, Marker> {
    type Item = TypedKeyValue<Marker>;

    fn next(&mut self) -> Option<Self::Item> {
        let (key, value) = self.0.next()?;
        Some(TypedKeyValue {
            key,
            value,
            _marker: PhantomData,
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl<Marker> ExactSizeIterator for Drain<'_, Marker> {}
impl<Marker> FusedIterator for Drain<'_, Marker> {}

/// An owning iterator over the entries of a `TypedMap`.
///
/// This `struct` is created by the [`into_iter`] method on [`TypedMap`]
/// (provided by the `IntoIterator` trait). See its documentation for more.
///
/// [`into_iter`]: IntoIterator::into_iter
///
/// # Example
/// ```
/// use typedmap::TypedMap;
/// use typedmap::TypedMapKey;
///
/// #[derive(Hash, PartialEq, Eq, Debug)]
/// struct Key(usize);
///
/// impl TypedMapKey for Key {
///     type Value = u32;
/// }
///
/// let mut map: TypedMap = TypedMap::new();
/// map.insert(Key(3), 3);
/// ```
pub struct IntoIter<Marker>(
    std::collections::hash_map::IntoIter<TypedKey, TypedMapValue>,
    PhantomData<Marker>,
);

impl<Marker> Iterator for IntoIter<Marker> {
    type Item = TypedKeyValue<Marker>;

    fn next(&mut self) -> Option<Self::Item> {
        let (key, value) = self.0.next()?;
        Some(TypedKeyValue {
            key,
            value,
            _marker: PhantomData,
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl<Marker> ExactSizeIterator for IntoIter<Marker> {}
impl<Marker> FusedIterator for IntoIter<Marker> {}

/// An iterator over the keys of a `HashMap`.
///
/// This `struct` is created by the [`keys`] method on [`TypedMap`]. See its
/// documentation for more.
///
/// [`keys`]: TypedMap::keys
///
/// # Example
///
/// ```
/// use typedmap::TypedMap;
/// use typedmap::TypedMapKey;
///
/// #[derive(Hash, PartialEq, Eq, Debug)]
/// struct Key(usize);
///
/// impl TypedMapKey for Key {
///     type Value = u32;
/// }
///
/// let mut map: TypedMap = TypedMap::new();
/// map.insert(Key(3), 3);
/// let iter = map.keys();
/// ```
#[derive(Clone)]
pub struct Keys<'a>(std::collections::hash_map::Keys<'a, TypedKey, TypedMapValue>);

impl<'a> Iterator for Keys<'a> {
    type Item = &'a dyn Any;

    fn next(&mut self) -> Option<Self::Item> {
        let key = self.0.next()?;
        Some(key.as_any())
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl ExactSizeIterator for Keys<'_> {}
impl FusedIterator for Keys<'_> {}

/// An iterator over the values of a `HashMap`.
///
/// This `struct` is created by the [`values`] method on [`TypedMap`]. See its
/// documentation for more.
///
/// [`values`]: TypedMap::values
///
/// # Example
///
/// ```
/// use typedmap::TypedMap;
/// use typedmap::TypedMapKey;
///
/// #[derive(Hash, PartialEq, Eq, Debug)]
/// struct Key(usize);
///
/// impl TypedMapKey for Key {
///     type Value = u32;
/// }
///
/// let mut map: TypedMap = TypedMap::new();
/// map.insert(Key(3), 3);
/// let iter = map.values();
/// ```
#[derive(Clone)]
pub struct Values<'a>(std::collections::hash_map::Values<'a, TypedKey, TypedMapValue>);

impl<'a> Iterator for Values<'a> {
    type Item = &'a dyn Any;

    fn next(&mut self) -> Option<Self::Item> {
        let value = self.0.next()?;
        Some(value.as_any())
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl ExactSizeIterator for Values<'_> {}
impl FusedIterator for Values<'_> {}

/// An mutable iterator over the values of a `HashMap`.
///
/// This `struct` is created by the [`values`] method on [`TypedMap`]. See its
/// documentation for more.
///
/// [`values`]: TypedMap::values
///
/// # Example
///
/// ```
/// use typedmap::TypedMap;
/// use typedmap::TypedMapKey;
///
/// #[derive(Hash, PartialEq, Eq, Debug)]
/// struct Key(usize);
///
/// impl TypedMapKey for Key {
///     type Value = u32;
/// }
///
/// let mut map: TypedMap = TypedMap::new();
/// map.insert(Key(3), 3);
/// let iter = map.values();
/// ```
pub struct ValuesMut<'a>(std::collections::hash_map::ValuesMut<'a, TypedKey, TypedMapValue>);

impl<'a> Iterator for ValuesMut<'a> {
    type Item = &'a mut dyn Any;

    fn next(&mut self) -> Option<Self::Item> {
        let value = self.0.next()?;
        Some(value.as_mut_any())
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl ExactSizeIterator for ValuesMut<'_> {}
impl FusedIterator for ValuesMut<'_> {}

/// Represents owned pair of key and value.
pub struct TypedKeyValue<Marker> {
    key: TypedKey,
    value: TypedMapValue,
    _marker: PhantomData<Marker>,
}

impl<Marker> TypedKeyValue<Marker> {
    /// Downcast key to reference of `K`. Returns `None` if not possible.
    pub fn downcast_key_ref<K: 'static + TypedMapKey<Marker>>(&self) -> Option<&K> {
        self.key.downcast_ref()
    }

    /// Downcast key to the owned value of type `K`. Returns Err(Self) if not possible.
    pub fn downcast_key<K: 'static + TypedMapKey<Marker>>(self) -> Result<K, Self> {
        let Self {
            key,
            value,
            _marker,
        } = self;
        key.downcast().map_err(|key| Self {
            key,
            value,
            _marker,
        })
    }

    /// Downcast key to reference of `V`. Returns `None` if not possible.
    pub fn downcast_value_ref<V: Any>(&self) -> Option<&V> {
        self.key.downcast_ref()
    }

    /// Downcast key to the owned value of type `V`. Returns Err(Self) if not possible.
    pub fn downcast_value<V: Any>(self) -> Result<V, Self> {
        let Self {
            key,
            value,
            _marker,
        } = self;
        value.downcast().map_err(|value| Self {
            key,
            value,
            _marker,
        })
    }

    /// Downcast key to reference of `K` and value to reference of `K::Value`.
    /// Returns `None` if not possible.
    pub fn downcast_pair_ref<K: 'static + TypedMapKey<Marker>>(&self) -> Option<(&K, &K::Value)> {
        let key = self.downcast_key_ref()?;
        let value = self.downcast_value_ref()?;
        Some((key, value))
    }

    /// Downcast key to owned value of type `K` and value to owned value of type `K::Value`.
    /// Returns Err(Self) if not possible.
    pub fn downcast_pair<K: 'static + TypedMapKey<Marker>>(self) -> Result<(K, K::Value), Self> {
        let Self {
            key,
            value,
            _marker,
        } = self;
        match key.downcast() {
            Ok(key) => match value.downcast() {
                Ok(value) => Ok((key, value)),
                Err(dyn_value) => Err(Self {
                    key: TypedKey::from_key(key),
                    value: dyn_value,
                    _marker,
                }),
            },
            Err(dyn_key) => Err(Self {
                key: dyn_key,
                value,
                _marker,
            }),
        }
    }
}

impl<M> Debug for TypedKeyValue<M> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("TypedKeyValue")
    }
}

/// Represents borrowed pair of key and value.
pub struct TypedKeyValueRef<'a, Marker> {
    key: &'a TypedKey,
    value: &'a TypedMapValue,
    _marker: PhantomData<Marker>,
}

// TODO: Consider whether should use _ref suffix in those methods
impl<'a, Marker> TypedKeyValueRef<'a, Marker> {
    /// Downcast key to reference of `K`. Returns `None` if not possible.
    pub fn downcast_key_ref<K: 'static + TypedMapKey<Marker>>(&self) -> Option<&'a K> {
        self.key.downcast_ref()
    }

    /// Downcast value and returns reference or `None` if downcast failed.
    pub fn downcast_value_ref<V: 'static + Any>(&self) -> Option<&'a V> {
        self.value.downcast_ref()
    }

    /// Downcast key to reference of `K` and value to reference of `K::Value`.
    /// Returns `None` if not possible.
    pub fn downcast_pair_ref<K: 'static + TypedMapKey<Marker>>(
        &self,
    ) -> Option<(&'a K, &'a K::Value)> {
        self.downcast_key_ref()
            .and_then(move |key| self.downcast_value_ref().map(move |value| (key, value)))
    }
}

impl<M> Debug for TypedKeyValueRef<'_, M> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("TypedKeyValueRef")
    }
}

/// Represents mutably borrowed pair of key and value.
pub struct TypedKeyValueMutRef<'a, Marker> {
    key: &'a TypedKey,
    value: &'a mut TypedMapValue,
    _marker: PhantomData<Marker>,
}

impl<'a, Marker> TypedKeyValueMutRef<'a, Marker> {
    /// Downcast key to reference of `K`. Returns `None` if not possible.
    pub fn downcast_key_ref<K: 'static + TypedMapKey<Marker>>(&self) -> Option<&'a K> {
        self.key.downcast_ref()
    }

    /// Downcast value to type `V`. Returns `None` if not possible.
    ///
    /// Note: this function borrows mutably self, and returns mutable reference with lifetime
    /// bounded by that borrow. If you need to obtain mutable reference with hashmap bounded
    /// lifetime ('a), then use `downcast_value` function.
    pub fn downcast_value_mut<'b, V: 'static + Any>(&'b mut self) -> Option<&'b mut V>
    where
        'a: 'b,
    {
        self.value.downcast_mut()
    }

    /// Tries to cast value to mutable reference of V consuming self. This allows to return
    /// mutable reference with 'a lifetime which may be useful when collecting mutable references.
    ///
    /// # Examples:
    /// ```
    /// use typedmap::TypedMap;
    /// use typedmap::TypedMapKey;
    ///
    /// #[derive(Hash, PartialEq, Eq, Debug)]
    /// struct Key(usize);
    /// #[derive(Hash, PartialEq, Eq, Debug)]
    /// struct SKey(&'static str);
    ///
    /// impl TypedMapKey for Key {
    ///     type Value = u32;
    /// }
    ///
    /// impl TypedMapKey for SKey {
    ///     type Value = usize;
    /// }
    ///
    /// let mut map: TypedMap = TypedMap::new();
    /// map.insert(Key(3), 3);
    /// map.insert(SKey("four"), 4);
    ///
    /// let v: Vec<&mut u32> = map
    ///     .iter_mut()
    ///     .flat_map(|kv| kv.downcast_value::<u32>().ok())
    ///     .collect();
    /// assert_eq!(*v[0], 3);
    /// assert_eq!(v.len(), 1);
    /// ```
    pub fn downcast_value<V: 'static + Any>(self) -> Result<&'a mut V, Self> {
        if self.value.is::<V>() {
            Ok(self.value.downcast_mut().expect("Unreachable!"))
        } else {
            Err(self)
        }
    }

    /// Downcast key to type `K` and value to type `K::Value`. Returns `None` if not possible.
    ///
    /// Note: this function borrows mutably self, and returns mutable reference with lifetime
    /// bounded by that borrow. If you need to obtain mutable reference with hashmap bounded
    /// lifetime ('a), then use `downcast_pair` function.
    pub fn downcast_pair_mut<'b, K: 'static + TypedMapKey<Marker>>(
        &'b mut self,
    ) -> Option<(&'b K, &'b mut K::Value)>
    where
        'a: 'b,
    {
        self.downcast_key_ref()
            .and_then(move |key| self.downcast_value_mut().map(move |value| (key, value)))
    }

    /// Tries to cast self to key K and value K::Value consuming self.
    /// This allows to return references with 'a lifetime which may be
    /// useful when collecting references to Vec.
    ///
    /// # Examples:
    /// ```
    /// use typedmap::TypedMap;
    /// use typedmap::TypedMapKey;
    ///
    /// #[derive(Hash, PartialEq, Eq, Debug)]
    /// struct Key(usize);
    /// #[derive(Hash, PartialEq, Eq, Debug)]
    /// struct SKey(&'static str);
    ///
    /// impl TypedMapKey for Key {
    ///     type Value = u32;
    /// }
    ///
    /// impl TypedMapKey for SKey {
    ///     type Value = usize;
    /// }
    ///
    /// let mut map: TypedMap = TypedMap::new();
    /// map.insert(Key(3), 3);
    /// map.insert(SKey("four"), 4);
    ///
    /// let v: Vec<(&Key, &mut u32)> = map
    ///     .iter_mut()
    ///     .flat_map(|kv| kv.downcast_pair::<Key>().ok())
    ///     .collect();
    /// assert_eq!(*v[0].0, Key(3));
    /// assert_eq!(*v[0].1, 3);
    /// assert_eq!(v.len(), 1);
    /// ```
    pub fn downcast_pair<K: 'static + TypedMapKey<Marker>>(
        self,
    ) -> Result<(&'a K, &'a mut K::Value), Self> {
        let key = self.downcast_key_ref();

        let key = match key {
            Some(key) => key,
            None => return Err(self),
        };

        match self.downcast_value() {
            Ok(value) => Ok((key, value)),
            Err(err) => Err(err),
        }
    }
}

impl<M> Debug for TypedKeyValueMutRef<'_, M> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("TypedMutRef")
    }
}

#[cfg(test)]
mod tests {
    use crate::TypedMap;
    use crate::TypedMapKey;
    use std::hash::Hash;

    #[test]
    fn test_basic_use() {
        // FIXME: split test into smaller tests testing one thing at a time
        struct OtherState;

        let mut state = TypedMap::new();
        let mut other_state = TypedMap::<OtherState>::new();

        #[derive(Clone, Debug, Hash, PartialEq, Eq)]
        struct AThing;

        #[derive(Clone, Debug, Hash, PartialEq, Eq)]
        struct BThing(usize);

        #[derive(Clone, Debug, Hash, PartialEq, Eq)]
        struct CThing(usize);

        impl TypedMapKey for AThing {
            type Value = String;
        }

        impl TypedMapKey for BThing {
            type Value = usize;
        }

        impl TypedMapKey<OtherState> for CThing {
            type Value = usize;
        }

        state.insert(AThing, "Example".to_owned());
        state.insert(BThing(32), 33);
        state.insert(BThing(33), 34);
        // This does not compile, as marker is not correct!
        // state.insert(&CThing(0), 33);
        // And this works fine!
        other_state.insert(CThing(0), 33);

        assert_eq!(state.get(&AThing), Some(&"Example".to_owned()));
        assert_eq!(state.get(&BThing(0)), None);
        assert_eq!(state.get(&BThing(32)), Some(&33));
        assert_eq!(state.get(&BThing(33)), Some(&34));
        assert_eq!(other_state.get(&CThing(0)), Some(&33));

        *state.entry(BThing(3)).or_default() += 1;
        assert_eq!(*state.get(&BThing(3)).unwrap(), 1usize);

        *state.entry(BThing(4)).or_insert(3usize) += 1;
        *state.entry(BThing(4)).or_insert(3usize) += 1;
        assert_eq!(*state.get(&BThing(4)).unwrap(), 5usize);

        if let crate::entry::Entry::Occupied(occupied) = state.entry(BThing(3)) {
            let (k, v) = occupied.remove_entry();
            assert_eq!(k, BThing(3));
            assert_eq!(v, 1usize);
        } else {
            panic!()
        }

        let mut b_entries: Vec<_> = state
            .iter()
            .flat_map(|r| r.downcast_pair_ref::<BThing>())
            .collect();
        b_entries.sort_by_key(|kv| (kv.0).0);

        let b4 = BThing(4);
        let b32 = BThing(32);
        let b33 = BThing(33);
        assert_eq!(
            b_entries,
            vec![(&b4, &5usize), (&b32, &33usize), (&b33, &34usize)]
        );

        state.iter_mut().for_each(|mut r| {
            if let Some((_, value)) = r.downcast_pair_mut::<BThing>() {
                *value += 1;
            }
        });

        let b_things: Vec<_> = state
            .iter_mut()
            .flat_map(|r| r.downcast_pair::<BThing>())
            .collect();

        assert_eq!(b_things.len(), 3);
    }

    #[test]
    fn test_always_equal_types() {
        let mut state = TypedMap::default();
        #[derive(Debug, Clone, Hash, PartialEq, Eq)]
        struct AThing;
        #[derive(Debug, Clone, Hash, PartialEq, Eq)]
        struct BThing;

        trait Foo {}

        impl Foo for AThing {}
        impl Foo for BThing {}

        impl Hash for Box<dyn Foo> {
            fn hash<H>(&self, hasher: &mut H)
            where
                H: std::hash::Hasher,
            {
                hasher.write_i8(0);
                hasher.finish();
            }
        }

        impl PartialEq for Box<dyn Foo> {
            fn eq(&self, _rhs: &Self) -> bool {
                true
            }
        }

        impl Eq for Box<dyn Foo> {}

        impl TypedMapKey for AThing {
            type Value = String;
        }

        impl TypedMapKey for BThing {
            type Value = usize;
        }

        impl TypedMapKey for Box<dyn Foo> {
            type Value = String;
        }

        let key_a = Box::new(AThing);
        let key_b = Box::new(BThing);

        state.insert(key_a.clone() as Box<dyn Foo>, "test1".to_owned());
        let old_key = state
            .insert(key_b.clone() as Box<dyn Foo>, "test2".to_owned())
            .unwrap();

        assert_eq!(old_key, "test1".to_owned());

        let key_a = &(key_a as Box<dyn Foo>);
        let key_b = &(key_b as Box<dyn Foo>);

        assert_eq!(state.get(key_a).unwrap(), &"test2".to_owned());
        assert_eq!(state.get(key_b).unwrap(), &"test2".to_owned());

        assert_eq!(state.remove(key_a).unwrap(), "test2".to_owned());

        assert!(state.is_empty());
        assert_eq!(state.len(), 0);
    }
}