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
//! Easy to use, high performance memory manager for Vulkan.

#![allow(invalid_value)]

extern crate erupt;
#[macro_use]
extern crate bitflags;
#[cfg(feature = "failure")]
extern crate failure;

pub mod error;
pub mod ffi;
pub use crate::error::{Error, ErrorKind, Result};
use std::mem;
use std::sync::Arc;

/// Main allocator object
pub struct Allocator {
    /// Pointer to internal VmaAllocator instance
    pub(crate) internal: ffi::VmaAllocator,
    /// Vulkan device handle
    #[allow(dead_code)]
    pub(crate) device: Arc<erupt::DeviceLoader>,
    /// Vulkan instance handle
    #[allow(dead_code)]
    pub(crate) instance: Arc<erupt::InstanceLoader>,
}

// Allocator is internally thread safe unless AllocatorCreateFlags::EXTERNALLY_SYNCHRONIZED is used (then you need to add synchronization!)
unsafe impl Send for Allocator {}
unsafe impl Sync for Allocator {}

/// Represents custom memory pool
///
/// Fill structure `AllocatorPoolCreateInfo` and call `Allocator::create_pool` to create it.
/// Call `Allocator::destroy_pool` to destroy it.
#[derive(Debug, Clone)]
pub struct AllocatorPool {
    /// Pointer to internal VmaPool instance
    pub(crate) internal: ffi::VmaPool,
}

/// Construct `AllocatorPool` with default values
impl Default for AllocatorPool {
    fn default() -> Self {
        AllocatorPool {
            internal: unsafe { mem::zeroed() },
        }
    }
}

/// Represents single memory allocation.
///
/// It may be either dedicated block of `erupt::vk::DeviceMemory` or a specific region of a
/// bigger block of this type plus unique offset.
///
/// Although the library provides convenience functions that create a Vulkan buffer or image,
/// allocate memory for it and bind them together, binding of the allocation to a buffer or an
/// image is out of scope of the allocation itself.
///
/// Allocation object can exist without buffer/image bound, binding can be done manually by
/// the user, and destruction of it can be done independently of destruction of the allocation.
///
/// The object also remembers its size and some other information. To retrieve this information,
/// use `Allocator::get_allocation_info`.
///
/// Some kinds allocations can be in lost state.
#[derive(Debug, Copy, Clone)]
pub struct Allocation {
    /// Pointer to internal VmaAllocation instance
    pub(crate) internal: ffi::VmaAllocation,
}

impl Allocation {
    pub fn null() -> Allocation {
        Allocation {
            internal: std::ptr::null_mut(),
        }
    }
}

unsafe impl Send for Allocation {}
unsafe impl Sync for Allocation {}

/// Parameters of `Allocation` objects, that can be retrieved using `Allocator::get_allocation_info`.
#[derive(Debug, Clone)]
pub struct AllocationInfo {
    /// Pointer to internal VmaAllocationInfo instance
    pub(crate) internal: ffi::VmaAllocationInfo,
}

unsafe impl Send for AllocationInfo {}
unsafe impl Sync for AllocationInfo {}

impl AllocationInfo {
    #[inline(always)]
    // Gets the memory type index that this allocation was allocated from. (Never changes)
    pub fn get_memory_type(&self) -> u32 {
        self.internal.memoryType
    }

    /// Handle to Vulkan memory object.
    ///
    /// Same memory object can be shared by multiple allocations.
    ///
    /// It can change after call to `Allocator::defragment` if this allocation is passed
    /// to the function, or if allocation is lost.
    ///
    /// If the allocation is lost, it is equal to `erupt::vk::DeviceMemory::null()`.
    #[inline(always)]
    pub fn get_device_memory(&self) -> erupt::vk::DeviceMemory {
        erupt::vk::DeviceMemory(self.internal.deviceMemory as u64)
    }

    /// Offset into device memory object to the beginning of this allocation, in bytes.
    /// (`self.get_device_memory()`, `self.get_offset()`) pair is unique to this allocation.
    ///
    /// It can change after call to `Allocator::defragment` if this allocation is passed
    /// to the function, or if allocation is lost.
    #[inline(always)]
    pub fn get_offset(&self) -> usize {
        self.internal.offset as usize
    }

    /// Size of this allocation, in bytes.
    ///
    /// It never changes, unless allocation is lost.
    #[inline(always)]
    pub fn get_size(&self) -> usize {
        self.internal.size as usize
    }

    /// Pointer to the beginning of this allocation as mapped data.
    ///
    /// If the allocation hasn't been mapped using `Allocator::map_memory` and hasn't been
    /// created with `AllocationCreateFlags::MAPPED` flag, this value is null.
    ///
    /// It can change after call to `Allocator::map_memory`, `Allocator::unmap_memory`.
    /// It can also change after call to `Allocator::defragment` if this allocation is
    /// passed to the function.
    #[inline(always)]
    pub fn get_mapped_data(&self) -> *mut u8 {
        self.internal.pMappedData as *mut u8
    }

    /*#[inline(always)]
    pub fn get_mapped_slice(&self) -> Option<&mut &[u8]> {
        if self.internal.pMappedData.is_null() {
            None
        } else {
            Some(unsafe { &mut ::std::slice::from_raw_parts(self.internal.pMappedData as *mut u8, self.get_size()) })
        }
    }*/

    /// Custom general-purpose pointer that was passed as `AllocationCreateInfo::user_data` or set using `Allocator::set_allocation_user_data`.
    ///
    /// It can change after a call to `Allocator::set_allocation_user_data` for this allocation.
    #[inline(always)]
    pub fn get_user_data(&self) -> *mut ::std::os::raw::c_void {
        self.internal.pUserData
    }
}

bitflags! {
    /// Flags for configuring `Allocator` construction.
    pub struct AllocatorCreateFlags: u32 {
        /// No allocator configuration other than defaults.
        const NONE = 0x0000_0000;

        /// Allocator and all objects created from it will not be synchronized internally,
        /// so you must guarantee they are used from only one thread at a time or synchronized
        /// externally by you. Using this flag may increase performance because internal
        /// mutexes are not used.
        const EXTERNALLY_SYNCHRONIZED = 0x0000_0001;

        /// Enables usage of `VK_KHR_dedicated_allocation` extension.
        ///
        /// Using this extenion will automatically allocate dedicated blocks of memory for
        /// some buffers and images instead of suballocating place for them out of bigger
        /// memory blocks (as if you explicitly used `AllocationCreateFlags::DEDICATED_MEMORY` flag) when it is
        /// recommended by the driver. It may improve performance on some GPUs.
        ///
        /// You may set this flag only if you found out that following device extensions are
        /// supported, you enabled them while creating Vulkan device passed as
        /// `AllocatorCreateInfo::device`, and you want them to be used internally by this
        /// library:
        ///
        /// - VK_KHR_get_memory_requirements2
        /// - VK_KHR_dedicated_allocation
        ///
        /// When this flag is set, you can experience following warnings reported by Vulkan
        /// validation layer. You can ignore them.
        /// `> vkBindBufferMemory(): Binding memory to buffer 0x2d but vkGetBufferMemoryRequirements() has not been called on that buffer.`
        const KHR_DEDICATED_ALLOCATION = 0x0000_0002;

        /// Enables usage of VK_KHR_bind_memory2 extension.
        ///
        /// The flag works only if VmaAllocatorCreateInfo::vulkanApiVersion `== VK_API_VERSION_1_0`.
        /// When it's `VK_API_VERSION_1_1`, the flag is ignored because the extension has been promoted to Vulkan 1.1.
        ///
        /// You may set this flag only if you found out that this device extension is supported,
        /// you enabled it while creating Vulkan device passed as VmaAllocatorCreateInfo::device,
        /// and you want it to be used internally by this library.
        ///
        /// The extension provides functions `vkBindBufferMemory2KHR` and `vkBindImageMemory2KHR`,
        /// which allow to pass a chain of `pNext` structures while binding.
        /// This flag is required if you use `pNext` parameter in vmaBindBufferMemory2() or vmaBindImageMemory2().
        const VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2 = 0x00000004;

        /// Enables usage of VK_EXT_memory_budget extension.
        ///
        /// You may set this flag only if you found out that this device extension is supported,
        /// you enabled it while creating Vulkan device passed as VmaAllocatorCreateInfo::device,
        /// and you want it to be used internally by this library, along with another instance extension
        /// VK_KHR_get_physical_device_properties2, which is required by it (or Vulkan 1.1, where this extension is promoted).
        ///
        /// The extension provides query for current memory usage and budget, which will probably
        /// be more accurate than an estimation used by the library otherwise.
        const VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET = 0x00000008;

        /// Enables usage of VK_AMD_device_coherent_memory extension.
        ///
        /// You may set this flag only if you:
        ///
        /// - found out that this device extension is supported and enabled it while creating Vulkan device passed as VmaAllocatorCreateInfo::device,
        /// - checked that `VkPhysicalDeviceCoherentMemoryFeaturesAMD::deviceCoherentMemory` is true and set it while creating the Vulkan device,
        /// - want it to be used internally by this library.
        ///
        /// The extension and accompanying device feature provide access to memory types with
        /// `VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD` and `VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD` flags.
        /// They are useful mostly for writing breadcrumb markers - a common method for debugging GPU crash/hang/TDR.
        ///
        /// When the extension is not enabled, such memory types are still enumerated, but their usage is illegal.
        /// To protect from this error, if you don't create the allocator with this flag, it will refuse to allocate any memory or create a custom pool in such memory type,
        /// returning `VK_ERROR_FEATURE_NOT_PRESENT`.
        const VMA_ALLOCATOR_CREATE_AMD_DEVICE_COHERENT_MEMORY = 0x00000010;

        /// Enables usage of "buffer device address" feature, which allows you to use function
        /// `vkGetBufferDeviceAddress*` to get raw GPU pointer to a buffer and pass it for usage inside a shader.
        ///
        /// You may set this flag only if you:
        ///
        /// 1. (For Vulkan version < 1.2) Found as available and enabled device extension
        /// VK_KHR_buffer_device_address.
        /// This extension is promoted to core Vulkan 1.2.
        /// 2. Found as available and enabled device feature `VkPhysicalDeviceBufferDeviceAddressFeatures::bufferDeviceAddress`.
        ///
        /// When this flag is set, you can create buffers with `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT` using VMA.
        /// The library automatically adds `VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT` to
        /// allocated memory blocks wherever it might be needed.
        ///
        /// For more information, see documentation chapter \ref enabling_buffer_device_address.
        const VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS = 0x00000020;

        /// Enables usage of VK_EXT_memory_priority extension in the library.
        ///
        /// You may set this flag only if you found available and enabled this device extension,
        /// along with `VkPhysicalDeviceMemoryPriorityFeaturesEXT::memoryPriority == VK_TRUE`,
        /// while creating Vulkan device passed as VmaAllocatorCreateInfo::device.
        ///
        /// When this flag is used, VmaAllocationCreateInfo::priority and VmaPoolCreateInfo::priority
        /// are used to set priorities of allocated Vulkan memory. Without it, these variables are ignored.
        ///
        /// A priority must be a floating-point value between 0 and 1, indicating the priority of the allocation relative to other memory allocations.
        /// Larger values are higher priority. The granularity of the priorities is implementation-dependent.
        /// It is automatically passed to every call to `vkAllocateMemory` done by the library using structure `VkMemoryPriorityAllocateInfoEXT`.
        /// The value to be used for default priority is 0.5.
        /// For more details, see the documentation of the VK_EXT_memory_priority extension.
        const VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY = 0x00000040;
    }
}

