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
//! The core function of MPI is getting data from point A to point B (where A and B are e.g. single
//! processes, multiple processes, the filesystem, ...). It offers facilities to describe that data
//! (layout in memory, behavior under certain operators) that go beyound a start address and a
//! number of bytes.
//!
//! An MPI datatype describes a memory layout and semantics (e.g. in a collective reduce
//! operation). There are several pre-defined `SystemDatatype`s which directly correspond to Rust
//! primitive types, such as `MPI_DOUBLE` and `f64`. A direct relationship between a Rust type and
//! an MPI datatype is covered by the `Equivalence` trait. Starting from the
//! `SystemDatatype`s, the user can build various `UserDatatype`s, e.g. to describe the layout of a
//! struct (which should then implement `Equivalence`) or to intrusively describe parts of
//! an object in memory like all elements below the diagonal of a dense matrix stored in row-major
//! order.
//!
//! ## Derived Datatypes
//! Derived MPI datatypes can exist in either an "uncommitted" or "committed" state. Only
//! "committed" datatypes can be used in MPI communication. There is a cost to committing a
//! datatype: only a final aggregate type should be committed when building it from component
//! derived datatypes.
//!
//! In order to represent the difference between committed and uncommitted `MPI_Datatype` objects,
//! two different flavors of types representing the "committed"-ness of the type are exposed.
//! Orthogonally, there are types representing both "owned" `MPI_Datatype` objects and "borrowed"
//! `MPI_Datatype` objects. This means there are four different types for `MPI_Datatype`:
//! - `UserDatatype` represents a committed, owned `MPI_Datatype`
//! - `DatatypeRef<'_>` represents a committed, borrowed `MPI_Datatype`.
//! - All builtin types are `DatatypeRef<'static>`
//! - `UncommittedUserDatatype` represents an uncommitted, owned `MPI_Datatype`
//! - `UncommittedDatatypeRef<'_>` represents an uncommitted, borrowed `MPI_Datatype`
//!
//! Along with this, there are two traits that are applied to these types:
//! - `UncommittedDatatype` indicates the type represents a possibly uncommitted `MPI_Datatype`
//! - `Datatype` indicates the type represents a committed `MPI_Datatype`
//!
//! An important concept here is that all committed `Datatype` objects are also
//! `UncommittedDatatype` objects. This may seem unintuitive at first, but as far as MPI is
//! concerned, "committing" a datatype is purely a promotion, enabling more capabilities. This
//! allows `Datatype` and `UncommittedDatatype` objects to be used interchangeably in the same
//! `Datatype` constructors.
//!
//! For more information on derived datatypes, see section 4.1 of the MPI 3.1 Standard.
//!
//! ## Data Buffers
//! A `Buffer` describes a specific piece of data in memory that MPI should operate on. In addition
//! to specifying the datatype of the data. It knows the address in memory where the data begins
//! and how many instances of the datatype are contained in the data. The `Buffer` trait is
//! implemented for slices that contain types implementing `Equivalence`.
//!
//! In order to use arbitrary datatypes to describe the contents of a slice, the `View` type is
//! provided. However, since it can be used to instruct the underlying MPI implementation to
//! rummage around arbitrary parts of memory, its constructors are currently marked unsafe.
//!
//! # Unfinished features
//!
//! - **4.1.3**: Subarray datatype constructors, `MPI_Type_create_subarray()`,
//! - **4.1.4**: Distributed array datatype constructors, `MPI_Type_create_darray()`
//! - **4.1.5**: Address and size functions, `MPI_Get_address()`, `MPI_Aint_add()`,
//! `MPI_Aint_diff()`, `MPI_Type_size()`, `MPI_Type_size_x()`
//! - **4.1.7**: Extent and bounds of datatypes: `MPI_Type_get_extent()`,
//! `MPI_Type_get_extent_x()`, `MPI_Type_create_resized()`
//! - **4.1.8**: True extent of datatypes, `MPI_Type_get_true_extent()`,
//! `MPI_Type_get_true_extent_x()`
//! - **4.1.11**: `MPI_Get_elements()`, `MPI_Get_elements_x()`
//! - **4.1.13**: Decoding a datatype, `MPI_Type_get_envelope()`, `MPI_Type_get_contents()`
//! - **4.3**: Canonical pack and unpack, `MPI_Pack_external()`, `MPI_Unpack_external()`,
//! `MPI_Pack_external_size()`
use std::borrow::Borrow;
use std::marker::PhantomData;
use std::os::raw::c_void;
use std::{mem, slice};
use conv::ConvUtil;
use super::{Address, Count};
use crate::ffi;
use crate::ffi::MPI_Datatype;
use crate::raw::traits::*;
use crate::with_uninitialized;
/// Datatype traits
pub mod traits {
pub use super::{
AsDatatype, Buffer, BufferMut, Collection, Datatype, Equivalence, Partitioned,
PartitionedBuffer, PartitionedBufferMut, Pointer, PointerMut, UncommittedDatatype,
};
}
/// A reference to an MPI data type.
///
/// This is similar to a raw `MPI_Datatype` but is guaranteed to be a valid for `'a`.
#[derive(Copy, Clone, Debug)]
pub struct DatatypeRef<'a> {
datatype: MPI_Datatype,
phantom: PhantomData<&'a ()>,
}
unsafe impl<'a> AsRaw for DatatypeRef<'a> {
type Raw = MPI_Datatype;
fn as_raw(&self) -> Self::Raw {
self.datatype
}
}
impl<'a> FromRaw for DatatypeRef<'a> {
unsafe fn from_raw(datatype: MPI_Datatype) -> Self {
Self {
datatype,
phantom: PhantomData,
}
}
}
unsafe impl<'a> MatchesRaw for DatatypeRef<'a> {}
impl<'a> Datatype for DatatypeRef<'a> {}
impl<'a> UncommittedDatatype for DatatypeRef<'a> {
type DuplicatedDatatype = UserDatatype;
}
impl<'a> From<DatatypeRef<'a>> for UncommittedDatatypeRef<'a> {
fn from(datatype_ref: DatatypeRef<'a>) -> Self {
unsafe { UncommittedDatatypeRef::from_raw(datatype_ref.as_raw()) }
}
}
/// A reference to an uncommitted, or potentially uncommitted, MPI data type.
///
/// This is similar to a raw uncommitted `MPI_Datatype` but is guaranteed to be a valid for `'a`.
#[derive(Copy, Clone, Debug)]
pub struct UncommittedDatatypeRef<'a> {
datatype: MPI_Datatype,
phantom: PhantomData<&'a ()>,
}
unsafe impl<'a> AsRaw for UncommittedDatatypeRef<'a> {
type Raw = MPI_Datatype;
fn as_raw(&self) -> Self::Raw {
self.datatype
}
}
impl<'a> FromRaw for UncommittedDatatypeRef<'a> {
unsafe fn from_raw(datatype: MPI_Datatype) -> Self {
Self {
datatype,
phantom: PhantomData,
}
}
}
unsafe impl<'a> MatchesRaw for UncommittedDatatypeRef<'a> {}
impl<'a> UncommittedDatatype for UncommittedDatatypeRef<'a> {
type DuplicatedDatatype = UncommittedUserDatatype;
}
/// A system datatype, e.g. `MPI_FLOAT`
///
/// # Standard section(s)
///
/// 3.2.2
pub type SystemDatatype = DatatypeRef<'static>;
/// A direct equivalence exists between the implementing type and an MPI datatype
///
/// # Standard section(s)
///
/// 3.2.2
pub unsafe trait Equivalence {
/// The type of the equivalent MPI datatype (e.g. `SystemDatatype` or `UserDatatype`)
type Out: Datatype;
/// The MPI datatype that is equivalent to this Rust type
fn equivalent_datatype() -> Self::Out;
}
macro_rules! equivalent_system_datatype {
($rstype:path, $mpitype:path) => {
unsafe impl Equivalence for $rstype {
type Out = SystemDatatype;
fn equivalent_datatype() -> Self::Out {
unsafe { DatatypeRef::from_raw($mpitype) }
}
}
};
}
equivalent_system_datatype!(bool, ffi::RSMPI_C_BOOL);
equivalent_system_datatype!(f32, ffi::RSMPI_FLOAT);
equivalent_system_datatype!(f64, ffi::RSMPI_DOUBLE);
equivalent_system_datatype!(i8, ffi::RSMPI_INT8_T);
equivalent_system_datatype!(i16, ffi::RSMPI_INT16_T);
equivalent_system_datatype!(i32, ffi::RSMPI_INT32_T);
equivalent_system_datatype!(i64, ffi::RSMPI_INT64_T);
equivalent_system_datatype!(u8, ffi::RSMPI_UINT8_T);
equivalent_system_datatype!(u16, ffi::RSMPI_UINT16_T);
equivalent_system_datatype!(u32, ffi::RSMPI_UINT32_T);
equivalent_system_datatype!(u64, ffi::RSMPI_UINT64_T);
#[cfg(target_pointer_width = "32")]
equivalent_system_datatype!(usize, ffi::RSMPI_UINT32_T);
#[cfg(target_pointer_width = "32")]
equivalent_system_datatype!(isize, ffi::RSMPI_INT32_T);
#[cfg(target_pointer_width = "64")]
equivalent_system_datatype!(usize, ffi::RSMPI_UINT64_T);
#[cfg(target_pointer_width = "64")]
equivalent_system_datatype!(isize, ffi::RSMPI_INT64_T);
#[cfg(feature = "complex")]
/// Implement direct equivalence for complex types
pub mod complex_datatype {
use super::{ffi, DatatypeRef, Equivalence, FromRaw, SystemDatatype};
use num_complex::{Complex32, Complex64};
equivalent_system_datatype!(Complex32, ffi::RSMPI_FLOAT_COMPLEX);
equivalent_system_datatype!(Complex64, ffi::RSMPI_DOUBLE_COMPLEX);
}
/// A user defined MPI datatype
///
/// # Standard section(s)
///
/// 4
pub struct UserDatatype(MPI_Datatype);
impl UserDatatype {
/// Constructs a new datatype by concatenating `count` repetitions of `oldtype`
///
/// # Examples
/// See `examples/contiguous.rs`
///
/// # Standard section(s)
///
/// 4.1.2
pub fn contiguous<D>(count: Count, oldtype: &D) -> UserDatatype
where
D: UncommittedDatatype,
{
UncommittedUserDatatype::contiguous(count, oldtype).commit()
}
/// Construct a new datatype out of `count` blocks of `blocklength` elements of `oldtype`
/// concatenated with the start of consecutive blocks placed `stride` elements apart.
///
/// # Examples
/// See `examples/vector.rs`
///
/// # Standard section(s)
///
/// 4.1.2
pub fn vector<D>(count: Count, blocklength: Count, stride: Count, oldtype: &D) -> UserDatatype
where
D: UncommittedDatatype,
{
UncommittedUserDatatype::vector(count, blocklength, stride, oldtype).commit()
}
/// Like `vector()` but `stride` is given in bytes rather than elements of `oldtype`.
///
/// # Standard section(s)
///
/// 4.1.2
pub fn heterogeneous_vector<D>(
count: Count,
blocklength: Count,
stride: Address,
oldtype: &D,
) -> UserDatatype
where
D: UncommittedDatatype,
{
UncommittedUserDatatype::heterogeneous_vector(count, blocklength, stride, oldtype).commit()
}
/// Constructs a new type out of multiple blocks of individual length and displacement.
/// Block `i` will be `blocklengths[i]` items of datytpe `oldtype` long and displaced by
/// `dispplacements[i]` items of the `oldtype`.
///
/// # Standard section(s)
///
/// 4.1.2
pub fn indexed<D>(blocklengths: &[Count], displacements: &[Count], oldtype: &D) -> UserDatatype
where
D: UncommittedDatatype,
{
UncommittedUserDatatype::indexed(blocklengths, displacements, oldtype).commit()
}
/// Constructs a new type out of multiple blocks of individual length and displacement.
/// Block `i` will be `blocklengths[i]` items of datytpe `oldtype` long and displaced by
/// `dispplacements[i]` bytes.
///
/// # Standard section(s)
///
/// 4.1.2
pub fn heterogeneous_indexed<D>(
blocklengths: &[Count],
displacements: &[Address],
oldtype: &D,
) -> UserDatatype
where
D: UncommittedDatatype,
{
UncommittedUserDatatype::heterogeneous_indexed(blocklengths, displacements, oldtype)
.commit()
}
/// Construct a new type out of blocks of the same length and individual displacements.
///
/// # Standard section(s)
///
/// 4.1.2
pub fn indexed_block<D>(
blocklength: Count,
displacements: &[Count],
oldtype: &D,
) -> UserDatatype
where
D: UncommittedDatatype,
{
UncommittedUserDatatype::indexed_block(blocklength, displacements, oldtype).commit()
}
/// Construct a new type out of blocks of the same length and individual displacements.
/// Displacements are in bytes.
///
/// # Standard section(s)
///
/// 4.1.2
pub fn heterogeneous_indexed_block<D>(
blocklength: Count,
displacements: &[Address],
oldtype: &D,
) -> UserDatatype
where
D: UncommittedDatatype,
{
UncommittedUserDatatype::heterogeneous_indexed_block(blocklength, displacements, oldtype)
.commit()
}
/// Constructs a new datatype out of blocks of different length, displacement and datatypes
///
/// # Examples
/// See `examples/structured.rs`
///
/// # Standard section(s)
///
/// 4.1.2
pub fn structured<D>(
blocklengths: &[Count],
displacements: &[Address],
types: &[D],
) -> UserDatatype
where
D: UncommittedDatatype + MatchesRaw<Raw = MPI_Datatype>,
{
UncommittedUserDatatype::structured(blocklengths, displacements, types).commit()
}
/// Creates a DatatypeRef from this datatype object.
pub fn as_ref(&self) -> DatatypeRef<'_> {
unsafe { DatatypeRef::from_raw(self.as_raw()) }
}
}
// TODO and NOTE: These impls are not 100% implemented, but reflect the larger reality that the
// current API does not strongly enforce the threading requirements of MPI's `MPI_Init_thread`
// function. In order to enforce uniformity across platforms, these traits are explicitly applied.
// Due to the nature of MPI implementations, without this declaration some implementations of
// MPI would otherwise be Send + Sync by default, and others would be !Sync by default.
unsafe impl Send for UserDatatype {}
unsafe impl Sync for UserDatatype {}
impl Clone for UserDatatype {
fn clone(&self) -> Self {
self.dup()
}
}
impl Drop for UserDatatype {
fn drop(&mut self) {
unsafe {
ffi::MPI_Type_free(&mut self.0);
}
assert_eq!(self.0, unsafe { ffi::RSMPI_DATATYPE_NULL });
}
}
unsafe impl AsRaw for UserDatatype {
type Raw = MPI_Datatype;
fn as_raw(&self) -> Self::Raw {
self.0
}
}
impl FromRaw for UserDatatype {
unsafe fn from_raw(handle: MPI_Datatype) -> Self {
assert_ne!(handle, ffi::RSMPI_DATATYPE_NULL);
UserDatatype(handle)
}
}
unsafe impl MatchesRaw for UserDatatype {}
impl Datatype for UserDatatype {}
impl UncommittedDatatype for UserDatatype {
type DuplicatedDatatype = UserDatatype;
}
impl<'a> From<&'a UserDatatype> for DatatypeRef<'a> {
fn from(datatype: &'a UserDatatype) -> Self {
unsafe { DatatypeRef::from_raw(datatype.as_raw()) }
}
}
impl<'a> From<&'a UserDatatype> for UncommittedDatatypeRef<'a> {
fn from(datatype: &'a UserDatatype) -> Self {
unsafe { UncommittedDatatypeRef::from_raw(datatype.as_raw()) }
}
}
/// Represents an MPI datatype that has not yet been committed. Can be used to build up more complex
/// datatypes before committing.
///
/// UncommittedUserDatatype does not implement Datatype - it cannot be used as a datatype, and must be
/// commited to retrieve a UserDatatype that implements Datatype.
///
/// # Standard section(s)
/// 4.1.9
pub struct UncommittedUserDatatype(MPI_Datatype);
impl UncommittedUserDatatype {
/// Constructs a new datatype by concatenating `count` repetitions of `oldtype`
///
/// # Examples
/// See `examples/contiguous.rs`
///
/// # Standard section(s)
///
/// 4.1.2
pub fn contiguous<D>(count: Count, oldtype: &D) -> Self
where
D: UncommittedDatatype,
{
unsafe {
UncommittedUserDatatype(
with_uninitialized(|newtype| {
ffi::MPI_Type_contiguous(count, oldtype.as_raw(), newtype)
})
.1,
)
}
}
/// Construct a new datatype out of `count` blocks of `blocklength` elements of `oldtype`
/// concatenated with the start of consecutive blocks placed `stride` elements apart.
///
/// # Examples
/// See `examples/vector.rs`
///
/// # Standard section(s)
///
/// 4.1.2
pub fn vector<D>(count: Count, blocklength: Count, stride: Count, oldtype: &D) -> Self
where
D: UncommittedDatatype,
{
unsafe {
UncommittedUserDatatype(
with_uninitialized(|newtype| {
ffi::MPI_Type_vector(count, blocklength, stride, oldtype.as_raw(), newtype)
})
.1,
)
}
}
/// Like `vector()` but `stride` is given in bytes rather than elements of `oldtype`.
///
/// # Standard section(s)
///
/// 4.1.2
pub fn heterogeneous_vector<D>(
count: Count,
blocklength: Count,
stride: Address,
oldtype: &D,
) -> Self
where
D: UncommittedDatatype,
{
unsafe {
UncommittedUserDatatype(
with_uninitialized(|newtype| {
ffi::MPI_Type_create_hvector(
count,
blocklength,
stride,
oldtype.as_raw(),
newtype,
)
})
.1,
)
}
}
/// Constructs a new type out of multiple blocks of individual length and displacement.
/// Block `i` will be `blocklengths[i]` items of datytpe `oldtype` long and displaced by
/// `dispplacements[i]` items of the `oldtype`.
///
/// # Standard section(s)
///
/// 4.1.2
pub fn indexed<D>(blocklengths: &[Count], displacements: &[Count], oldtype: &D) -> Self
where
D: UncommittedDatatype,
{
assert_eq!(
blocklengths.len(),
displacements.len(),
"'blocklengths' and 'displacements' must be the same length"
);
unsafe {
UncommittedUserDatatype(
with_uninitialized(|newtype| {
ffi::MPI_Type_indexed(
blocklengths.count(),
blocklengths.as_ptr(),
displacements.as_ptr(),
oldtype.as_raw(),
newtype,
)
})
.1,
)
}
}
/// Constructs a new type out of multiple blocks of individual length and displacement.
/// Block `i` will be `blocklengths[i]` items of datytpe `oldtype` long and displaced by
/// `dispplacements[i]` bytes.
///
/// # Standard section(s)
///
/// 4.1.2
pub fn heterogeneous_indexed<D>(
blocklengths: &[Count],
displacements: &[Address],
oldtype: &D,
) -> Self
where
D: UncommittedDatatype,
{
assert_eq!(
blocklengths.len(),
displacements.len(),
"'blocklengths' and 'displacements' must be the same length"
);
unsafe {
UncommittedUserDatatype(
with_uninitialized(|newtype| {
ffi::MPI_Type_create_hindexed(
blocklengths.count(),
blocklengths.as_ptr(),
displacements.as_ptr(),
oldtype.as_raw(),
newtype,
)
})
.1,
)
}
}
/// Construct a new type out of blocks of the same length and individual displacements.
///
/// # Standard section(s)
///
/// 4.1.2
pub fn indexed_block<D>(blocklength: Count, displacements: &[Count], oldtype: &D) -> Self
where
D: UncommittedDatatype,
{
unsafe {
UncommittedUserDatatype(
with_uninitialized(|newtype| {
ffi::MPI_Type_create_indexed_block(
displacements.count(),
blocklength,
displacements.as_ptr(),
oldtype.as_raw(),
newtype,
)
})
.1,
)
}
}
/// Construct a new type out of blocks of the same length and individual displacements.
/// Displacements are in bytes.
///
/// # Standard section(s)
///
/// 4.1.2
pub fn heterogeneous_indexed_block<D>(
blocklength: Count,
displacements: &[Address],
oldtype: &D,
) -> Self
where
D: UncommittedDatatype,
{
unsafe {
UncommittedUserDatatype(
with_uninitialized(|newtype| {
ffi::MPI_Type_create_hindexed_block(
displacements.count(),
blocklength,
displacements.as_ptr(),
oldtype.as_raw(),
newtype,
)
})
.1,
)
}
}
/// Constructs a new datatype out of blocks of different length, displacement and datatypes
///
/// # Examples
/// See `examples/structured.rs`
///
/// # Standard section(s)
///
/// 4.1.2
pub fn structured<D>(blocklengths: &[Count], displacements: &[Address], types: &[D]) -> Self
where
D: UncommittedDatatype + MatchesRaw<Raw = MPI_Datatype>,
{
assert_eq!(
blocklengths.len(),
displacements.len(),
"'displacements', 'blocklengths', and 'types' must be the same length"
);
assert_eq!(
blocklengths.len(),
types.len(),
"'displacements', 'blocklengths', and 'types' must be the same length"
);
unsafe {
UncommittedUserDatatype(
with_uninitialized(|newtype| {
ffi::MPI_Type_create_struct(
blocklengths.count(),
blocklengths.as_ptr(),
displacements.as_ptr(),
types.as_ptr() as *const _,
newtype,
)
})
.1,
)
}
}
/// Commits a datatype to a specific representation so that it can be used in MPI calls.
///
/// # Standard section(s)
/// 4.1.9
pub fn commit(mut self) -> UserDatatype {
let handle = self.0;
unsafe {
ffi::MPI_Type_commit(&mut self.0);
}
mem::forget(self);
UserDatatype(handle)
}
/// Creates an UncommittedDatatypeRef from this datatype object.
pub fn as_ref(&self) -> UncommittedDatatypeRef<'_> {
unsafe { UncommittedDatatypeRef::from_raw(self.as_raw()) }
}
}
impl Clone for UncommittedUserDatatype {
fn clone(&self) -> Self {
self.dup()
}
}
impl Drop for UncommittedUserDatatype {
fn drop(&mut self) {
unsafe {
ffi::MPI_Type_free(&mut self.0);
}
assert_eq!(self.0, unsafe { ffi::RSMPI_DATATYPE_NULL });
}
}
unsafe impl AsRaw for UncommittedUserDatatype {
type Raw = MPI_Datatype;
fn as_raw(&self) -> Self::Raw {
self.0
}
}
impl FromRaw for UncommittedUserDatatype {
unsafe fn from_raw(handle: MPI_Datatype) -> Self {
assert_ne!(handle, ffi::RSMPI_DATATYPE_NULL);
UncommittedUserDatatype(handle)
}
}
unsafe impl MatchesRaw for UncommittedUserDatatype {}
impl UncommittedDatatype for UncommittedUserDatatype {
type DuplicatedDatatype = UncommittedUserDatatype;
}
impl<'a> From<&'a UncommittedUserDatatype> for UncommittedDatatypeRef<'a> {
fn from(datatype: &'a UncommittedUserDatatype) -> Self {
unsafe { UncommittedDatatypeRef::from_raw(datatype.as_raw()) }
}
}
/// A Datatype describes the layout of messages in memory.
///
/// `Datatype` always represents a committed datatype that can be immediately used for sending and
/// receiving messages. `UncommittedDatatype` is used for datatypes that are possibly uncommitted.
pub trait Datatype: UncommittedDatatype {}
impl<'a, D> Datatype for &'a D where D: 'a + Datatype {}
/// An UncommittedDatatype is a partial description of the layout of messages in memory which may
/// not yet have been committed to an implementation-defined message format.
///
/// Committed datatypes can be treated as-if they are uncommitted.
pub trait UncommittedDatatype: AsRaw<Raw = MPI_Datatype> {
/// The type returned when the datatype is duplicated.
type DuplicatedDatatype: FromRaw<Raw = MPI_Datatype>;
/// Creates a new datatype with the same key-values as this datatype.
///
/// # Standard section(s)
/// 4.1.10
fn dup(&self) -> Self::DuplicatedDatatype {
unsafe {
Self::DuplicatedDatatype::from_raw(
with_uninitialized(|newtype| ffi::MPI_Type_dup(self.as_raw(), newtype)).1,
)
}
}
}
impl<'a, D> UncommittedDatatype for &'a D
where
D: 'a + UncommittedDatatype,
{
type DuplicatedDatatype = <D as UncommittedDatatype>::DuplicatedDatatype;
}
/// Something that has an associated datatype
pub unsafe trait AsDatatype {
/// The type of the associated MPI datatype (e.g. `SystemDatatype` or `UserDatatype`)
type Out: Datatype;
/// The associated MPI datatype
fn as_datatype(&self) -> Self::Out;
}
unsafe impl<T> AsDatatype for T
where
T: Equivalence,
{
type Out = <T as Equivalence>::Out;
fn as_datatype(&self) -> Self::Out {
<T as Equivalence>::equivalent_datatype()
}
}
unsafe impl<T> AsDatatype for [T]
where
T: Equivalence,
{
type Out = <T as Equivalence>::Out;
fn as_datatype(&self) -> Self::Out {
<T as Equivalence>::equivalent_datatype()
}
}
unsafe impl<T> AsDatatype for Vec<T>
where
T: Equivalence,
{
type Out = <T as Equivalence>::Out;
fn as_datatype(&self) -> Self::Out {
<T as Equivalence>::equivalent_datatype()
}
}
unsafe impl<T, const D: usize> AsDatatype for [T; D]
where
T: Equivalence,
{
type Out = <T as Equivalence>::Out;
fn as_datatype(&self) -> Self::Out {
<T as Equivalence>::equivalent_datatype()
}
}
#[doc(hidden)]
pub mod internal {
#[cfg(feature = "derive")]
pub fn check_derive_equivalence_universe_state(type_name: &str) {
use crate::environment::UNIVERSE_STATE;
// Take lock on UNIVERSE_STATE to prevent racing with mpi::init and mpi::finalize.
let universe_state = UNIVERSE_STATE.read().unwrap();
if !crate::environment::is_initialized() {
panic!(
"\n\
RSMPI PANIC: Pre-MPI_Init datatype initialization\n\
\n\
Application attempted to initialize datatype of #[derive(Equivalence)] for \
`{}` before initializing rsmpi. You must first initialize rsmpi before attempting \
to use a custom type in an MPI call.\n",
type_name
);
}
let universe_state = universe_state.as_ref().unwrap();
if crate::environment::is_finalized() {
panic!(
"\n\
RSMPI PANIC: Post-MPI_Finalize datatype initialization.\n\
\n\
Application attempted to initialize datatype of #[derive(Equivalence)] for \
`{0}` after finalizing rsmpi. You must not attempt to use `{0}` in an MPI context \
after finalizing rsmpi.\n",
type_name
);
}
if crate::environment::threading_support() != crate::Threading::Multiple
&& universe_state.main_thread != std::thread::current().id()
{
panic!(
"\n\
RSMPI PANIC: Invalid threaded datatype initialization\n\
\n\
Application attempted to initialize the datatype of #[derive(Equivalence)]
for `{0}` from a different thread than that which initialized `rsmpi`. This \
is only supported when rsmpi is initialized with \
`mpi::Threading::Multiple`. Please explicitly call \
`{0}::equivalent_datatype()` at least once from the same thread as you call \
`rsmpi::initialize*`, or initialize MPI using \
`mpi::initialize_with_threading(mpi::Threading::Multiple)`.\n",
type_name
)
}
}
}
/// A countable collection of things.
pub unsafe trait Collection {
/// How many things are in this collection.
fn count(&self) -> Count;
}
unsafe impl<T> Collection for T
where
T: Equivalence,
{
fn count(&self) -> Count {
1
}
}
unsafe impl<T> Collection for [T]
where
T: Equivalence,
{
fn count(&self) -> Count {
self.len()
.value_as()
.expect("Length of slice cannot be expressed as an MPI Count.")
}
}
unsafe impl<T> Collection for Vec<T>
where
T: Equivalence,
{
fn count(&self) -> Count {
self.len()
.value_as()
.expect("Length of slice cannot be expressed as an MPI Count.")
}
}
unsafe impl<T, const D: usize> Collection for [T; D]
where
T: Equivalence,
{
fn count(&self) -> Count {
// TODO const generic bound
D.value_as()
.expect("Length of slice cannot be expressed as an MPI Count.")
}
}
/// Provides a pointer to the starting address in memory.
pub unsafe trait Pointer {
/// A pointer to the starting address in memory
fn pointer(&self) -> *const c_void;
}
unsafe impl<T> Pointer for T
where
T: Equivalence,
{
fn pointer(&self) -> *const c_void {
let p: *const T = self;
p as *const c_void
}
}
unsafe impl<T> Pointer for [T]
where
T: Equivalence,
{
fn pointer(&self) -> *const c_void {
self.as_ptr() as _
}
}
unsafe impl<T> Pointer for Vec<T>
where
T: Equivalence,
{
fn pointer(&self) -> *const c_void {
self.as_ptr() as _
}
}
unsafe impl<T, const D: usize> Pointer for [T; D]
where
T: Equivalence,
{
fn pointer(&self) -> *const c_void {
self.as_ptr() as _
}
}
/// Provides a mutable pointer to the starting address in memory.
pub unsafe trait PointerMut {
/// A mutable pointer to the starting address in memory
fn pointer_mut(&mut self) -> *mut c_void;
}
unsafe impl<T> PointerMut for T
where
T: Equivalence,
{
fn pointer_mut(&mut self) -> *mut c_void {
let p: *mut T = self;
p as *mut c_void
}
}
unsafe impl<T> PointerMut for [T]
where
T: Equivalence,
{
fn pointer_mut(&mut self) -> *mut c_void {
self.as_mut_ptr() as _
}
}
unsafe impl<T> PointerMut for Vec<T>
where
T: Equivalence,
{
fn pointer_mut(&mut self) -> *mut c_void {
self.as_mut_ptr() as _
}
}
unsafe impl<T, const D: usize> PointerMut for [T; D]
where
T: Equivalence,
{
fn pointer_mut(&mut self) -> *mut c_void {
self.as_mut_ptr() as _
}
}
/// A buffer is a region in memory that starts at `pointer()` and contains `count()` copies of
/// `as_datatype()`.
pub unsafe trait Buffer: Pointer + Collection + AsDatatype {}
unsafe impl<T> Buffer for T where T: Equivalence {}
unsafe impl<T> Buffer for [T] where T: Equivalence {}
unsafe impl<T> Buffer for Vec<T> where T: Equivalence {}
unsafe impl<T, const D: usize> Buffer for [T; D] where T: Equivalence {}
/// A mutable buffer is a region in memory that starts at `pointer_mut()` and contains `count()`
/// copies of `as_datatype()`.
pub unsafe trait BufferMut: PointerMut + Collection + AsDatatype {}
unsafe impl<T> BufferMut for T where T: Equivalence {}
unsafe impl<T> BufferMut for [T] where T: Equivalence {}
unsafe impl<T> BufferMut for Vec<T> where T: Equivalence {}
unsafe impl<T, const D: usize> BufferMut for [T; D] where T: Equivalence {}
/// An immutable dynamically-typed buffer.
///
/// The buffer has a definite length and MPI datatype, but it is not yet known which Rust type it
/// corresponds to. This is the MPI analogue of `&Any`. It is semantically equivalent to the trait
/// object reference `&Buffer`.
#[derive(Copy, Clone, Debug)]
pub struct DynBuffer<'a> {
ptr: *const c_void,
len: Count,
datatype: DatatypeRef<'a>,
}
unsafe impl<'a> Send for DynBuffer<'a> {}
unsafe impl<'a> Sync for DynBuffer<'a> {}
unsafe impl<'a> Collection for DynBuffer<'a> {
fn count(&self) -> Count {
self.len
}
}
unsafe impl<'a> Pointer for DynBuffer<'a> {
fn pointer(&self) -> *const c_void {
self.ptr
}
}
unsafe impl<'a> AsDatatype for DynBuffer<'a> {
type Out = DatatypeRef<'a>;
fn as_datatype(&self) -> Self::Out {
self.datatype
}
}
unsafe impl<'a> Buffer for DynBuffer<'a> {}
impl<'a> DynBuffer<'a> {
/// Creates a buffer from a slice with whose type has an MPI equivalent.
pub fn new<T: Equivalence>(buf: &'a [T]) -> Self {
unsafe {
let datatype = DatatypeRef::from_raw(T::equivalent_datatype().as_raw());
Self::from_raw(buf.as_ptr(), buf.count(), datatype)
}
}
/// Tests whether the buffer type matches `T`.
pub fn is<T: Equivalence>(&self) -> bool {
self.as_datatype().as_raw() == T::equivalent_datatype().as_raw()
}
/// Returns some slice if the type matches `T`, or `None` if it doesn't.
pub fn downcast<T: Equivalence>(self) -> Option<&'a [T]> {
if self.is::<T>() {
unsafe { Some(slice::from_raw_parts(self.as_ptr() as _, self.len())) }
} else {
None
}
}
/// Creates a buffer from its raw components. The buffer must remain valid for `'a` and the
/// pointer must not be null.
///
/// # Safety
/// - Buffer pointed to by `ptr` must live as long as `'a`
/// - `ptr` must point to an object that holds `len` elements of the type described by
/// `datatype`.
pub unsafe fn from_raw<T>(ptr: *const T, len: Count, datatype: DatatypeRef<'a>) -> Self {
debug_assert!(!ptr.is_null());
Self {
ptr: ptr as _,
len,
datatype,
}
}
/// Returns the number of elements in the buffer.
pub fn len(&self) -> usize {
self.count()
.value_as()
.expect("Length of DynBuffer cannot be expressed as a usize")
}
/// Returns `true` if the buffer is empty
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns the underlying raw pointer.
pub fn as_ptr(&self) -> *const c_void {
self.ptr
}
}
/// A mutable dynamically-typed buffer.
///
/// The buffer has a definite length and MPI datatype, but it is not yet known which Rust type it
/// corresponds to. This is the MPI analogue of `&mut Any`. It is semantically equivalent to the
/// mutable trait object reference `&mut BufferMut`.
#[derive(Debug)]
pub struct DynBufferMut<'a> {
ptr: *mut c_void,
len: Count,
datatype: DatatypeRef<'a>,
}
unsafe impl<'a> Send for DynBufferMut<'a> {}
unsafe impl<'a> Sync for DynBufferMut<'a> {}
unsafe impl<'a> Collection for DynBufferMut<'a> {
fn count(&self) -> Count {
self.len
}
}
unsafe impl<'a> Pointer for DynBufferMut<'a> {
fn pointer(&self) -> *const c_void {
self.ptr
}
}
unsafe impl<'a> PointerMut for DynBufferMut<'a> {
fn pointer_mut(&mut self) -> *mut c_void {
self.ptr
}
}
unsafe impl<'a> Buffer for DynBufferMut<'a> {}
unsafe impl<'a> BufferMut for DynBufferMut<'a> {}
unsafe impl<'a> AsDatatype for DynBufferMut<'a> {
type Out = DatatypeRef<'a>;
fn as_datatype(&self) -> Self::Out {
self.datatype
}
}
impl<'a> DynBufferMut<'a> {
/// Creates a mutable buffer from a mutable slice with whose type has an MPI equivalent.
pub fn new<T: Equivalence>(buf: &'a mut [T]) -> Self {
unsafe {
let datatype = DatatypeRef::from_raw(T::equivalent_datatype().as_raw());
Self::from_raw(buf.as_mut_ptr(), buf.count(), datatype)
}
}
/// Tests whether the buffer type matches `T`.
pub fn is<T: Equivalence>(&self) -> bool {
self.as_datatype().as_raw() == T::equivalent_datatype().as_raw()
}
/// Returns some mutable slice if the type matches `T`, or `None` if it doesn't.
pub fn downcast<T: Equivalence>(mut self) -> Option<&'a mut [T]> {
if self.is::<T>() {
unsafe {
Some(slice::from_raw_parts_mut(
self.as_mut_ptr() as _,
self.len(),
))
}
} else {
None
}
}
/// Creates a buffer from its raw components. The buffer must remain valid for `'a` and the
/// pointer must not be null.
///
/// # Safety
/// - Buffer pointed to by `ptr` must live as long as `'a`. There must be no other
/// live reference to the buffer in Rust.
/// - `ptr` must point to an object that holds `len` elements of the type described by
/// `datatype`.
pub unsafe fn from_raw<T>(ptr: *mut T, len: Count, datatype: DatatypeRef<'a>) -> Self {
debug_assert!(!ptr.is_null());
Self {
ptr: ptr as _,
len,
datatype,
}
}
/// Returns the number of elements in the buffer.
pub fn len(&self) -> usize {
self.count()
.value_as()
.expect("Length of DynBufferMut cannot be expressed as a usize")
}
/// Returns `true` if the buffer is empty
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns the underlying raw pointer.
pub fn as_ptr(&self) -> *const c_void {
self.ptr
}
/// Returns the underlying raw pointer.
pub fn as_mut_ptr(&mut self) -> *mut c_void {
self.ptr
}
/// Reborrows the buffer with a shorter lifetime.
pub fn reborrow(&self) -> DynBuffer {
unsafe { DynBuffer::from_raw(self.as_ptr(), self.count(), self.as_datatype()) }
}
/// Reborrows the buffer mutably with a shorter lifetime.
pub fn reborrow_mut(&mut self) -> DynBufferMut {
unsafe { DynBufferMut::from_raw(self.as_mut_ptr(), self.count(), self.as_datatype()) }
}
/// Makes the buffer immutable.
pub fn downgrade(self) -> DynBuffer<'a> {
unsafe { DynBuffer::from_raw(self.as_ptr(), self.count(), self.as_datatype()) }
}
}
/// A buffer with a user specified count and datatype
///
/// # Safety
///
/// Views can be used to instruct the underlying MPI library to rummage around at arbitrary
/// locations in memory. This might be controlled later on using datatype bounds an slice lengths
/// but for now, all View constructors are marked `unsafe`.
pub struct View<'d, 'b, D, B: ?Sized>
where
D: 'd + Datatype,
B: 'b + Pointer,
{
datatype: &'d D,
count: Count,
buffer: &'b B,
}
impl<'d, 'b, D, B: ?Sized> View<'d, 'b, D, B>
where
D: 'd + Datatype,
B: 'b + Pointer,
{
/// Return a view of `buffer` containing `count` instances of MPI datatype `datatype`.
///
/// # Examples
/// See `examples/contiguous.rs`, `examples/vector.rs`
///
/// # Safety
/// - `datatype` must map an element of `buffer` without exposing any padding bytes or
/// exceeding the bounds of the object.
pub unsafe fn with_count_and_datatype(
buffer: &'b B,
count: Count,
datatype: &'d D,
) -> View<'d, 'b, D, B> {
View {
datatype,
count,
buffer,
}
}
}
unsafe impl<'d, 'b, D, B: ?Sized> AsDatatype for View<'d, 'b, D, B>
where
D: 'd + Datatype,
B: 'b + Pointer,
{
type Out = &'d D;
fn as_datatype(&self) -> Self::Out {
self.datatype
}
}
unsafe impl<'d, 'b, D, B: ?Sized> Collection for View<'d, 'b, D, B>
where
D: 'd + Datatype,
B: 'b + Pointer,
{
fn count(&self) -> Count {
self.count
}
}
unsafe impl<'d, 'b, D, B: ?Sized> Pointer for View<'d, 'b, D, B>
where
D: 'd + Datatype,
B: 'b + Pointer,
{
fn pointer(&self) -> *const c_void {
self.buffer.pointer()
}
}
unsafe impl<'d, 'b, D, B: ?Sized> Buffer for View<'d, 'b, D, B>
where
D: 'd + Datatype,
B: 'b + Pointer,
{
}
/// A buffer with a user specified count and datatype
///
/// # Safety
///
/// Views can be used to instruct the underlying MPI library to rummage around at arbitrary
/// locations in memory. This might be controlled later on using datatype bounds an slice lengths
/// but for now, all View constructors are marked `unsafe`.
pub struct MutView<'d, 'b, D, B: ?Sized>
where
D: 'd + Datatype,
B: 'b + PointerMut,
{
datatype: &'d D,
count: Count,
buffer: &'b mut B,
}
impl<'d, 'b, D, B: ?Sized> MutView<'d, 'b, D, B>
where
D: 'd + Datatype,
B: 'b + PointerMut,
{
/// Return a view of `buffer` containing `count` instances of MPI datatype `datatype`.
///
/// # Examples
/// See `examples/contiguous.rs`, `examples/vector.rs`
///
/// # Safety
/// - `datatype` must map an element of `buffer` without exposing any padding bytes or
/// exceeding the bounds of the object.
pub unsafe fn with_count_and_datatype(
buffer: &'b mut B,
count: Count,
datatype: &'d D,
) -> MutView<'d, 'b, D, B> {
MutView {
datatype,
count,
buffer,
}
}
}
unsafe impl<'d, 'b, D, B: ?Sized> AsDatatype for MutView<'d, 'b, D, B>
where
D: 'd + Datatype,
B: 'b + PointerMut,
{
type Out = &'d D;
fn as_datatype(&self) -> Self::Out {
self.datatype
}
}
unsafe impl<'d, 'b, D, B: ?Sized> Collection for MutView<'d, 'b, D, B>
where
D: 'd + Datatype,
B: 'b + PointerMut,
{
fn count(&self) -> Count {
self.count
}
}
unsafe impl<'d, 'b, D, B: ?Sized> PointerMut for MutView<'d, 'b, D, B>
where
D: 'd + Datatype,
B: 'b + PointerMut,
{
fn pointer_mut(&mut self) -> *mut c_void {
self.buffer.pointer_mut()
}
}
unsafe impl<'d, 'b, D, B: ?Sized> BufferMut for MutView<'d, 'b, D, B>
where
D: 'd + Datatype,
B: 'b + PointerMut,
{
}
/// Describes how a `Buffer` is partitioned by specifying the count of elements and displacement
/// from the start of the buffer for each partition.
pub trait Partitioned {
/// The count of elements in each partition.
fn counts(&self) -> &[Count];
/// The displacement from the start of the buffer for each partition.
fn displs(&self) -> &[Count];
}
/// A buffer that is `Partitioned`
pub trait PartitionedBuffer: Partitioned + Pointer + AsDatatype {}
/// A mutable buffer that is `Partitioned`
pub trait PartitionedBufferMut: Partitioned + PointerMut + AsDatatype {}
/// Adds a partitioning to an existing `Buffer` so that it becomes `Partitioned`
pub struct Partition<'b, B: 'b + ?Sized, C, D> {
buf: &'b B,
counts: C,
displs: D,
}
impl<'b, B: ?Sized, C, D> Partition<'b, B, C, D>
where
B: 'b + Buffer,
C: Borrow<[Count]>,
D: Borrow<[Count]>,
{
/// Partition `buf` using `counts` and `displs`
pub fn new(buf: &B, counts: C, displs: D) -> Partition<B, C, D> {
let n = buf.count();
assert!(counts
.borrow()
.iter()
.zip(displs.borrow().iter())
.all(|(&c, &d)| c + d <= n));
Partition {
buf,
counts,
displs,
}
}
}
unsafe impl<'b, B: ?Sized, C, D> AsDatatype for Partition<'b, B, C, D>
where
B: 'b + AsDatatype,
{
type Out = <B as AsDatatype>::Out;
fn as_datatype(&self) -> Self::Out {
self.buf.as_datatype()
}
}
unsafe impl<'b, B: ?Sized, C, D> Pointer for Partition<'b, B, C, D>
where
B: 'b + Pointer,
{
fn pointer(&self) -> *const c_void {
self.buf.pointer()
}
}
impl<'b, B: ?Sized, C, D> Partitioned for Partition<'b, B, C, D>
where
B: 'b,
C: Borrow<[Count]>,
D: Borrow<[Count]>,
{
fn counts(&self) -> &[Count] {
self.counts.borrow()
}
fn displs(&self) -> &[Count] {
self.displs.borrow()
}
}
impl<'b, B: ?Sized, C, D> PartitionedBuffer for Partition<'b, B, C, D>
where
B: 'b + Pointer + AsDatatype,
C: Borrow<[Count]>,
D: Borrow<[Count]>,
{
}
/// Adds a partitioning to an existing `BufferMut` so that it becomes `Partitioned`
pub struct PartitionMut<'b, B: 'b + ?Sized, C, D> {
buf: &'b mut B,
counts: C,
displs: D,
}
impl<'b, B: ?Sized, C, D> PartitionMut<'b, B, C, D>
where
B: 'b + BufferMut,
C: Borrow<[Count]>,
D: Borrow<[Count]>,
{
/// Partition `buf` using `counts` and `displs`
pub fn new(buf: &mut B, counts: C, displs: D) -> PartitionMut<B, C, D> {
let n = buf.count();
assert!(counts
.borrow()
.iter()
.zip(displs.borrow().iter())
.all(|(&c, &d)| c + d <= n));
PartitionMut {
buf,
counts,
displs,
}
}
}
unsafe impl<'b, B: ?Sized, C, D> AsDatatype for PartitionMut<'b, B, C, D>
where
B: 'b + AsDatatype,
{
type Out = <B as AsDatatype>::Out;
fn as_datatype(&self) -> Self::Out {
self.buf.as_datatype()
}
}
unsafe impl<'b, B: ?Sized, C, D> PointerMut for PartitionMut<'b, B, C, D>
where
B: 'b + PointerMut,
{
fn pointer_mut(&mut self) -> *mut c_void {
self.buf.pointer_mut()
}
}
impl<'b, B: ?Sized, C, D> Partitioned for PartitionMut<'b, B, C, D>
where
B: 'b,
C: Borrow<[Count]>,
D: Borrow<[Count]>,
{
fn counts(&self) -> &[Count] {
self.counts.borrow()
}
fn displs(&self) -> &[Count] {
self.displs.borrow()
}
}
impl<'b, B: ?Sized, C, D> PartitionedBufferMut for PartitionMut<'b, B, C, D>
where
B: 'b + PointerMut + AsDatatype,
C: Borrow<[Count]>,
D: Borrow<[Count]>,
{
}
/// Returns the address of the argument in a format suitable for use with datatype constructors
///
/// # Examples
/// See `examples/structured.rs`
///
/// # Standard section(s)
///
/// 4.1.5
pub fn address_of<T>(x: &T) -> Address {
let x: *const T = x;
unsafe { with_uninitialized(|address| ffi::MPI_Get_address(x as *const c_void, address)).1 }
}