/// Construct `AllocatorCreateFlags` with default values
impl Default for AllocatorCreateFlags {
    fn default() -> Self {
        AllocatorCreateFlags::NONE
    }
}

/// Description of an `Allocator` to be created.
pub struct AllocatorCreateInfo {
    /// Vulkan physical device. It must be valid throughout whole lifetime of created allocator.
    pub physical_device: erupt::vk::PhysicalDevice,

    /// Vulkan device. It must be valid throughout whole lifetime of created allocator.
    pub device: Arc<erupt::DeviceLoader>,

    /// Vulkan instance. It must be valid throughout whole lifetime of created allocator.
    pub instance: Arc<erupt::InstanceLoader>,

    /// Flags for created allocator.
    pub flags: AllocatorCreateFlags,

    /// Preferred size of a single `erupt::vk::DeviceMemory` block to be allocated from large heaps > 1 GiB.
    /// Set to 0 to use default, which is currently 256 MiB.
    pub preferred_large_heap_block_size: usize,

    /// Maximum number of additional frames that are in use at the same time as current frame.
    ///
    /// This value is used only when you make allocations with `AllocationCreateFlags::CAN_BECOME_LOST` flag.
    ///
    /// Such allocations cannot become lost if:
    /// `allocation.lastUseFrameIndex >= allocator.currentFrameIndex - frameInUseCount`
    ///
    /// For example, if you double-buffer your command buffers, so resources used for
    /// rendering in previous frame may still be in use by the GPU at the moment you
    /// allocate resources needed for the current frame, set this value to 1.
    ///
    /// If you want to allow any allocations other than used in the current frame to
    /// become lost, set this value to 0.
    pub frame_in_use_count: u32,

    /// Either empty or an array of limits on maximum number of bytes that can be allocated
    /// out of particular Vulkan memory heap.
    ///
    /// If not empty, it must contain `erupt::vk::PhysicalDeviceMemoryProperties::memory_heap_count` elements,
    /// defining limit on maximum number of bytes that can be allocated out of particular Vulkan
    /// memory heap.
    ///
    /// Any of the elements may be equal to `erupt::vk::WHOLE_SIZE`, which means no limit on that
    /// heap. This is also the default in case of an empty slice.
    ///
    /// If there is a limit defined for a heap:
    ///
    /// * If user tries to allocate more memory from that heap using this allocator, the allocation
    /// fails with `erupt::vk::Result::ERROR_OUT_OF_DEVICE_MEMORY`.
    ///
    /// * If the limit is smaller than heap size reported in `erupt::vk::MemoryHeap::size`, the value of this
    /// limit will be reported instead when using `Allocator::get_memory_properties`.
    ///
    /// Warning! Using this feature may not be equivalent to installing a GPU with smaller amount of
    /// memory, because graphics driver doesn't necessary fail new allocations with
    /// `erupt::vk::Result::ERROR_OUT_OF_DEVICE_MEMORY` result when memory capacity is exceeded. It may return success
    /// and just silently migrate some device memory" blocks to system RAM. This driver behavior can
    /// also be controlled using the `VK_AMD_memory_overallocation_behavior` extension.
    pub heap_size_limits: Option<Vec<erupt::vk::DeviceSize>>,
}

// /// Construct `AllocatorCreateInfo` with default values
// ///
// /// Note that the default `device` and `instance` fields are filled with dummy
// /// implementations that will panic if used. These fields must be overwritten.
// impl Default for AllocatorCreateInfo {
//     fn default() -> Self {
//         extern "C" fn get_device_proc_addr(
//             _: erupt::vk::Instance,
//             _: *const std::os::raw::c_char,
//         ) -> *const std::os::raw::c_void {
//             std::ptr::null()
//         }
//         extern "C" fn get_instance_proc_addr(
//             _: erupt::vk::Instance,
//             _: *const std::os::raw::c_char,
//         ) -> *const std::os::raw::c_void {
//             get_device_proc_addr as *const _
//         }
//         let instance = Arc<>;
//         let device = unsafe { Arc::new(DeviceLoader::) };
//         AllocatorCreateInfo {
//             physical_device: erupt::vk::PhysicalDevice::null(),
//             device,
//             instance,
//             flags: AllocatorCreateFlags::NONE,
//             preferred_large_heap_block_size: 0,
//             frame_in_use_count: 0,
//             heap_size_limits: None,
//         }
//     }
// }

/// Converts a raw result into an erupt result.
#[inline]
fn ffi_to_result(result: ffi::VkResult) -> erupt::vk::Result {
    erupt::vk::Result(result)
}

/// Converts an `AllocationCreateInfo` struct into the raw representation.
fn allocation_create_info_to_ffi(info: &AllocationCreateInfo) -> ffi::VmaAllocationCreateInfo {
    let mut create_info: ffi::VmaAllocationCreateInfo = unsafe { mem::zeroed() };
    create_info.usage = match &info.usage {
        MemoryUsage::Unknown => ffi::VmaMemoryUsage_VMA_MEMORY_USAGE_UNKNOWN,
        MemoryUsage::GpuOnly => ffi::VmaMemoryUsage_VMA_MEMORY_USAGE_GPU_ONLY,
        MemoryUsage::CpuOnly => ffi::VmaMemoryUsage_VMA_MEMORY_USAGE_CPU_ONLY,
        MemoryUsage::CpuToGpu => ffi::VmaMemoryUsage_VMA_MEMORY_USAGE_CPU_TO_GPU,
        MemoryUsage::GpuToCpu => ffi::VmaMemoryUsage_VMA_MEMORY_USAGE_GPU_TO_CPU,
        MemoryUsage::CpuCopy => ffi::VmaMemoryUsage_VMA_MEMORY_USAGE_CPU_COPY,
        MemoryUsage::GpuLazilyAllocated => {
            ffi::VmaMemoryUsage_VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED
        }
    };
    create_info.flags = info.flags.bits();
    create_info.requiredFlags = info.required_flags.bits();
    create_info.preferredFlags = info.preferred_flags.bits();
    create_info.memoryTypeBits = info.memory_type_bits;
    create_info.pool = match &info.pool {
        Some(pool) => pool.internal,
        None => unsafe { mem::zeroed() },
    };
    create_info.pUserData = info.user_data.unwrap_or(::std::ptr::null_mut());
    create_info
}

/// Converts an `AllocatorPoolCreateInfo` struct into the raw representation.
fn pool_create_info_to_ffi(info: &AllocatorPoolCreateInfo) -> ffi::VmaPoolCreateInfo {
    let mut create_info: ffi::VmaPoolCreateInfo = unsafe { mem::zeroed() };
    create_info.memoryTypeIndex = info.memory_type_index;
    create_info.flags = info.flags.bits();
    create_info.blockSize = info.block_size as ffi::VkDeviceSize;
    create_info.minBlockCount = info.min_block_count;
    create_info.maxBlockCount = info.max_block_count;
    create_info.frameInUseCount = info.frame_in_use_count;
    create_info
}

/// Intended usage of memory.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord)]
pub enum MemoryUsage {
    /// No intended memory usage specified.
    /// Use other members of `AllocationCreateInfo` to specify your requirements.
    Unknown,

    /// Memory will be used on device only, so fast access from the device is preferred.
    /// It usually means device-local GPU (video) memory.
    /// No need to be mappable on host.
    /// It is roughly equivalent of `D3D12_HEAP_TYPE_DEFAULT`.
    ///
    /// Usage:
    ///
    /// - Resources written and read by device, e.g. images used as attachments.
    /// - Resources transferred from host once (immutable) or infrequently and read by
    ///   device multiple times, e.g. textures to be sampled, vertex buffers, uniform
    ///   (constant) buffers, and majority of other types of resources used on GPU.
    ///
    /// Allocation may still end up in `erupt::vk::MemoryPropertyFlags::HOST_VISIBLE` memory on some implementations.
    /// In such case, you are free to map it.
    /// You can use `AllocationCreateFlags::MAPPED` with this usage type.
    GpuOnly,

    /// Memory will be mappable on host.
    /// It usually means CPU (system) memory.
    /// Guarantees to be `erupt::vk::MemoryPropertyFlags::HOST_VISIBLE` and `erupt::vk::MemoryPropertyFlags::HOST_COHERENT`.
    /// CPU access is typically uncached. Writes may be write-combined.
    /// Resources created in this pool may still be accessible to the device, but access to them can be slow.
    /// It is roughly equivalent of `D3D12_HEAP_TYPE_UPLOAD`.
    ///
    /// Usage: Staging copy of resources used as transfer source.
    CpuOnly,

    /// Memory that is both mappable on host (guarantees to be `erupt::vk::MemoryPropertyFlags::HOST_VISIBLE`) and preferably fast to access by GPU.
    /// CPU access is typically uncached. Writes may be write-combined.
    ///
    /// Usage: Resources written frequently by host (dynamic), read by device. E.g. textures, vertex buffers,
    /// uniform buffers updated every frame or every draw call.
    CpuToGpu,

    /// Memory mappable on host (guarantees to be `erupt::vk::MemoryPropertFlags::HOST_VISIBLE`) and cached.
    /// It is roughly equivalent of `D3D12_HEAP_TYPE_READBACK`.
    ///
    /// Usage:
    ///
    /// - Resources written by device, read by host - results of some computations, e.g. screen capture, average scene luminance for HDR tone mapping.
    /// - Any resources read or accessed randomly on host, e.g. CPU-side copy of vertex buffer used as source of transfer, but also used for collision detection.
    GpuToCpu,

    /// CPU memory - memory that is preferably not `DEVICE_LOCAL`, but also not guaranteed to be `HOST_VISIBLE`.
    ///
    /// Usage: Staging copy of resources moved from GPU memory to CPU memory as part
    /// of custom paging/residency mechanism, to be moved back to GPU memory when needed.
    CpuCopy,

    /// Lazily allocated GPU memory having `VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT`.
    /// Exists mostly on mobile platforms. Using it on desktop PC or other GPUs with no such memory type present will fail the allocation.
    ///
    /// Usage: Memory for transient attachment images (color attachments, depth attachments etc.), created with `VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT`.
    ///
    /// Allocations with this usage are always created as dedicated - it implies #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
    GpuLazilyAllocated,
}

bitflags! {
    /// Flags for configuring `AllocatorPool` construction.
    pub struct AllocatorPoolCreateFlags: u32 {
        const NONE = 0x0000_0000;

        /// Use this flag if you always allocate only buffers and linear images or only optimal images
        /// out of this pool and so buffer-image granularity can be ignored.
        ///
        /// This is an optional optimization flag.
        ///
        /// If you always allocate using `Allocator::create_buffer`, `Allocator::create_image`,
        /// `Allocator::allocate_memory_for_buffer`, then you don't need to use it because allocator
        /// knows exact type of your allocations so it can handle buffer-image granularity
        /// in the optimal way.
        ///
        /// If you also allocate using `Allocator::allocate_memory_for_image` or `Allocator::allocate_memory`,
        /// exact type of such allocations is not known, so allocator must be conservative
        /// in handling buffer-image granularity, which can lead to suboptimal allocation
        /// (wasted memory). In that case, if you can make sure you always allocate only
        /// buffers and linear images or only optimal images out of this pool, use this flag
        /// to make allocator disregard buffer-image granularity and so make allocations
        /// faster and more optimal.
        const IGNORE_BUFFER_IMAGE_GRANULARITY = 0x0000_0002;

        /// Enables alternative, linear allocation algorithm in this pool.
        ///
        /// Specify this flag to enable linear allocation algorithm, which always creates
        /// new allocations after last one and doesn't reuse space from allocations freed in
        /// between. It trades memory consumption for simplified algorithm and data
        /// structure, which has better performance and uses less memory for metadata.
        ///
        /// By using this flag, you can achieve behavior of free-at-once, stack,
        /// ring buffer, and double stack.
        ///
        /// When using this flag, you must specify PoolCreateInfo::max_block_count == 1 (or 0 for default).
        const LINEAR_ALGORITHM = 0x0000_0004;

        /// Enables alternative, buddy allocation algorithm in this pool.
        ///
        /// It operates on a tree of blocks, each having size that is a power of two and
        /// a half of its parent's size. Comparing to default algorithm, this one provides
        /// faster allocation and deallocation and decreased external fragmentation,
        /// at the expense of more memory wasted (internal fragmentation).
        const BUDDY_ALGORITHM = 0x0000_0008;

        /// Bit mask to extract only `*_ALGORITHM` bits from entire set of flags.
        const ALGORITHM_MASK = 0x0000_0004 | 0x0000_0008;
    }
}

bitflags! {
    /// Flags for configuring `Allocation` construction.
    pub struct AllocationCreateFlags: u32 {
        /// Default configuration for allocation.
        const NONE = 0x0000_0000;

        /// Set this flag if the allocation should have its own memory block.
        ///
        /// Use it for special, big resources, like fullscreen images used as attachments.
        ///
        /// You should not use this flag if `AllocationCreateInfo::pool` is not `None`.
        const DEDICATED_MEMORY = 0x0000_0001;

        /// Set this flag to only try to allocate from existing `erupt::vk::DeviceMemory` blocks and never create new such block.
        ///
        /// If new allocation cannot be placed in any of the existing blocks, allocation
        /// fails with `erupt::vk::Result::ERROR_OUT_OF_DEVICE_MEMORY` error.
        ///
        /// You should not use `AllocationCreateFlags::DEDICATED_MEMORY` and `AllocationCreateFlags::NEVER_ALLOCATE` at the same time. It makes no sense.
        ///
        /// If `AllocationCreateInfo::pool` is not `None`, this flag is implied and ignored.
        const NEVER_ALLOCATE = 0x0000_0002;

        /// Set this flag to use a memory that will be persistently mapped and retrieve pointer to it.
        ///
        /// Pointer to mapped memory will be returned through `Allocation::get_mapped_data()`.
        ///
        /// Is it valid to use this flag for allocation made from memory type that is not
        /// `erupt::vk::MemoryPropertyFlags::HOST_VISIBLE`. This flag is then ignored and memory is not mapped. This is
        /// useful if you need an allocation that is efficient to use on GPU
        /// (`erupt::vk::MemoryPropertyFlags::DEVICE_LOCAL`) and still want to map it directly if possible on platforms that
        /// support it (e.g. Intel GPU).
        ///
        /// You should not use this flag together with `AllocationCreateFlags::CAN_BECOME_LOST`.
        const MAPPED = 0x0000_0004;

        /// Allocation created with this flag can become lost as a result of another
        /// allocation with `AllocationCreateFlags::CAN_MAKE_OTHER_LOST` flag, so you must check it before use.
        ///
        /// To check if allocation is not lost, call `Allocator::get_allocation_info` and check if
        /// `AllocationInfo::device_memory` is not null.
        ///
        /// You should not use this flag together with `AllocationCreateFlags::MAPPED`.
        const CAN_BECOME_LOST = 0x0000_0008;

        /// While creating allocation using this flag, other allocations that were
        /// created with flag `AllocationCreateFlags::CAN_BECOME_LOST` can become lost.
        const CAN_MAKE_OTHER_LOST = 0x0000_0010;

        /// Set this flag to treat `AllocationCreateInfo::user_data` as pointer to a
        /// null-terminated string. Instead of copying pointer value, a local copy of the
        /// string is made and stored in allocation's user data. The string is automatically
        /// freed together with the allocation. It is also used in `Allocator::build_stats_string`.
        const USER_DATA_COPY_STRING = 0x0000_0020;

        /// Allocation will be created from upper stack in a double stack pool.
        ///
        /// This flag is only allowed for custom pools created with `AllocatorPoolCreateFlags::LINEAR_ALGORITHM` flag.
        const UPPER_ADDRESS = 0x0000_0040;

        /// Create both buffer/image and allocation, but don't bind them together.
        /// It is useful when you want to bind yourself to do some more advanced binding, e.g. using some extensions.
        /// The flag is meaningful only with functions that bind by default, such as `Allocator::create_buffer`
        /// or `Allocator::create_image`. Otherwise it is ignored.
        const CREATE_DONT_BIND = 0x0000_0080;

        /// Allocation strategy that chooses smallest possible free range for the
        /// allocation.
        const STRATEGY_BEST_FIT = 0x0001_0000;

        /// Allocation strategy that chooses biggest possible free range for the
        /// allocation.
        const STRATEGY_WORST_FIT = 0x0002_0000;

        /// Allocation strategy that chooses first suitable free range for the
        /// allocation.
        ///
        /// "First" doesn't necessarily means the one with smallest offset in memory,
        /// but rather the one that is easiest and fastest to find.
        const STRATEGY_FIRST_FIT = 0x0004_0000;

        /// Allocation strategy that tries to minimize memory usage.
        const STRATEGY_MIN_MEMORY = 0x0001_0000;

        /// Allocation strategy that tries to minimize allocation time.
        const STRATEGY_MIN_TIME = 0x0004_0000;

        /// Allocation strategy that tries to minimize memory fragmentation.
        const STRATEGY_MIN_FRAGMENTATION = 0x0002_0000;

        /// A bit mask to extract only `*_STRATEGY` bits from entire set of flags.
        const STRATEGY_MASK = 0x0001_0000 | 0x0002_0000 | 0x0004_0000;
    }
}

/// Description of an `Allocation` to be created.
#[derive(Debug, Clone)]
pub struct AllocationCreateInfo {
    /// Intended usage of memory.
    ///
    /// You can leave `MemoryUsage::UNKNOWN` if you specify memory requirements
    /// in another way.
    ///
    /// If `pool` is not `None`, this member is ignored.
    pub usage: MemoryUsage,

    /// Flags for configuring the allocation
    pub flags: AllocationCreateFlags,

    /// Flags that must be set in a Memory Type chosen for an allocation.
    ///
    /// Leave 0 if you specify memory requirements in other way.
    ///
    /// If `pool` is not `None`, this member is ignored.
    pub required_flags: erupt::vk::MemoryPropertyFlags,

    /// Flags that preferably should be set in a memory type chosen for an allocation.
    ///
    /// Set to 0 if no additional flags are prefered.
    ///
    /// If `pool` is not `None`, this member is ignored.
    pub preferred_flags: erupt::vk::MemoryPropertyFlags,

    /// Bit mask containing one bit set for every memory type acceptable for this allocation.
    ///
    /// Value 0 is equivalent to `std::u32::MAX` - it means any memory type is accepted if
    /// it meets other requirements specified by this structure, with no further restrictions
    /// on memory type index.
    ///
    /// If `pool` is not `None`, this member is ignored.
    pub memory_type_bits: u32,

    /// Pool that this allocation should be created in.
    ///
    /// Specify `None` to allocate from default pool. If not `None`, members:
    /// `usage`, `required_flags`, `preferred_flags`, `memory_type_bits` are ignored.
    pub pool: Option<AllocatorPool>,

    /// Custom general-purpose pointer that will be stored in `Allocation`, can be read
    /// as `Allocation::get_user_data()` and changed using `Allocator::set_allocation_user_data`.
    ///
    /// If `AllocationCreateFlags::USER_DATA_COPY_STRING` is used, it must be either null or pointer to a
    /// null-terminated string. The string will be then copied to internal buffer, so it
    /// doesn't need to be valid after allocation call.
    pub user_data: Option<*mut ::std::os::raw::c_void>,
}

/// Construct `AllocationCreateInfo` with default values
impl Default for AllocationCreateInfo {
    fn default() -> Self {
        AllocationCreateInfo {
            usage: MemoryUsage::Unknown,
            flags: AllocationCreateFlags::NONE,
            required_flags: erupt::vk::MemoryPropertyFlags::empty(),
            preferred_flags: erupt::vk::MemoryPropertyFlags::empty(),
            memory_type_bits: 0,
            pool: None,
            user_data: None,
        }
    }
}

/// Description of an `AllocationPool` to be created.
#[derive(Debug, Clone)]
pub struct AllocatorPoolCreateInfo {
    /// Vulkan memory type index to allocate this pool from.
    pub memory_type_index: u32,

    /// Use combination of `AllocatorPoolCreateFlags`
    pub flags: AllocatorPoolCreateFlags,

    /// Size of a single `erupt::vk::DeviceMemory` block to be allocated as part of this
    /// pool, in bytes.
    ///
    /// Specify non-zero to set explicit, constant size of memory blocks used by
    /// this pool.
    ///
    /// Leave 0 to use default and let the library manage block sizes automatically.
    /// Sizes of particular blocks may vary.
    pub block_size: usize,

    /// Minimum number of blocks to be always allocated in this pool, even if they stay empty.
    ///
    /// Set to 0 to have no preallocated blocks and allow the pool be completely empty.
    pub min_block_count: usize,

    /// Maximum number of blocks that can be allocated in this pool.
    ///
    /// Set to 0 to use default, which is no limit.
    ///
    /// Set to same value as `AllocatorPoolCreateInfo::min_block_count` to have fixed amount
    /// of memory allocated throughout whole lifetime of this pool.
    pub max_block_count: usize,

    /// Maximum number of additional frames that are in use at the same time as current frame.
    /// This value is used only when you make allocations with `AllocationCreateFlags::CAN_BECOME_LOST` flag.
    /// Such allocations cannot become lost if:
    ///   `allocation.lastUseFrameIndex >= allocator.currentFrameIndex - frameInUseCount`.
    ///
    /// For example, if you double-buffer your command buffers, so resources used for rendering
    /// in previous frame may still be in use by the GPU at the moment you allocate resources
    /// needed for the current frame, set this value to 1.
    ///
    /// If you want to allow any allocations other than used in the current frame to become lost,
    /// set this value to 0.
    pub frame_in_use_count: u32,
}

/// Construct `AllocatorPoolCreateInfo` with default values
impl Default for AllocatorPoolCreateInfo {
    fn default() -> Self {
        AllocatorPoolCreateInfo {
            memory_type_index: 0,
            flags: AllocatorPoolCreateFlags::NONE,
            block_size: 0,
            min_block_count: 0,
            max_block_count: 0,
            frame_in_use_count: 0,
        }
    }
}

#[derive(Debug)]
pub struct DefragmentationContext {
    pub(crate) internal: ffi::VmaDefragmentationContext,
    pub(crate) stats: Box<ffi::VmaDefragmentationStats>,
    pub(crate) changed: Vec<erupt::vk::Bool32>,
}

/// Optional configuration parameters to be passed to `Allocator::defragment`
///
/// DEPRECATED.
#[derive(Debug, Copy, Clone)]
pub struct DefragmentationInfo {
    /// Maximum total numbers of bytes that can be copied while moving
    /// allocations to different places.
    ///
    /// Default is `erupt::vk::WHOLE_SIZE`, which means no limit.
    pub max_bytes_to_move: usize,

    /// Maximum number of allocations that can be moved to different place.
    ///
    /// Default is `std::u32::MAX`, which means no limit.
    pub max_allocations_to_move: u32,
}

/// Construct `DefragmentationInfo` with default values
impl Default for DefragmentationInfo {
    fn default() -> Self {
        DefragmentationInfo {
            max_bytes_to_move: erupt::vk::WHOLE_SIZE as usize,
            max_allocations_to_move: std::u32::MAX,
        }
    }
}

/// Parameters for defragmentation.
///
/// To be used with function `Allocator::defragmentation_begin`.
#[derive(Debug, Clone)]
pub struct DefragmentationInfo2<'a> {
    /// Collection of allocations that can be defragmented.
    ///
    /// Elements in the slice should be unique - same allocation cannot occur twice.
    /// It is safe to pass allocations that are in the lost state - they are ignored.
    /// All allocations not present in this slice are considered non-moveable during this defragmentation.
    pub allocations: &'a [Allocation],

    /// Either `None` or a slice of pools to be defragmented.
    ///
    /// All the allocations in the specified pools can be moved during defragmentation
    /// and there is no way to check if they were really moved as in `allocations_changed`,
    /// so you must query all the allocations in all these pools for new `erupt::vk::DeviceMemory`
    /// and offset using `Allocator::get_allocation_info` if you might need to recreate buffers
    /// and images bound to them.
    ///
    /// Elements in the array should be unique - same pool cannot occur twice.
    ///
    /// Using this array is equivalent to specifying all allocations from the pools in `allocations`.
    /// It might be more efficient.
    pub pools: Option<&'a [AllocatorPool]>,

    /// Maximum total numbers of bytes that can be copied while moving allocations to different places using transfers on CPU side, like `memcpy()`, `memmove()`.
    ///
    /// `erupt::vk::WHOLE_SIZE` means no limit.
    pub max_cpu_bytes_to_move: erupt::vk::DeviceSize,

    /// Maximum number of allocations that can be moved to a different place using transfers on CPU side, like `memcpy()`, `memmove()`.
    ///
    /// `std::u32::MAX` means no limit.
    pub max_cpu_allocations_to_move: u32,

    /// Maximum total numbers of bytes that can be copied while moving allocations to different places using transfers on GPU side, posted to `command_buffer`.
    ///
    /// `erupt::vk::WHOLE_SIZE` means no limit.
    pub max_gpu_bytes_to_move: erupt::vk::DeviceSize,

    /// Maximum number of allocations that can be moved to a different place using transfers on GPU side, posted to `command_buffer`.
    ///
    /// `std::u32::MAX` means no limit.
    pub max_gpu_allocations_to_move: u32,

    /// Command buffer where GPU copy commands will be posted.
    ///
    /// If not `None`, it must be a valid command buffer handle that supports transfer queue type.
    /// It must be in the recording state and outside of a render pass instance.
    /// You need to submit it and make sure it finished execution before calling `Allocator::defragmentation_end`.
    ///
    /// Passing `None` means that only CPU defragmentation will be performed.
    pub command_buffer: Option<erupt::vk::CommandBuffer>,
}

/// Statistics returned by `Allocator::defragment`
#[derive(Debug, Copy, Clone)]
pub struct DefragmentationStats {
    /// Total number of bytes that have been copied while moving allocations to different places.
    pub bytes_moved: usize,

    /// Total number of bytes that have been released to the system by freeing empty `erupt::vk::DeviceMemory` objects.
    pub bytes_freed: usize,

    /// Number of allocations that have been moved to different places.
    pub allocations_moved: u32,

    /// Number of empty `erupt::vk::DeviceMemory` objects that have been released to the system.
    pub device_memory_blocks_freed: u32,
}

impl Allocator {
    /// Constructor a new `Allocator` using the provided options.
    pub fn new(create_info: &AllocatorCreateInfo) -> Result<Self> {
        let instance = create_info.instance.clone();
        let device = create_info.device.clone();
        let routed_functions = unsafe {
            ffi::VmaVulkanFunctions {
                vkGetPhysicalDeviceProperties: mem::transmute::<
                    _,
                    ffi::PFN_vkGetPhysicalDeviceProperties,
                >(
                    instance.get_physical_device_properties
                ),
                vkGetPhysicalDeviceMemoryProperties: mem::transmute::<
                    _,
                    ffi::PFN_vkGetPhysicalDeviceMemoryProperties,
                >(
                    instance.get_physical_device_memory_properties,
                ),
                vkAllocateMemory: mem::transmute::<_, ffi::PFN_vkAllocateMemory>(
                    device.allocate_memory,
                ),
                vkFreeMemory: mem::transmute::<_, ffi::PFN_vkFreeMemory>(device.free_memory),
                vkMapMemory: mem::transmute::<_, ffi::PFN_vkMapMemory>(device.map_memory),
                vkUnmapMemory: mem::transmute::<_, ffi::PFN_vkUnmapMemory>(device.unmap_memory),
                vkFlushMappedMemoryRanges: mem::transmute::<_, ffi::PFN_vkFlushMappedMemoryRanges>(
                    device.flush_mapped_memory_ranges,
                ),
                vkInvalidateMappedMemoryRanges: mem::transmute::<
                    _,
                    ffi::PFN_vkInvalidateMappedMemoryRanges,
                >(
                    device.invalidate_mapped_memory_ranges
                ),
                vkBindBufferMemory: mem::transmute::<_, ffi::PFN_vkBindBufferMemory>(
                    device.bind_buffer_memory,
                ),
                vkBindBufferMemory2KHR: mem::transmute::<_, ffi::PFN_vkBindBufferMemory2KHR>(
                    device.bind_buffer_memory2,
                ),
                vkBindImageMemory: mem::transmute::<_, ffi::PFN_vkBindImageMemory>(
                    device.bind_image_memory,
                ),
                vkBindImageMemory2KHR: mem::transmute::<_, ffi::PFN_vkBindImageMemory2KHR>(
                    device.bind_image_memory2,
                ),
                vkGetBufferMemoryRequirements: mem::transmute::<
                    _,
                    ffi::PFN_vkGetBufferMemoryRequirements,
                >(
                    device.get_buffer_memory_requirements
                ),
                vkGetImageMemoryRequirements: mem::transmute::<
                    _,
                    ffi::PFN_vkGetImageMemoryRequirements,
                >(
                    device.get_image_memory_requirements
                ),
                vkCreateBuffer: mem::transmute::<_, ffi::PFN_vkCreateBuffer>(device.create_buffer),
                vkDestroyBuffer: mem::transmute::<_, ffi::PFN_vkDestroyBuffer>(
                    device.destroy_buffer,
                ),
                vkCreateImage: mem::transmute::<_, ffi::PFN_vkCreateImage>(device.create_image),
                vkDestroyImage: mem::transmute::<_, ffi::PFN_vkDestroyImage>(device.destroy_image),
                vkCmdCopyBuffer: mem::transmute::<_, ffi::PFN_vkCmdCopyBuffer>(
                    device.cmd_copy_buffer,
                ),
                vkGetBufferMemoryRequirements2KHR: mem::transmute::<
                    _,
                    ffi::PFN_vkGetBufferMemoryRequirements2KHR,
                >(
                    device.get_buffer_memory_requirements2
                ),
                vkGetImageMemoryRequirements2KHR: mem::transmute::<
                    _,
                    ffi::PFN_vkGetImageMemoryRequirements2KHR,
                >(
                    device.get_image_memory_requirements2
                ),
                // TODO:
                vkGetPhysicalDeviceMemoryProperties2KHR: None,
                /*vkGetPhysicalDeviceMemoryProperties2KHR: mem::transmute::<
                    _,
                    ffi::PFN_vkGetPhysicalDeviceMemoryProperties2KHR,
                >(Some(
                    device.fp_v1_1().get_physical_device_memory_properties2,
                )),*/
            }
        };
        let ffi_create_info = ffi::VmaAllocatorCreateInfo {
            physicalDevice: create_info.physical_device.object_handle() as ffi::VkPhysicalDevice,
            device: create_info.device.handle.object_handle() as ffi::VkDevice,
            instance: instance.handle.object_handle() as ffi::VkInstance,
            flags: create_info.flags.bits(),
            frameInUseCount: create_info.frame_in_use_count,
            preferredLargeHeapBlockSize: create_info.preferred_large_heap_block_size as u64,
            pHeapSizeLimit: match &create_info.heap_size_limits {
                None => ::std::ptr::null(),
                Some(limits) => limits.as_ptr(),
            },
            pVulkanFunctions: &routed_functions,
            pAllocationCallbacks: ::std::ptr::null(), // TODO: Add support
            pDeviceMemoryCallbacks: ::std::ptr::null(), // TODO: Add support
            pRecordSettings: ::std::ptr::null(),      // TODO: Add support
            vulkanApiVersion: 0,
            pTypeExternalMemoryHandleTypes: ::std::ptr::null(), // TODO: Make configurable
        };
        let mut internal: ffi::VmaAllocator = unsafe { mem::zeroed() };
        let result = ffi_to_result(unsafe {
            ffi::vmaCreateAllocator(
                &ffi_create_info as *const ffi::VmaAllocatorCreateInfo,
                &mut internal,
            )
        });
        match result {
            erupt::vk::Result::SUCCESS => Ok(Allocator {
                internal,
                instance,
                device,
            }),
            _ => Err(Error::vulkan(result)),
        }
    }

    /// The allocator fetches `erupt::vk::PhysicalDeviceProperties` from the physical device.
    /// You can get it here, without fetching it again on your own.
    pub fn get_physical_device_properties(&self) -> Result<erupt::vk::PhysicalDeviceProperties> {
        let mut ffi_properties: *const ffi::VkPhysicalDeviceProperties = unsafe { mem::zeroed() };
        Ok(unsafe {
            ffi::vmaGetPhysicalDeviceProperties(self.internal, &mut ffi_properties);
            mem::transmute::<ffi::VkPhysicalDeviceProperties, erupt::vk::PhysicalDeviceProperties>(
                *ffi_properties,
            )
        })
    }

    /// The allocator fetches `erupt::vk::PhysicalDeviceMemoryProperties` from the physical device.
    /// You can get it here, without fetching it again on your own.
    pub fn get_memory_properties(&self) -> Result<erupt::vk::PhysicalDeviceMemoryProperties> {
        let mut ffi_properties: *const ffi::VkPhysicalDeviceMemoryProperties =
            unsafe { mem::zeroed() };
        Ok(unsafe {
            ffi::vmaGetMemoryProperties(self.internal, &mut ffi_properties);
            mem::transmute::<
                ffi::VkPhysicalDeviceMemoryProperties,
                erupt::vk::PhysicalDeviceMemoryProperties,
            >(*ffi_properties)
        })
    }

    /// Given a memory type index, returns `erupt::vk::MemoryPropertyFlags` of this memory type.
    ///
    /// This is just a convenience function; the same information can be obtained using
    /// `Allocator::get_memory_properties`.
    pub fn get_memory_type_properties(
        &self,
        memory_type_index: u32,
    ) -> Result<erupt::vk::MemoryPropertyFlags> {
        let mut ffi_properties: ffi::VkMemoryPropertyFlags = unsafe { mem::zeroed() };
        Ok(unsafe {
            ffi::vmaGetMemoryTypeProperties(self.internal, memory_type_index, &mut ffi_properties);
            mem::transmute::<ffi::VkMemoryPropertyFlags, erupt::vk::MemoryPropertyFlags>(
                ffi_properties,
            )
        })
    }

    /// Sets index of the current frame.
    ///
    /// This function must be used if you make allocations with `AllocationCreateFlags::CAN_BECOME_LOST` and
    /// `AllocationCreateFlags::CAN_MAKE_OTHER_LOST` flags to inform the allocator when a new frame begins.
    /// Allocations queried using `Allocator::get_allocation_info` cannot become lost
    /// in the current frame.
    pub fn set_current_frame_index(&self, frame_index: u32) {
        unsafe {
            ffi::vmaSetCurrentFrameIndex(self.internal, frame_index);
        }
    }

    /// Retrieves statistics from current state of the `Allocator`.
    pub fn calculate_stats(&self) -> Result<ffi::VmaStats> {
        let mut vma_stats: ffi::VmaStats = unsafe { mem::zeroed() };
        unsafe {
            ffi::vmaCalculateStats(self.internal, &mut vma_stats);
        }
        Ok(vma_stats)
    }

    /// Builds and returns statistics in `JSON` format.
    pub fn build_stats_string(&self, detailed_map: bool) -> Result<String> {
        let mut stats_string: *mut ::std::os::raw::c_char = ::std::ptr::null_mut();
        unsafe {
            ffi::vmaBuildStatsString(
                self.internal,
                &mut stats_string,
                if detailed_map { 1 } else { 0 },
            );
        }
        Ok(if stats_string.is_null() {
            String::new()
        } else {
            let result = unsafe {
                std::ffi::CStr::from_ptr(stats_string)
                    .to_string_lossy()
                    .into_owned()
            };
            unsafe {
                ffi::vmaFreeStatsString(self.internal, stats_string);
            }
            result
        })
    }

    /// Helps to find memory type index, given memory type bits and allocation info.
    ///
    /// This algorithm tries to find a memory type that:
    ///
    /// - Is allowed by memory type bits.
    /// - Contains all the flags from `allocation_info.required_flags`.
    /// - Matches intended usage.
    /// - Has as many flags from `allocation_info.preferred_flags` as possible.
    ///
    /// Returns erupt::vk::Result::ERROR_FEATURE_NOT_PRESENT if not found. Receiving such a result
    /// from this function or any other allocating function probably means that your
    /// device doesn't support any memory type with requested features for the specific
    /// type of resource you want to use it for. Please check parameters of your
    /// resource, like image layout (OPTIMAL versus LINEAR) or mip level count.
    pub fn find_memory_type_index(
        &self,
        memory_type_bits: u32,
        allocation_info: &AllocationCreateInfo,
    ) -> Result<u32> {
        let create_info = allocation_create_info_to_ffi(&allocation_info);
        let mut memory_type_index: u32 = 0;
        let result = ffi_to_result(unsafe {
            ffi::vmaFindMemoryTypeIndex(
                self.internal,
                memory_type_bits,
                &create_info,
                &mut memory_type_index,
            )
        });
        match result {
            erupt::vk::Result::SUCCESS => Ok(memory_type_index),
            _ => Err(Error::vulkan(result)),
        }
    }

    /// Helps to find memory type index, given buffer info and allocation info.
    ///
    /// It can be useful e.g. to determine value to be used as `AllocatorPoolCreateInfo::memory_type_index`.
    /// It internally creates a temporary, dummy buffer that never has memory bound.
    /// It is just a convenience function, equivalent to calling:
    ///
    /// - `erupt::vk::Device::create_buffer`
    /// - `erupt::vk::Device::get_buffer_memory_requirements`
    /// - `Allocator::find_memory_type_index`
    /// - `erupt::vk::Device::destroy_buffer`
    pub fn find_memory_type_index_for_buffer_info(
        &self,
        buffer_info: &erupt::vk::BufferCreateInfo,
        allocation_info: &AllocationCreateInfo,
    ) -> Result<u32> {
        let allocation_create_info = allocation_create_info_to_ffi(&allocation_info);
        let buffer_create_info = unsafe {
            mem::transmute::<erupt::vk::BufferCreateInfo, ffi::VkBufferCreateInfo>(*buffer_info)
        };
        let mut memory_type_index: u32 = 0;
        let result = ffi_to_result(unsafe {
            ffi::vmaFindMemoryTypeIndexForBufferInfo(
                self.internal,
                &buffer_create_info,
                &allocation_create_info,
                &mut memory_type_index,
            )
        });
        match result {
            erupt::vk::Result::SUCCESS => Ok(memory_type_index),
            _ => Err(Error::vulkan(result)),
        }
    }

    /// Helps to find memory type index, given image info and allocation info.
    ///
    /// It can be useful e.g. to determine value to be used as `AllocatorPoolCreateInfo::memory_type_index`.
    /// It internally creates a temporary, dummy image that never has memory bound.
    /// It is just a convenience function, equivalent to calling:
    ///
    /// - `erupt::vk::Device::create_image`
    /// - `erupt::vk::Device::get_image_memory_requirements`
    /// - `Allocator::find_memory_type_index`
    /// - `erupt::vk::Device::destroy_image`
    pub fn find_memory_type_index_for_image_info(
        &self,
        image_info: &erupt::vk::ImageCreateInfo,
        allocation_info: &AllocationCreateInfo,
    ) -> Result<u32> {
        let allocation_create_info = allocation_create_info_to_ffi(&allocation_info);
        let image_create_info = unsafe {
            mem::transmute::<erupt::vk::ImageCreateInfo, ffi::VkImageCreateInfo>(*image_info)
        };
        let mut memory_type_index: u32 = 0;
        let result = ffi_to_result(unsafe {
            ffi::vmaFindMemoryTypeIndexForImageInfo(
                self.internal,
                &image_create_info,
                &allocation_create_info,
                &mut memory_type_index,
            )
        });
        match result {
            erupt::vk::Result::SUCCESS => Ok(memory_type_index),
            _ => Err(Error::vulkan(result)),
        }
    }

    /// Allocates Vulkan device memory and creates `AllocatorPool` object.
    pub fn create_pool(&self, pool_info: &AllocatorPoolCreateInfo) -> Result<AllocatorPool> {
        let mut ffi_pool: ffi::VmaPool = unsafe { mem::zeroed() };
        let create_info = pool_create_info_to_ffi(&pool_info);
        let result = ffi_to_result(unsafe {
            ffi::vmaCreatePool(self.internal, &create_info, &mut ffi_pool)
        });
        match result {
            erupt::vk::Result::SUCCESS => Ok(AllocatorPool { internal: ffi_pool }),
            _ => Err(Error::vulkan(result)),
        }
    }

    /// Destroys `AllocatorPool` object and frees Vulkan device memory.
    pub fn destroy_pool(&self, pool: &AllocatorPool) {
        unsafe {
            ffi::vmaDestroyPool(self.internal, pool.internal);
        }
    }

    /// Retrieves statistics of existing `AllocatorPool` object.
    pub fn get_pool_stats(&self, pool: &AllocatorPool) -> Result<ffi::VmaPoolStats> {
        let mut pool_stats: ffi::VmaPoolStats = unsafe { mem::zeroed() };
        unsafe {
            ffi::vmaGetPoolStats(self.internal, pool.internal, &mut pool_stats);
        }
        Ok(pool_stats)
    }

    /// Marks all allocations in given pool as lost if they are not used in current frame
    /// or AllocatorPoolCreateInfo::frame_in_use_count` back from now.
    ///
    /// Returns the number of allocations marked as lost.
    pub fn make_pool_allocations_lost(&self, pool: &mut AllocatorPool) -> Result<usize> {
        let mut lost_count: usize = 0;
        unsafe {
            ffi::vmaMakePoolAllocationsLost(self.internal, pool.internal, &mut lost_count);
        }
        Ok(lost_count as usize)
    }

    /// Checks magic number in margins around all allocations in given memory pool in search for corruptions.
    ///
    /// Corruption detection is enabled only when `VMA_DEBUG_DETECT_CORRUPTION` macro is defined to nonzero,
    /// `VMA_DEBUG_MARGIN` is defined to nonzero and the pool is created in memory type that is
    /// `erupt::vk::MemoryPropertyFlags::HOST_VISIBLE` and `erupt::vk::MemoryPropertyFlags::HOST_COHERENT`.
    ///
    /// Possible error values:
    ///
    /// - `erupt::vk::Result::ERROR_FEATURE_NOT_PRESENT` - corruption detection is not enabled for specified pool.
    /// - `erupt::vk::Result::ERROR_VALIDATION_FAILED_EXT` - corruption detection has been performed and found memory corruptions around one of the allocations.
    ///   `VMA_ASSERT` is also fired in that case.
    /// - Other value: Error returned by Vulkan, e.g. memory mapping failure.
    pub fn check_pool_corruption(&self, pool: &AllocatorPool) -> Result<()> {
        let result =
            ffi_to_result(unsafe { ffi::vmaCheckPoolCorruption(self.internal, pool.internal) });
        match result {
            erupt::vk::Result::SUCCESS => Ok(()),
            _ => Err(Error::vulkan(result)),
        }
    }

    /// General purpose memory allocation.
    ///
    /// You should free the memory using `Allocator::free_memory` or 'Allocator::free_memory_pages'.
    ///
    /// It is recommended to use `Allocator::allocate_memory_for_buffer`, `Allocator::allocate_memory_for_image`,
    /// `Allocator::create_buffer`, `Allocator::create_image` instead whenever possible.
    pub fn allocate_memory(
        &self,
        memory_requirements: &erupt::vk::MemoryRequirements,
        allocation_info: &AllocationCreateInfo,
    ) -> Result<(Allocation, AllocationInfo)> {
        let ffi_requirements = unsafe {
            mem::transmute::<erupt::vk::MemoryRequirements, ffi::VkMemoryRequirements>(
                *memory_requirements,
            )
        };
        let create_info = allocation_create_info_to_ffi(&allocation_info);
        let mut allocation: Allocation = unsafe { mem::zeroed() };
        let mut allocation_info: AllocationInfo = unsafe { mem::zeroed() };
        let result = ffi_to_result(unsafe {
            ffi::vmaAllocateMemory(
                self.internal,
                &ffi_requirements,
                &create_info,
                &mut allocation.internal,
                &mut allocation_info.internal,
            )
        });
        match result {
            erupt::vk::Result::SUCCESS => Ok((allocation, allocation_info)),
            _ => Err(Error::vulkan(result)),
        }
    }

    /// General purpose memory allocation for multiple allocation objects at once.
    ///
    /// You should free the memory using `Allocator::free_memory` or `Allocator::free_memory_pages`.
    ///
    /// Word "pages" is just a suggestion to use this function to allocate pieces of memory needed for sparse binding.
    /// It is just a general purpose allocation function able to make multiple allocations at once.
    /// It may be internally optimized to be more efficient than calling `Allocator::allocate_memory` `allocations.len()` times.
    ///
    /// All allocations are made using same parameters. All of them are created out of the same memory pool and type.
    pub fn allocate_memory_pages(
        &self,
        memory_requirements: &erupt::vk::MemoryRequirements,
        allocation_info: &AllocationCreateInfo,
        allocation_count: usize,
    ) -> Result<Vec<(Allocation, AllocationInfo)>> {
        let ffi_requirements = unsafe {
            mem::transmute::<erupt::vk::MemoryRequirements, ffi::VkMemoryRequirements>(
                *memory_requirements,
            )
        };
        let create_info = allocation_create_info_to_ffi(&allocation_info);
        let mut allocations: Vec<ffi::VmaAllocation> =
            vec![unsafe { mem::zeroed() }; allocation_count];
        let mut allocation_info: Vec<ffi::VmaAllocationInfo> =
            vec![unsafe { mem::zeroed() }; allocation_count];
        let result = ffi_to_result(unsafe {
            ffi::vmaAllocateMemoryPages(
                self.internal,
                &ffi_requirements,
                &create_info,
                allocation_count,
                allocations.as_mut_ptr(),
                allocation_info.as_mut_ptr(),
            )
        });
        match result {
            erupt::vk::Result::SUCCESS => {
                let it = allocations.iter().zip(allocation_info.iter());
                let allocations: Vec<(Allocation, AllocationInfo)> = it
                    .map(|(alloc, info)| {
                        (
                            Allocation { internal: *alloc },
                            AllocationInfo { internal: *info },
                        )
                    })
                    .collect();
                Ok(allocations)
            }
            _ => Err(Error::vulkan(result)),
        }
    }

    /// Buffer specialized memory allocation.
    ///
    /// You should free the memory using `Allocator::free_memory` or 'Allocator::free_memory_pages'.
    pub fn allocate_memory_for_buffer(
        &self,
        buffer: erupt::vk::Buffer,
        allocation_info: &AllocationCreateInfo,
    ) -> Result<(Allocation, AllocationInfo)> {
        let ffi_buffer = buffer.object_handle() as ffi::VkBuffer;
        let create_info = allocation_create_info_to_ffi(&allocation_info);
        let mut allocation: Allocation = unsafe { mem::zeroed() };
        let mut allocation_info: AllocationInfo = unsafe { mem::zeroed() };
        let result = ffi_to_result(unsafe {
            ffi::vmaAllocateMemoryForBuffer(
                self.internal,
                ffi_buffer,
                &create_info,
                &mut allocation.internal,
                &mut allocation_info.internal,
            )
        });
        match result {
            erupt::vk::Result::SUCCESS => Ok((allocation, allocation_info)),
            _ => Err(Error::vulkan(result)),
        }
    }

    /// Image specialized memory allocation.
    ///
    /// You should free the memory using `Allocator::free_memory` or 'Allocator::free_memory_pages'.
    pub fn allocate_memory_for_image(
        &self,
        image: erupt::vk::Image,
        allocation_info: &AllocationCreateInfo,
    ) -> Result<(Allocation, AllocationInfo)> {
        let ffi_image = image.object_handle() as ffi::VkImage;
        let create_info = allocation_create_info_to_ffi(&allocation_info);
        let mut allocation: Allocation = unsafe { mem::zeroed() };
        let mut allocation_info: AllocationInfo = unsafe { mem::zeroed() };
        let result = ffi_to_result(unsafe {
            ffi::vmaAllocateMemoryForImage(
                self.internal,
                ffi_image,
                &create_info,
                &mut allocation.internal,
                &mut allocation_info.internal,
            )
        });
        match result {
            erupt::vk::Result::SUCCESS => Ok((allocation, allocation_info)),
            _ => Err(Error::vulkan(result)),
        }
    }

    /// Frees memory previously allocated using `Allocator::allocate_memory`,
    /// `Allocator::allocate_memory_for_buffer`, or `Allocator::allocate_memory_for_image`.
    pub fn free_memory(&self, allocation: &Allocation) {
        unsafe {
            ffi::vmaFreeMemory(self.internal, allocation.internal);
        }
    }

    /// Frees memory and destroys multiple allocations.
    ///
    /// Word "pages" is just a suggestion to use this function to free pieces of memory used for sparse binding.
    /// It is just a general purpose function to free memory and destroy allocations made using e.g. `Allocator::allocate_memory',
    /// 'Allocator::allocate_memory_pages` and other functions.
    ///
    /// It may be internally optimized to be more efficient than calling 'Allocator::free_memory` `allocations.len()` times.
    ///
    /// Allocations in 'allocations' slice can come from any memory pools and types.
    pub fn free_memory_pages(&self, allocations: &[Allocation]) {
        let mut allocations_ffi: Vec<ffi::VmaAllocation> =
            allocations.iter().map(|x| x.internal).collect();
        unsafe {
            ffi::vmaFreeMemoryPages(
                self.internal,
                allocations_ffi.len(),
                allocations_ffi.as_mut_ptr(),
            );
        }
    }

    /// Returns current information about specified allocation and atomically marks it as used in current frame.
    ///
    /// Current parameters of given allocation are returned in the result object, available through accessors.
    ///
    /// This function also atomically "touches" allocation - marks it as used in current frame,
    /// just like `Allocator::touch_allocation`.
    ///
    /// If the allocation is in lost state, `allocation.get_device_memory` returns `erupt::vk::DeviceMemory::null()`.
    ///
    /// Although this function uses atomics and doesn't lock any mutex, so it should be quite efficient,
    /// you can avoid calling it too often.
    ///
    /// If you just want to check if allocation is not lost, `Allocator::touch_allocation` will work faster.
    pub fn get_allocation_info(&self, allocation: &Allocation) -> Result<AllocationInfo> {
        let mut allocation_info: AllocationInfo = unsafe { mem::zeroed() };
        unsafe {
            ffi::vmaGetAllocationInfo(
                self.internal,
                allocation.internal,
                &mut allocation_info.internal,
            )
        }
        Ok(allocation_info)
    }

    /// Returns `true` if allocation is not lost and atomically marks it as used in current frame.
    ///
    /// If the allocation has been created with `AllocationCreateFlags::CAN_BECOME_LOST` flag,
    /// this function returns `true` if it's not in lost state, so it can still be used.
    /// It then also atomically "touches" the allocation - marks it as used in current frame,
    /// so that you can be sure it won't become lost in current frame or next `frame_in_use_count` frames.
    ///
    /// If the allocation is in lost state, the function returns `false`.
    /// Memory of such allocation, as well as buffer or image bound to it, should not be used.
    /// Lost allocation and the buffer/image still need to be destroyed.
    ///
    /// If the allocation has been created without `AllocationCreateFlags::CAN_BECOME_LOST` flag,
    /// this function always returns `true`.
    pub fn touch_allocation(&self, allocation: &Allocation) -> Result<bool> {
        let result = unsafe { ffi::vmaTouchAllocation(self.internal, allocation.internal) };
        Ok(result == erupt::vk::TRUE)
    }

    /// Sets user data in given allocation to new value.
    ///
    /// If the allocation was created with `AllocationCreateFlags::USER_DATA_COPY_STRING`,
    /// `user_data` must be either null, or pointer to a null-terminated string. The function
    /// makes local copy of the string and sets it as allocation's user data. String
    /// passed as user data doesn't need to be valid for whole lifetime of the allocation -
    /// you can free it after this call. String previously pointed by allocation's
    /// user data is freed from memory.
    ///
    /// If the flag was not used, the value of pointer `user_data` is just copied to
    /// allocation's user data. It is opaque, so you can use it however you want - e.g.
    /// as a pointer, ordinal number or some handle to you own data.
    pub unsafe fn set_allocation_user_data(
        &self,
        allocation: &Allocation,
        user_data: *mut ::std::os::raw::c_void,
    ) {
        ffi::vmaSetAllocationUserData(self.internal, allocation.internal, user_data);
    }

    /// Creates new allocation that is in lost state from the beginning.
    ///
    /// It can be useful if you need a dummy, non-null allocation.
    ///
    /// You still need to destroy created object using `Allocator::free_memory`.
    ///
    /// Returned allocation is not tied to any specific memory pool or memory type and
    /// not bound to any image or buffer. It has size = 0. It cannot be turned into
    /// a real, non-empty allocation.
    pub fn create_lost_allocation(&self) -> Result<Allocation> {
        let mut allocation: Allocation = unsafe { mem::zeroed() };
        unsafe {
            ffi::vmaCreateLostAllocation(self.internal, &mut allocation.internal);
        }
        Ok(allocation)
    }

    /// Maps memory represented by given allocation and returns pointer to it.
    ///
    /// Maps memory represented by given allocation to make it accessible to CPU code.
    /// When succeeded, result is a pointer to first byte of this memory.
    ///
    /// If the allocation is part of bigger `erupt::vk::DeviceMemory` block, the pointer is
    /// correctly offseted to the beginning of region assigned to this particular
    /// allocation.
    ///
    /// Mapping is internally reference-counted and synchronized, so despite raw Vulkan
    /// function `erupt::vk::Device::MapMemory` cannot be used to map same block of
    /// `erupt::vk::DeviceMemory` multiple times simultaneously, it is safe to call this
    /// function on allocations assigned to the same memory block. Actual Vulkan memory
    /// will be mapped on first mapping and unmapped on last unmapping.
    ///
    /// If the function succeeded, you must call `Allocator::unmap_memory` to unmap the
    /// allocation when mapping is no longer needed or before freeing the allocation, at
    /// the latest.
    ///
    /// It also safe to call this function multiple times on the same allocation. You
    /// must call `Allocator::unmap_memory` same number of times as you called
    /// `Allocator::map_memory`.
    ///
    /// It is also safe to call this function on allocation created with
    /// `AllocationCreateFlags::MAPPED` flag. Its memory stays mapped all the time.
    /// You must still call `Allocator::unmap_memory` same number of times as you called
    /// `Allocator::map_memory`. You must not call `Allocator::unmap_memory` additional
    /// time to free the "0-th" mapping made automatically due to `AllocationCreateFlags::MAPPED` flag.
    ///
    /// This function fails when used on allocation made in memory type that is not
    /// `erupt::vk::MemoryPropertyFlags::HOST_VISIBLE`.
    ///
    /// This function always fails when called for allocation that was created with
    /// `AllocationCreateFlags::CAN_BECOME_LOST` flag. Such allocations cannot be mapped.
    pub fn map_memory(&self, allocation: &Allocation) -> Result<*mut u8> {
        let mut mapped_data: *mut ::std::os::raw::c_void = ::std::ptr::null_mut();
        let result = ffi_to_result(unsafe {
            ffi::vmaMapMemory(self.internal, allocation.internal, &mut mapped_data)
        });
        match result {
            erupt::vk::Result::SUCCESS => Ok(mapped_data as *mut u8),
            _ => Err(Error::vulkan(result)),
        }
    }

    /// Unmaps memory represented by given allocation, mapped previously using `Allocator::map_memory`.
    pub fn unmap_memory(&self, allocation: &Allocation) {
        unsafe {
            ffi::vmaUnmapMemory(self.internal, allocation.internal);
        }
    }

    /// Flushes memory of given allocation.
    ///
    /// Calls `erupt::vk::Device::FlushMappedMemoryRanges` for memory associated with given range of given allocation.
    ///
    /// - `offset` must be relative to the beginning of allocation.
    /// - `size` can be `erupt::vk::WHOLE_SIZE`. It means all memory from `offset` the the end of given allocation.
    /// - `offset` and `size` don't have to be aligned; hey are internally rounded down/up to multiple of `nonCoherentAtomSize`.
    /// - If `size` is 0, this call is ignored.
    /// - If memory type that the `allocation` belongs to is not `erupt::vk::MemoryPropertyFlags::HOST_VISIBLE` or it is `erupt::vk::MemoryPropertyFlags::HOST_COHERENT`, this call is ignored.
    pub fn flush_allocation(&self, allocation: &Allocation, offset: usize, size: usize) {
        unsafe {
            ffi::vmaFlushAllocation(
                self.internal,
                allocation.internal,
                offset as ffi::VkDeviceSize,
                size as ffi::VkDeviceSize,
            );
        }
    }

    /// Invalidates memory of given allocation.
    ///
    /// Calls `erupt::vk::Device::invalidate_mapped_memory_ranges` for memory associated with given range of given allocation.
    ///
    /// - `offset` must be relative to the beginning of allocation.
    /// - `size` can be `erupt::vk::WHOLE_SIZE`. It means all memory from `offset` the the end of given allocation.
    /// - `offset` and `size` don't have to be aligned. They are internally rounded down/up to multiple of `nonCoherentAtomSize`.
    /// - If `size` is 0, this call is ignored.
    /// - If memory type that the `allocation` belongs to is not `erupt::vk::MemoryPropertyFlags::HOST_VISIBLE` or it is `erupt::vk::MemoryPropertyFlags::HOST_COHERENT`, this call is ignored.
    pub fn invalidate_allocation(&self, allocation: &Allocation, offset: usize, size: usize) {
        unsafe {
            ffi::vmaInvalidateAllocation(
                self.internal,
                allocation.internal,
                offset as ffi::VkDeviceSize,
                size as ffi::VkDeviceSize,
            );
        }
    }

    /// Checks magic number in margins around all allocations in given memory types (in both default and custom pools) in search for corruptions.
    ///
    /// `memory_type_bits` bit mask, where each bit set means that a memory type with that index should be checked.
    ///
    /// Corruption detection is enabled only when `VMA_DEBUG_DETECT_CORRUPTION` macro is defined to nonzero,
    /// `VMA_DEBUG_MARGIN` is defined to nonzero and only for memory types that are `HOST_VISIBLE` and `HOST_COHERENT`.
    ///
    /// Possible error values:
    ///
    /// - `erupt::vk::Result::ERROR_FEATURE_NOT_PRESENT` - corruption detection is not enabled for any of specified memory types.
    /// - `erupt::vk::Result::ERROR_VALIDATION_FAILED_EXT` - corruption detection has been performed and found memory corruptions around one of the allocations.
    ///   `VMA_ASSERT` is also fired in that case.
    /// - Other value: Error returned by Vulkan, e.g. memory mapping failure.
    pub fn check_corruption(&self, memory_types: erupt::vk::MemoryPropertyFlags) -> Result<()> {
        let result =
            ffi_to_result(unsafe { ffi::vmaCheckCorruption(self.internal, memory_types.bits()) });
        match result {
            erupt::vk::Result::SUCCESS => Ok(()),
            _ => Err(Error::vulkan(result)),
        }
    }

    /// Begins defragmentation process.
    ///
    /// Use this function instead of old, deprecated `Allocator::defragment`.
    ///
    /// Warning! Between the call to `Allocator::defragmentation_begin` and `Allocator::defragmentation_end`.
    ///
    /// - You should not use any of allocations passed as `allocations` or
    /// any allocations that belong to pools passed as `pools`,
    /// including calling `Allocator::get_allocation_info`, `Allocator::touch_allocation`, or access
    /// their data.
    ///
    /// - Some mutexes protecting internal data structures may be locked, so trying to
    /// make or free any allocations, bind buffers or images, map memory, or launch
    /// another simultaneous defragmentation in between may cause stall (when done on
    /// another thread) or deadlock (when done on the same thread), unless you are
    /// 100% sure that defragmented allocations are in different pools.
    ///
    /// - Information returned via stats and `info.allocations_changed` are undefined.
    /// They become valid after call to `Allocator::defragmentation_end`.
    ///
    /// - If `info.command_buffer` is not null, you must submit that command buffer
    /// and make sure it finished execution before calling `Allocator::defragmentation_end`.
    pub fn defragmentation_begin(
        &self,
        info: &DefragmentationInfo2,
    ) -> Result<DefragmentationContext> {
        let command_buffer = match info.command_buffer {
            Some(command_buffer) => command_buffer,
            None => erupt::vk::CommandBuffer::null(),
        };
        let mut pools: Vec<ffi::VmaPool> = match info.pools {
            Some(ref pools) => pools.iter().map(|pool| pool.internal).collect(),
            None => Vec::new(),
        };
        let mut allocations: Vec<ffi::VmaAllocation> =
            info.allocations.iter().map(|x| x.internal).collect();
        let mut context = DefragmentationContext {
            internal: unsafe { mem::zeroed() },
            stats: Box::new(unsafe { mem::zeroed() }),
            changed: vec![erupt::vk::FALSE; allocations.len()],
        };
        let ffi_info = ffi::VmaDefragmentationInfo2 {
            flags: 0, // Reserved for future use
            allocationCount: info.allocations.len() as u32,
            pAllocations: allocations.as_mut_ptr(),
            pAllocationsChanged: context.changed.as_mut_ptr(),
            poolCount: pools.len() as u32,
            pPools: pools.as_mut_ptr(),
            maxCpuBytesToMove: info.max_cpu_bytes_to_move,
            maxCpuAllocationsToMove: info.max_cpu_allocations_to_move,
            maxGpuBytesToMove: info.max_gpu_bytes_to_move,
            maxGpuAllocationsToMove: info.max_gpu_allocations_to_move,
            commandBuffer: command_buffer.object_handle() as ffi::VkCommandBuffer,
        };
        let result = ffi_to_result(unsafe {
            ffi::vmaDefragmentationBegin(
                self.internal,
                &ffi_info,
                &mut *context.stats,
                &mut context.internal,
            )
        });
        match result {
            erupt::vk::Result::SUCCESS => Ok(context),
            _ => Err(Error::vulkan(result)),
        }
    }

    /// Ends defragmentation process.
    ///
    /// Use this function to finish defragmentation started by `Allocator::defragmentation_begin`.
    pub fn defragmentation_end(
        &self,
        context: &mut DefragmentationContext,
    ) -> Result<(DefragmentationStats, Vec<bool>)> {
        let result =
            ffi_to_result(unsafe { ffi::vmaDefragmentationEnd(self.internal, context.internal) });
        let changed: Vec<bool> = context.changed.iter().map(|change| *change == 1).collect();
        match result {
            erupt::vk::Result::SUCCESS => Ok((
                DefragmentationStats {
                    bytes_moved: context.stats.bytesMoved as usize,
                    bytes_freed: context.stats.bytesFreed as usize,
                    allocations_moved: context.stats.allocationsMoved,
                    device_memory_blocks_freed: context.stats.deviceMemoryBlocksFreed,
                },
                changed,
            )),
            _ => Err(Error::vulkan(result)),
        }
    }

    /// Compacts memory by moving allocations.
    ///
    /// `allocations` is a slice of allocations that can be moved during this compaction.
    /// `defrag_info` optional configuration parameters.
    /// Returns statistics from the defragmentation, and an associated array to `allocations`
    /// which indicates which allocations were changed (if any).
    ///
    /// Possible error values:
    ///
    /// - `erupt::vk::Result::INCOMPLETE` if succeeded but didn't make all possible optimizations because limits specified in
    ///   `defrag_info` have been reached, negative error code in case of error.
    ///
    /// This function works by moving allocations to different places (different
    /// `erupt::vk::DeviceMemory` objects and/or different offsets) in order to optimize memory
    /// usage. Only allocations that are in `allocations` slice can be moved. All other
    /// allocations are considered nonmovable in this call. Basic rules:
    ///
    /// - Only allocations made in memory types that have
    ///   `erupt::vk::MemoryPropertyFlags::HOST_VISIBLE` and `erupt::vk::MemoryPropertyFlags::HOST_COHERENT`
    ///   flags can be compacted. You may pass other allocations but it makes no sense -
    ///   these will never be moved.
    ///
    /// - Custom pools created with `AllocatorPoolCreateFlags::LINEAR_ALGORITHM` or `AllocatorPoolCreateFlags::BUDDY_ALGORITHM` flag are not
    ///   defragmented. Allocations passed to this function that come from such pools are ignored.
    ///
    /// - Allocations created with `AllocationCreateFlags::DEDICATED_MEMORY` or created as dedicated allocations for any
    ///   other reason are also ignored.
    ///
    /// - Both allocations made with or without `AllocationCreateFlags::MAPPED` flag can be compacted. If not persistently
    ///   mapped, memory will be mapped temporarily inside this function if needed.
    ///
    /// - You must not pass same `allocation` object multiple times in `allocations` slice.
    ///
    /// The function also frees empty `erupt::vk::DeviceMemory` blocks.
    ///
    /// Warning: This function may be time-consuming, so you shouldn't call it too often
    /// (like after every resource creation/destruction).
    /// You can call it on special occasions (like when reloading a game level or
    /// when you just destroyed a lot of objects). Calling it every frame may be OK, but
    /// you should measure that on your platform.
    #[deprecated(
        since = "0.1.3",
        note = "This is a part of the old interface. It is recommended to use structure `DefragmentationInfo2` and function `Allocator::defragmentation_begin` instead."
    )]
    pub fn defragment(
        &self,
        allocations: &[Allocation],
        defrag_info: Option<&DefragmentationInfo>,
    ) -> Result<(DefragmentationStats, Vec<bool>)> {
        let mut ffi_allocations: Vec<ffi::VmaAllocation> = allocations
            .iter()
            .map(|allocation| allocation.internal)
            .collect();
        let mut ffi_change_list: Vec<ffi::VkBool32> = vec![0; ffi_allocations.len()];
        let ffi_info = match defrag_info {
            Some(info) => ffi::VmaDefragmentationInfo {
                maxBytesToMove: info.max_bytes_to_move as ffi::VkDeviceSize,
                maxAllocationsToMove: info.max_allocations_to_move,
            },
            None => ffi::VmaDefragmentationInfo {
                maxBytesToMove: erupt::vk::WHOLE_SIZE,
                maxAllocationsToMove: std::u32::MAX,
            },
        };
        let mut ffi_stats: ffi::VmaDefragmentationStats = unsafe { mem::zeroed() };
        let result = ffi_to_result(unsafe {
            ffi::vmaDefragment(
                self.internal,
                ffi_allocations.as_mut_ptr(),
                ffi_allocations.len(),
                ffi_change_list.as_mut_ptr(),
                &ffi_info,
                &mut ffi_stats,
            )
        });
        match result {
            erupt::vk::Result::SUCCESS => {
                let change_list: Vec<bool> = ffi_change_list
                    .iter()
                    .map(|change| *change == erupt::vk::TRUE)
                    .collect();
                Ok((
                    DefragmentationStats {
                        bytes_moved: ffi_stats.bytesMoved as usize,
                        bytes_freed: ffi_stats.bytesFreed as usize,
                        allocations_moved: ffi_stats.allocationsMoved,
                        device_memory_blocks_freed: ffi_stats.deviceMemoryBlocksFreed,
                    },
                    change_list,
                ))
            }
            _ => Err(Error::vulkan(result)),
        }
    }

    /// Binds buffer to allocation.
    ///
    /// Binds specified buffer to region of memory represented by specified allocation.
    /// Gets `erupt::vk::DeviceMemory` handle and offset from the allocation.
    ///
    /// If you want to create a buffer, allocate memory for it and bind them together separately,
    /// you should use this function for binding instead of `erupt::vk::Device::bind_buffer_memory`,
    /// because it ensures proper synchronization so that when a `erupt::vk::DeviceMemory` object is
    /// used by multiple allocations, calls to `erupt::vk::Device::bind_buffer_memory()` or
    /// `erupt::vk::Device::map_memory()` won't happen from multiple threads simultaneously
    /// (which is illegal in Vulkan).
    ///
    /// It is recommended to use function `Allocator::create_buffer` instead of this one.
    pub fn bind_buffer_memory(
        &self,
        buffer: erupt::vk::Buffer,
        allocation: &Allocation,
    ) -> Result<()> {
        let result = ffi_to_result(unsafe {
            ffi::vmaBindBufferMemory(
                self.internal,
                allocation.internal,
                buffer.object_handle() as ffi::VkBuffer,
            )
        });
        match result {
            erupt::vk::Result::SUCCESS => Ok(()),
            _ => Err(Error::vulkan(result)),
        }
    }

    /// Binds image to allocation.
    ///
    /// Binds specified image to region of memory represented by specified allocation.
    /// Gets `erupt::vk::DeviceMemory` handle and offset from the allocation.
    ///
    /// If you want to create a image, allocate memory for it and bind them together separately,
    /// you should use this function for binding instead of `erupt::vk::Device::bind_image_memory`,
    /// because it ensures proper synchronization so that when a `erupt::vk::DeviceMemory` object is
    /// used by multiple allocations, calls to `erupt::vk::Device::bind_image_memory()` or
    /// `erupt::vk::Device::map_memory()` won't happen from multiple threads simultaneously
    /// (which is illegal in Vulkan).
    ///
    /// It is recommended to use function `Allocator::create_image` instead of this one.
    pub fn bind_image_memory(
        &self,
        image: erupt::vk::Image,
        allocation: &Allocation,
    ) -> Result<()> {
        let result = ffi_to_result(unsafe {
            ffi::vmaBindImageMemory(
                self.internal,
                allocation.internal,
                image.object_handle() as ffi::VkImage,
            )
        });
        match result {
            erupt::vk::Result::SUCCESS => Ok(()),
            _ => Err(Error::vulkan(result)),
        }
    }

    /// This function automatically creates a buffer, allocates appropriate memory
    /// for it, and binds the buffer with the memory.
    ///
    /// If the function succeeded, you must destroy both buffer and allocation when you
    /// no longer need them using either convenience function `Allocator::destroy_buffer` or
    /// separately, using `erupt::Device::destroy_buffer` and `Allocator::free_memory`.
    ///
    /// If `AllocatorCreateFlags::KHR_DEDICATED_ALLOCATION` flag was used,
    /// VK_KHR_dedicated_allocation extension is used internally to query driver whether
    /// it requires or prefers the new buffer to have dedicated allocation. If yes,
    /// and if dedicated allocation is possible (AllocationCreateInfo::pool is null
    /// and `AllocationCreateFlags::NEVER_ALLOCATE` is not used), it creates dedicated
    /// allocation for this buffer, just like when using `AllocationCreateFlags::DEDICATED_MEMORY`.
    pub fn create_buffer(
        &self,
        buffer_info: &erupt::vk::BufferCreateInfo,
        allocation_info: &AllocationCreateInfo,
    ) -> Result<(erupt::vk::Buffer, Allocation, AllocationInfo)> {
        let buffer_create_info = unsafe {
            mem::transmute::<erupt::vk::BufferCreateInfo, ffi::VkBufferCreateInfo>(*buffer_info)
        };
        let allocation_create_info = allocation_create_info_to_ffi(&allocation_info);
        let mut buffer: ffi::VkBuffer = unsafe { mem::zeroed() };
        let mut allocation: Allocation = unsafe { mem::zeroed() };
        let mut allocation_info: AllocationInfo = unsafe { mem::zeroed() };
        let result = ffi_to_result(unsafe {
            ffi::vmaCreateBuffer(
                self.internal,
                &buffer_create_info,
                &allocation_create_info,
                &mut buffer,
                &mut allocation.internal,
                &mut allocation_info.internal,
            )
        });
        match result {
            erupt::vk::Result::SUCCESS => Ok((
                erupt::vk::Buffer(buffer as u64),
                allocation,
                allocation_info,
            )),
            _ => Err(Error::vulkan(result)),
        }
    }

    /// Destroys Vulkan buffer and frees allocated memory.
    ///
    /// This is just a convenience function equivalent to:
    ///
    /// ```ignore
    /// erupt::vk::Device::destroy_buffer(buffer, None);
    /// Allocator::free_memory(allocator, allocation);
    /// ```
    ///
    /// It it safe to pass null as `buffer` and/or `allocation`.
    pub fn destroy_buffer(&self, buffer: erupt::vk::Buffer, allocation: &Allocation) {
        unsafe {
            ffi::vmaDestroyBuffer(
                self.internal,
                buffer.object_handle() as ffi::VkBuffer,
                allocation.internal,
            );
        }
    }

    /// This function automatically creates an image, allocates appropriate memory
    /// for it, and binds the image with the memory.
    ///
    /// If the function succeeded, you must destroy both image and allocation when you
    /// no longer need them using either convenience function `Allocator::destroy_image` or
    /// separately, using `erupt::Device::destroy_image` and `Allocator::free_memory`.
    ///
    /// If `AllocatorCreateFlags::KHR_DEDICATED_ALLOCATION` flag was used,
    /// `VK_KHR_dedicated_allocation extension` is used internally to query driver whether
    /// it requires or prefers the new image to have dedicated allocation. If yes,
    /// and if dedicated allocation is possible (AllocationCreateInfo::pool is null
    /// and `AllocationCreateFlags::NEVER_ALLOCATE` is not used), it creates dedicated
    /// allocation for this image, just like when using `AllocationCreateFlags::DEDICATED_MEMORY`.
    ///
    /// If `VK_ERROR_VALIDAITON_FAILED_EXT` is returned, VMA may have encountered a problem
    /// that is not caught by the validation layers. One example is if you try to create a 0x0
    /// image, a panic will occur and `VK_ERROR_VALIDAITON_FAILED_EXT` is thrown.
    pub fn create_image(
        &self,
        image_info: &erupt::vk::ImageCreateInfo,
        allocation_info: &AllocationCreateInfo,
    ) -> Result<(erupt::vk::Image, Allocation, AllocationInfo)> {
        let image_create_info = unsafe {
            mem::transmute::<erupt::vk::ImageCreateInfo, ffi::VkImageCreateInfo>(*image_info)
        };
        let allocation_create_info = allocation_create_info_to_ffi(&allocation_info);
        let mut image: ffi::VkImage = unsafe { mem::zeroed() };
        let mut allocation: Allocation = unsafe { mem::zeroed() };
        let mut allocation_info: AllocationInfo = unsafe { mem::zeroed() };
        let result = ffi_to_result(unsafe {
            ffi::vmaCreateImage(
                self.internal,
                &image_create_info,
                &allocation_create_info,
                &mut image,
                &mut allocation.internal,
                &mut allocation_info.internal,
            )
        });
        match result {
            erupt::vk::Result::SUCCESS => {
                Ok((erupt::vk::Image(image as u64), allocation, allocation_info))
            }
            _ => Err(Error::vulkan(result)),
        }
    }

    /// Destroys Vulkan image and frees allocated memory.
    ///
    /// This is just a convenience function equivalent to:
    ///
    /// ```ignore
    /// erupt::vk::Device::destroy_image(image, None);
    /// Allocator::free_memory(allocator, allocation);
    /// ```
    ///
    /// It it safe to pass null as `image` and/or `allocation`.
    pub fn destroy_image(&self, image: erupt::vk::Image, allocation: &Allocation) {
        unsafe {
            ffi::vmaDestroyImage(
                self.internal,
                image.object_handle() as ffi::VkImage,
                allocation.internal,
            );
        }
    }

    /// Destroys the internal allocator instance. After this has been called,
    /// no other functions may be called. Useful for ensuring a specific destruction
    /// order (for example, if an Allocator is a member of something that owns the Vulkan
    /// instance and destroys it in its own Drop).
    pub fn destroy(&mut self) {
        if !self.internal.is_null() {
            unsafe {
                ffi::vmaDestroyAllocator(self.internal);
                self.internal = std::ptr::null_mut();
            }
        }
    }
}

/// Custom `Drop` implementation to clean up internal allocation instance
impl Drop for Allocator {
    fn drop(&mut self) {
        self.destroy();
    }
}