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
use std::convert::TryFrom; use std::fs::{File, OpenOptions}; use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use std::path::Path; use std::slice; use std::{cmp, fmt, io}; use crate::os::{advise, flush, lock, map_anon, map_file, protect, unlock, unmap}; use crate::sealed::FromPtr; use crate::{ AdviseAccess, AdviseUsage, ConvertResult, Error, Extent, Flush, Input, Operation, Protect, Result, Size, Span, SpanMut, }; /// Allocation of one or more read-only sequential pages. /// /// # Examples /// /// ``` /// use vmap::{Map, AdviseAccess, AdviseUsage}; /// use std::path::PathBuf; /// use std::str::from_utf8; /// /// # fn main() -> vmap::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// # std::fs::write(&path, "A cross-platform library for fast and safe memory-mapped IO in Rust")?; /// let (map, file) = Map::with_options().offset(29).len(30).open(&path)?; /// map.advise(AdviseAccess::Sequential, AdviseUsage::WillNeed)?; /// assert_eq!(Ok("fast and safe memory-mapped IO"), from_utf8(&map[..])); /// assert_eq!(Ok("safe"), from_utf8(&map[9..13])); /// # Ok(()) /// # } /// ``` pub struct Map(MapMut); impl Map { /// Returns a new [`Options`] object to create a read-only `Map`. /// /// When used to [`.open()`] a path or [`.map()`] a file, the default /// [`Options`] object is assumed to cover the entire file. /// /// See the [`Options`] type for details on options for modifying the file /// size, specifying offset positions, and selecting specific lengths. /// /// # Examples /// /// ``` /// use vmap::Map; /// use std::path::PathBuf; /// use std::str::from_utf8; /// /// # fn main() -> vmap::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// # std::fs::write(&path, "A cross-platform library for fast and safe memory-mapped IO in Rust")?; /// let (map, file) = Map::with_options() /// .offset(29) /// .len(30) /// .open(&path)?; /// assert_eq!(Ok("fast and safe memory-mapped IO"), from_utf8(&map)); /// # Ok(()) /// # } /// ``` pub fn with_options() -> Options<Self> { Options::new() } /// Creates a new read-only map object using the full range of a file. /// /// The underlying file handle is open as read-only. If there is a need to /// convert the `Map` into a `MapMut`, use `Map::file` with a file handle /// open for writing. If not done, the convertion to `MapMut` will fail. /// /// # Examples /// ``` /// use vmap::Map; /// use std::path::PathBuf; /// use std::str::from_utf8; /// /// # fn main() -> vmap::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// # std::fs::write(&path, "A cross-platform library for fast and safe memory-mapped IO in Rust")?; /// let map = Map::open(&path)?; /// assert_eq!(map.is_empty(), false); /// assert_eq!(Ok("fast and safe memory-mapped IO"), from_utf8(&map[29..59])); /// /// // The file handle is read-only. /// assert!(map.into_map_mut().is_err()); /// # Ok(()) /// # } /// ``` #[deprecated(since = "0.4.0", note = "use Map::with_options().open(path) instead")] pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> { Ok(Self::with_options().open(path)?.0) } /// Create a new map object from a range of a file. /// /// # Examples /// /// ``` /// use vmap::Map; /// use std::path::PathBuf; /// use std::fs::OpenOptions; /// use std::str::from_utf8; /// /// # fn main() -> vmap::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// # std::fs::write(&path, "A cross-platform library for fast and safe memory-mapped IO in Rust")?; /// let file = OpenOptions::new().read(true).open(&path)?; /// let map = Map::file(&file, 29, 30)?; /// assert_eq!(map.is_empty(), false); /// assert_eq!(Ok("fast and safe memory-mapped IO"), from_utf8(&map[..])); /// /// let map = Map::file(&file, 0, file.metadata()?.len() as usize + 1); /// assert!(map.is_err()); /// # Ok(()) /// # } /// ``` #[deprecated( since = "0.4.0", note = "use Map::with_options().offset(off).len(len).map(f) instead" )] pub fn file(f: &File, offset: usize, length: usize) -> Result<Self> { Self::with_options().offset(offset).len(length).map(f) } /// Create a new map object from a maximum range of a file. Unlike `file`, /// the length is only a maximum size to map. If the length of the file /// is less than the requested range, the returned mapping will be /// shortened to match the file. /// /// # Examples /// /// ``` /// use vmap::Map; /// use std::path::PathBuf; /// use std::fs::OpenOptions; /// use std::str::from_utf8; /// /// # fn main() -> vmap::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// # std::fs::write(&path, "A cross-platform library for fast and safe memory-mapped IO in Rust")?; /// let file = OpenOptions::new().read(true).open(&path)?; /// let map = Map::file_max(&file, 0, 5000)?.expect("should be valid range"); /// assert_eq!(map.is_empty(), false); /// assert_eq!(Ok("fast and safe memory-mapped IO"), from_utf8(&map[29..59])); /// /// let map = Map::file_max(&file, 0, file.metadata()?.len() as usize + 1); /// assert!(!map.is_err()); /// /// let map = Map::file_max(&file, 5000, 100)?; /// assert!(map.is_none()); /// # Ok(()) /// # } /// ``` #[deprecated( since = "0.4.0", note = "use Map::with_options().offset(off).len(Extent::Max(len)).map_if(f) instead" )] pub fn file_max(f: &File, offset: usize, max_length: usize) -> Result<Option<Self>> { Self::with_options() .offset(offset) .len(Extent::Max(max_length)) .map_if(f) } /// Transfer ownership of the map into a mutable map. /// /// This will change the protection of the mapping. If the original file /// was not opened with write permissions, this will error. /// /// # Examples /// /// ``` /// use vmap::Map; /// use std::fs::OpenOptions; /// use std::path::PathBuf; /// use std::str::from_utf8; /// # use std::fs; /// /// # fn main() -> vmap::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// # fs::write(&path, b"this is a test")?; /// /// // Map the beginning of the file /// let (map, file) = Map::with_options().write().len(14).open(path)?; /// assert_eq!(Ok("this is a test"), from_utf8(&map[..])); /// /// let mut map = map.into_map_mut()?; /// map[..4].clone_from_slice(b"that"); /// assert_eq!(Ok("that is a test"), from_utf8(&map[..])); /// # Ok(()) /// # } /// ``` pub fn into_map_mut(self) -> ConvertResult<MapMut, Self> { unsafe { let (ptr, len) = Size::page().bounds(self.0.ptr, self.0.len); match protect(ptr, len, Protect::ReadWrite) { Ok(()) => Ok(self.0), Err(err) => Err((err, self)), } } } /// Transfer ownership of the map into a mutable map. /// /// This will change the protection of the mapping. If the original file /// was not opened with write permissions, this will error. /// /// This will cause the original map to be dropped if the protection change /// fails. Using `into_map_mut` allows the original map to be retained in the /// case of a failure. #[deprecated(since = "0.4.0", note = "use try_into or into_map_mut instead")] pub fn make_mut(self) -> Result<MapMut> { Ok(self.into_map_mut()?) } /// Updates the advise for the entire mapped region.. pub fn advise(&self, access: AdviseAccess, usage: AdviseUsage) -> Result<()> { self.0.advise(access, usage) } /// Updates the advise for a specific range of the mapped region. pub fn advise_range( &self, off: usize, len: usize, access: AdviseAccess, usage: AdviseUsage, ) -> Result<()> { self.0.advise_range(off, len, access, usage) } /// Lock all mapped physical pages into memory. pub fn lock(&self) -> Result<()> { self.0.lock() } /// Lock a range of physical pages into memory. pub fn lock_range(&self, off: usize, len: usize) -> Result<()> { self.0.lock_range(off, len) } /// Unlock all mapped physical pages into memory. pub fn unlock(&self) -> Result<()> { self.0.unlock() } /// Unlock a range of physical pages into memory. pub fn unlock_range(&self, off: usize, len: usize) -> Result<()> { self.0.unlock_range(off, len) } } impl FromPtr for Map { unsafe fn from_ptr(ptr: *mut u8, len: usize) -> Self { Self(MapMut::from_ptr(ptr, len)) } } impl Span for Map { #[inline] fn len(&self) -> usize { self.0.len() } #[inline] fn as_ptr(&self) -> *const u8 { self.0.as_ptr() } } impl Deref for Map { type Target = [u8]; #[inline] fn deref(&self) -> &[u8] { unsafe { slice::from_raw_parts(self.0.ptr, self.0.len) } } } impl AsRef<[u8]> for Map { #[inline] fn as_ref(&self) -> &[u8] { self.deref() } } impl TryFrom<MapMut> for Map { type Error = (Error, MapMut); fn try_from(map: MapMut) -> ConvertResult<Self, MapMut> { map.into_map() } } impl fmt::Debug for Map { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("Map") .field("ptr", &self.0.ptr) .field("len", &self.0.len) .finish() } } /// Allocation of one or more read-write sequential pages. #[derive(Debug)] pub struct MapMut { ptr: *mut u8, len: usize, } impl MapMut { /// Returns a new `Options` object to create a writable `MapMut`. /// /// When used to [`.open()`] a path or [`.map()`] a file, the default /// [`Options`] object is assumed to cover the entire file. /// /// See the [`Options`] type for details on options for modifying the file /// size, specifying offset positions, and selecting specific lengths. /// /// # Examples /// /// ``` /// use vmap::{MapMut, Flush}; /// use std::path::PathBuf; /// use std::str::from_utf8; /// /// # fn main() -> vmap::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// # std::fs::write(&path, "A cross-platform library for fast and safe memory-mapped IO in Rust")?; /// let (mut map, file) = MapMut::with_options() /// .offset(29) /// .len(30) /// .open(&path)?; /// assert_eq!(Ok("fast and safe memory-mapped IO"), from_utf8(&map)); /// map[..4].clone_from_slice(b"nice"); /// /// map.flush_range(&file, 0, 4, Flush::Sync); /// /// assert_eq!(Ok("nice and safe memory-mapped IO"), from_utf8(&map)); /// # Ok(()) /// # } /// ``` pub fn with_options() -> Options<Self> { let mut opts = Options::new(); opts.write(); opts } /// Create a new anonymous mapping at least as large as the hint. /// /// # Examples /// /// ``` /// use vmap::{MapMut, Protect}; /// use std::str::from_utf8; /// /// # fn main() -> vmap::Result<()> { /// let mut map = MapMut::new(200)?; /// map[..4].clone_from_slice(b"test"); /// assert_eq!(Ok("test"), from_utf8(&map[..4])); /// # Ok(()) /// # } /// ``` pub fn new(hint: usize) -> Result<Self> { Self::with_options().len(Extent::Min(hint)).alloc() } /// Creates a new read/write map object using the full range of a file. /// /// # Examples /// ``` /// use vmap::MapMut; /// use std::path::PathBuf; /// use std::fs::OpenOptions; /// use std::str::from_utf8; /// /// # fn main() -> vmap::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// # std::fs::write(&path, "A cross-platform library for fast and safe memory-mapped IO in Rust")?; /// let map = MapMut::open(&path)?; /// assert_eq!(map.is_empty(), false); /// assert_eq!(Ok("fast and safe memory-mapped IO"), from_utf8(&map[29..59])); /// # Ok(()) /// # } /// ``` #[deprecated( since = "0.4.0", note = "use MapMut::with_options().open(path) instead" )] pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> { Ok(Self::with_options().open(path)?.0) } /// Create a new mutable map object from a range of a file. #[deprecated( since = "0.4.0", note = "use MapMut::with_options().offset(off).len(len).map(f) instead" )] pub fn file(f: &File, offset: usize, length: usize) -> Result<Self> { Self::with_options().offset(offset).len(length).map(f) } /// Create a new mutable map object from a maximum range of a file. Unlike /// `file`, the length is only a maximum size to map. If the length of the /// file is less than the requested range, the returned mapping will be /// shortened to match the file. #[deprecated( since = "0.4.0", note = "use MapMut::with_options().offset(off).len(Extent::Max(len)).map_if(f) instead" )] pub fn file_max(f: &File, offset: usize, max_length: usize) -> Result<Option<Self>> { Self::with_options() .offset(offset) .len(Extent::Max(max_length)) .map_if(f) } /// Create a new private map object from a range of a file. /// /// Initially, the mapping will be shared with other processes, but writes /// will be kept private. /// /// # Examples /// /// ``` /// use vmap::MapMut; /// use std::path::PathBuf; /// use std::fs::OpenOptions; /// use std::str::from_utf8; /// /// # fn main() -> vmap::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// # std::fs::write(&path, "A cross-platform library for fast and safe memory-mapped IO in Rust")?; /// let file = OpenOptions::new().read(true).open(&path)?; /// /// let mut map = MapMut::copy(&file, 29, 30)?; /// assert_eq!(map.is_empty(), false); /// assert_eq!(Ok("fast and safe memory-mapped IO"), from_utf8(&map[..])); /// /// map[..4].clone_from_slice(b"nice"); /// /// assert_eq!(Ok("nice and safe memory-mapped IO"), from_utf8(&map[..])); /// # Ok(()) /// # } /// ``` #[deprecated( since = "0.4.0", note = "use MapMut::with_options().copy().offset(off).len(len).map(f) instead" )] pub fn copy(f: &File, offset: usize, length: usize) -> Result<Self> { Self::with_options() .copy() .offset(offset) .len(length) .map(f) } /// Create a new private map object from a range of a file. Unlike /// `copy`, the length is only a maximum size to map. If the length of the /// file is less than the requested range, the returned mapping will be /// shortened to match the file. /// /// Initially, the mapping will be shared with other processes, but writes /// will be kept private. #[deprecated( since = "0.4.0", note = "use MapMut::with_options().copy().offset(off).len(Extent::Max(len)).map_if(f) instead" )] pub fn copy_max(f: &File, offset: usize, max_length: usize) -> Result<Option<Self>> { Self::with_options() .copy() .offset(offset) .len(Extent::Max(max_length)) .map_if(f) } /// Transfer ownership of the map into a mutable map. /// /// This will change the protection of the mapping. If the original file /// was not opened with write permissions, this will error. /// /// # Examples /// /// ``` /// use vmap::MapMut; /// use std::fs::OpenOptions; /// use std::path::PathBuf; /// use std::str::from_utf8; /// # use std::fs; /// /// # fn main() -> vmap::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// # fs::write(&path, b"this is a test")?; /// let (mut map, file) = MapMut::with_options().len(14).open(&path)?; /// assert_eq!(Ok("this is a test"), from_utf8(&map[..])); /// /// map[..4].clone_from_slice(b"that"); /// /// let map = map.into_map()?; /// assert_eq!(Ok("that is a test"), from_utf8(&map[..])); /// # Ok(()) /// # } /// ``` pub fn into_map(self) -> ConvertResult<Map, Self> { unsafe { let (ptr, len) = Size::page().bounds(self.ptr, self.len); match protect(ptr, len, Protect::ReadWrite) { Ok(()) => Ok(Map(self)), Err(err) => Err((err, self)), } } } /// Transfer ownership of the map into a mutable map. /// /// This will change the protection of the mapping. If the original file /// was not opened with write permissions, this will error. /// /// This will cause the original map to be dropped if the protection change /// fails. Using `into_map` allows the original map to be retained in the /// case of a failure. #[deprecated(since = "0.4.0", note = "use try_into or into_map instead")] pub fn make_read_only(self) -> Result<Map> { Ok(self.into_map()?) } /// Writes modifications back to the filesystem. /// /// Flushes will happen automatically, but this will invoke a flush and /// return any errors with doing so. pub fn flush(&self, file: &File, mode: Flush) -> Result<()> { unsafe { let (ptr, len) = Size::page().bounds(self.ptr, self.len); flush(ptr, file, len, mode) } } /// Writes modifications back to the filesystem for a sub-range of the map. /// /// Flushes will happen automatically, but this will invoke a flush and /// return any errors with doing so. pub fn flush_range(&self, file: &File, off: usize, len: usize, mode: Flush) -> Result<()> { if off + len > self.len { Err(Error::input(Operation::Flush, Input::InvalidRange)) } else { unsafe { let (ptr, len) = Size::page().bounds(self.ptr.add(off), len); flush(ptr, file, len, mode) } } } /// Updates the advise for the entire mapped region.. pub fn advise(&self, access: AdviseAccess, usage: AdviseUsage) -> Result<()> { unsafe { let (ptr, len) = Size::page().bounds(self.ptr, self.len); advise(ptr, len, access, usage) } } /// Updates the advise for a specific range of the mapped region. pub fn advise_range( &self, off: usize, len: usize, access: AdviseAccess, usage: AdviseUsage, ) -> Result<()> { if off + len > self.len { Err(Error::input(Operation::Advise, Input::InvalidRange)) } else { unsafe { let (ptr, len) = Size::page().bounds(self.ptr.add(off), len); advise(ptr, len, access, usage) } } } /// Lock all mapped physical pages into memory. pub fn lock(&self) -> Result<()> { unsafe { let (ptr, len) = Size::page().bounds(self.ptr, self.len); lock(ptr, len) } } /// Lock a range of physical pages into memory. pub fn lock_range(&self, off: usize, len: usize) -> Result<()> { if off + len > self.len { Err(Error::input(Operation::Lock, Input::InvalidRange)) } else { unsafe { let (ptr, len) = Size::page().bounds(self.ptr.add(off), len); lock(ptr, len) } } } /// Unlock all mapped physical pages into memory. pub fn unlock(&self) -> Result<()> { unsafe { let (ptr, len) = Size::page().bounds(self.ptr, self.len); unlock(ptr, len) } } /// Unlock a range of physical pages into memory. pub fn unlock_range(&self, off: usize, len: usize) -> Result<()> { if off + len > self.len { Err(Error::input(Operation::Unlock, Input::InvalidRange)) } else { unsafe { let (ptr, len) = Size::page().bounds(self.ptr.add(off), len); unlock(ptr, len) } } } } impl FromPtr for MapMut { unsafe fn from_ptr(ptr: *mut u8, len: usize) -> Self { Self { ptr, len } } } impl Span for MapMut { #[inline] fn len(&self) -> usize { self.len } #[inline] fn as_ptr(&self) -> *const u8 { self.ptr } } impl SpanMut for MapMut { #[inline] fn as_mut_ptr(&mut self) -> *mut u8 { self.ptr } } impl Drop for MapMut { fn drop(&mut self) { unsafe { if self.len > 0 { let (ptr, len) = Size::alloc().bounds(self.ptr, self.len); unmap(ptr, len).unwrap_or_default(); } } } } impl Deref for MapMut { type Target = [u8]; #[inline] fn deref(&self) -> &[u8] { unsafe { slice::from_raw_parts(self.ptr, self.len) } } } impl DerefMut for MapMut { #[inline] fn deref_mut(&mut self) -> &mut [u8] { unsafe { slice::from_raw_parts_mut(self.ptr, self.len) } } } impl AsRef<[u8]> for MapMut { #[inline] fn as_ref(&self) -> &[u8] { self.deref() } } impl AsMut<[u8]> for MapMut { #[inline] fn as_mut(&mut self) -> &mut [u8] { self.deref_mut() } } impl TryFrom<Map> for MapMut { type Error = (Error, Map); fn try_from(map: Map) -> ConvertResult<Self, Map> { map.into_map_mut() } } /// Options and flags which can be used to configure how a map is allocated. /// /// This builder exposes the ability to configure how a [`Map`] or a [`MapMut`] /// is allocated. These options can be used to either map a file or allocate /// an anonymous memory region. For file-based operations, a `std::fs::OpenOptions` /// value is maintained to match the desired abilities between the mapping and /// the underlying resource. This allows the creation, truncation, and resizing /// of a file to be coordinated when allocating a named map. For both mapping /// and anonymous allocations the option can also specify an offset and a /// mapping length. /// /// The `T` must either be a [`Map`] or a [`MapMut`]. Generally, this will be /// created by [`Map::with_options()`] or [`MapMut::with_options()`], then /// chain calls to methods to set each option, then call either [`.open()`], /// [`.map()`], or [`.alloc()`]. This will return a [`Result`] with the correct /// [`Map`] or [`MapMut`] inside. Additionally, there are [`.open_if()`] and /// [`.map_if()`] variations which instead return a [`Result`] containing an /// `Option<T>`. These return `Ok(None)` if the attempted range lies outside /// of the file rather than an `Err`. /// /// Without specifying a size, the options defaults to either the full size of /// the file when using [`.open()`] or [`.map()`]. When using [`.alloc()`], the default /// size will be a single unit of allocation granularity. /// /// [`Map`]: struct.Map.html /// [`MapMut`]: struct.MapMut.html /// [`Map::with_options()`]: struct.Map.html#method.with_options /// [`MapMut::with_options()`]: struct.MapMut.html#method.with_options /// [`.open()`]: #method.open /// [`.open_if()`]: #method.open_if /// [`.map()`]: #method.map /// [`.map_if()`]: #method.map_if /// [`.alloc()`]: #method.alloc /// [`Result`]: type.Result.html pub struct Options<T: FromPtr> { open_options: OpenOptions, resize: Extent, len: Extent, offset: usize, protect: Protect, truncate: bool, phantom: PhantomData<T>, } impl<T: FromPtr> Options<T> { /// Creates a new [`Options`] value with a default state. /// /// Generally, [`Map::with_options()`] or [`MapMut::with_options()`] is the /// preferred way to create options. /// /// [`Options`]: struct.Options.html /// [`Map::with_options()`]: struct.Map.html#method.with_options /// [`MapMut::with_options()`]: struct.MapMut.html#method.with_options pub fn new() -> Self { let mut open_options = OpenOptions::new(); open_options.read(true); Self { open_options, resize: Extent::End, len: Extent::End, offset: 0, protect: Protect::ReadOnly, truncate: false, phantom: PhantomData, } } /// Sets the option for write access. /// /// This is applied automatically when using [`MapMut::with_options()`]. /// This can be useful with [`Map`] when there is a future intent to call /// [`Map::into_map_mut()`]. /// /// # Examples /// /// ``` /// use vmap::Map; /// /// # fn main() -> vmap::Result<()> { /// let (map, file) = Map::with_options().open("README.md")?; /// assert!(map.into_map_mut().is_err()); /// /// let (map, file) = Map::with_options().write().open("README.md")?; /// assert!(map.into_map_mut().is_ok()); /// # Ok(()) /// # } /// ``` /// /// [`MapMut::with_options()`]: struct.MapMut.html#method.with_options /// [`Map`]: struct.Map.html /// [`Map::into_map_mut()`]: struct.Map.html#method.into_map_mut pub fn write(&mut self) -> &mut Self { self.open_options.write(true); self.protect = Protect::ReadWrite; self } /// Sets the option for copy-on-write access. /// /// This efficiently implements a copy to an underlying modifiable /// resource. The allocated memory can be shared between multiple /// unmodified instances, and the copy operation is deferred until the /// first write. When used for an anonymous allocation, the deffered copy /// can be used in a child process. /// /// # Examples /// /// ``` /// use vmap::MapMut; /// /// # fn main() -> vmap::Result<()> { /// let (mut map1, file) = MapMut::with_options().copy().open("README.md")?; /// let (mut map2, _) = MapMut::with_options().copy().open("README.md")?; /// let first = map1[0]; /// /// map1[0] = b'X'; /// /// assert_eq!(first, map2[0]); /// # Ok(()) /// # } /// ``` /// /// [`MapMut::with_options()`]: struct.MapMut.html#method.with_options /// [`Map`]: struct.Map.html /// [`Map::into_map_mut()`]: struct.Map.html#method.into_map_mut pub fn copy(&mut self) -> &mut Self { self.open_options.write(false); self.protect = Protect::ReadCopy; self } /// Sets the option to create a new file, or open it if it already exists. /// /// This only applies when using [`.open()`] or [`.open_if()`]. In order for the /// file to be created, [`.write()`] access must be used. /// /// # Examples /// /// ``` /// use vmap::{Map, MapMut}; /// use std::path::PathBuf; /// /// # fn main() -> vmap::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// let (mut map, file) = MapMut::with_options().create(true).resize(100).open(&path)?; /// assert_eq!(100, map.len()); /// assert_eq!(b"\0\0\0\0", &map[..4]); /// /// map[..4].clone_from_slice(b"test"); /// /// let (map, file) = Map::with_options().open(&path)?; /// assert_eq!(100, map.len()); /// assert_eq!(b"test", &map[..4]); /// # Ok(()) /// # } /// ``` /// /// [`.open()`]: #method.open /// [`.open_if()`]: #method.open_if /// [`.write()`]: #method.write pub fn create(&mut self, create: bool) -> &mut Self { self.open_options.create(create); self } /// Sets the option to create a new file, failing if it already exists. /// /// This option is useful because it is atomic. Otherwise between checking /// whether a file exists and creating a new one, the file may have been /// created by another process (a TOCTOU race condition / attack). /// /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are /// ignored. /// /// This only applies when using [`.open()`] or [`.open_if()`]. In order for the /// file to be created, [`.write()`] access must be used. /// /// # Examples /// /// ``` /// use vmap::MapMut; /// use std::path::PathBuf; /// /// # fn main() -> vmap::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// /// let (map, file) = MapMut::with_options().create_new(true).resize(10).open(&path)?; /// assert_eq!(10, map.len()); /// assert!(MapMut::with_options().create_new(true).open(&path).is_err()); /// # Ok(()) /// # } /// ``` /// /// [`.create()`]: #method.create /// [`.truncate()`]: #method.truncate /// [`.open()`]: #method.open /// [`.open_if()`]: #method.open_if /// [`.write()`]: #method.write pub fn create_new(&mut self, create_new: bool) -> &mut Self { self.open_options.create_new(create_new); self } /// Sets the option for truncating a previous file. /// /// If a file is successfully opened with this option set it will truncate /// the file to 0 length if it already exists. Given that the file will now /// be empty, a [`.resize()`] should be used. /// /// In order for the file to be truncated, [`.write()`] access must be used. /// /// # Examples /// /// ``` /// use vmap::MapMut; /// use std::path::PathBuf; /// /// # fn main() -> vmap::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// /// { /// let (mut map, file) = MapMut::with_options() /// .create(true) /// .truncate(true) /// .resize(4) /// .open(&path)?; /// assert_eq!(b"\0\0\0\0", &map[..]); /// map[..4].clone_from_slice(b"test"); /// assert_eq!(b"test", &map[..]); /// } /// /// let (mut map, file) = MapMut::with_options().truncate(true).resize(4).open(&path)?; /// assert_eq!(b"\0\0\0\0", &map[..]); /// # Ok(()) /// # } /// ``` /// /// [`.resize()`]: #method.resize /// [`.write()`]: #method.write pub fn truncate(&mut self, truncate: bool) -> &mut Self { self.open_options.truncate(truncate); self.truncate = truncate; self } /// Sets the byte offset into the mapping. /// /// For file-based mappings, the offset defines the starting byte range /// from the beginning of the resource. This must be within the range of /// the file. /// /// # Examples /// /// ``` /// use vmap::Map; /// use std::path::PathBuf; /// use std::str::from_utf8; /// use std::fs; /// /// # fn main() -> vmap::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// fs::write(&path, b"this is a test")?; /// /// let (map, file) = Map::with_options().offset(10).open(path)?; /// assert_eq!(Ok("test"), from_utf8(&map[..])); /// # Ok(()) /// # } /// ``` pub fn offset(&mut self, offset: usize) -> &mut Self { self.offset = offset; self } /// Sets the byte length extent of the mapping. /// /// For file-based mappings, this length must be available in the /// underlying resource, including any [`.offset()`]. When not specified, /// the default length is implied to be [`Extent::End`]. /// /// # Length with `Extent::End` /// /// With this value, the length extent is set to the end of the underlying /// resource. This is the default if no `.len()` is applied, but this can /// be set to override a prior setting if desired. /// /// For anonymous mappings, it is generally preferred to use a different /// extent strategy. Without setting any other extent, the default length /// is a single allocation unit of granularity. /// /// # Length with `Extent::Exact` /// /// Using an exact extent option will instruct the map to cover an exact /// byte length. That is, it will not consider the length of the underlying /// resource, if any. For file-based mappings, this length must be /// available in the file. For anonymous mappings, this is the minimum size /// that will be allocated, however, the resulting map will be sized /// exactly to this size. /// /// A `usize` may be used as an [`Extent::Exact`] through the `usize` /// implementation of [`Into<Extent>`]. /// /// ``` /// use vmap::{Map, MapMut}; /// use std::path::PathBuf; /// use std::str::from_utf8; /// use std::fs; /// /// # fn main() -> vmap::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// fs::write(&path, b"this is a test")?; /// /// let (map, file) = Map::with_options() /// .len(4) // or .len(Extent::Exaxt(4)) /// .open(&path)?; /// assert_eq!(Ok("this"), from_utf8(&map[..])); /// /// let mut anon = MapMut::with_options() /// .len(4) /// .alloc()?; /// assert_eq!(4, anon.len()); /// # Ok(()) /// # } /// ``` /// /// # Length with `Extent::Min` /// /// The minimum extent strategy creates a mapping that is at least the /// desired byte length, but may be larger. When applied to a file-based /// mapping, this ensures that the resulting memory region covers a minimum /// extent, but otherwise covers to the end of the file. For an anonymous /// map, this ensures the allocated region meets the minimum size required, /// but allows accessing the remaining allocated space that would otherwise /// be unusable. /// /// ``` /// use vmap::{Extent, Map, MapMut, Size}; /// use std::path::PathBuf; /// use std::str::from_utf8; /// use std::fs; /// /// # fn main() -> vmap::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// fs::write(&path, b"this is a test")?; /// /// let (map, file) = Map::with_options() /// .offset(5) /// .len(Extent::Min(4)) /// .open(&path)?; /// assert_eq!(9, map.len()); /// assert_eq!(Ok("is a test"), from_utf8(&map[..])); /// /// assert!( /// Map::with_options() /// .len(Extent::Min(100)) /// .open_if(&path)? /// .0 /// .is_none() /// ); /// /// let mut anon = MapMut::with_options() /// .len(Extent::Min(2000)) /// .alloc()?; /// assert_eq!(Size::alloc().size(1), anon.len()); /// # Ok(()) /// # } /// ``` /// /// # Length with `Extent::Max` /// /// The maximum extent strategy creates a mapping that is no larger than /// the desired byte length, but may be smaller. When applied to a file- /// based mapping, this will ensure that the resulting /// /// ``` /// use vmap::{Extent, Map, MapMut}; /// use std::path::PathBuf; /// use std::str::from_utf8; /// use std::fs; /// /// # fn main() -> vmap::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// fs::write(&path, b"this is a test")?; /// /// let (map, file) = Map::with_options() /// .offset(5) /// .len(Extent::Max(100)) /// .open(&path)?; /// assert_eq!(9, map.len()); /// assert_eq!(Ok("is a test"), from_utf8(&map[..])); /// /// let mut anon = MapMut::with_options() /// .len(Extent::Max(2000)) /// .alloc()?; /// assert_eq!(2000, anon.len()); /// # Ok(()) /// # } /// ``` /// /// [`Into<Extent>`]: enum.Extent.html#impl-From<usize> /// [`Extent::End`]: enum.Extent.html#variant.End /// [`Extent::Exact`]: enum.Extent.html#variant.Exact /// [`Extent::Min`]: enum.Extent.html#variant.Min /// [`Extent::Max`]: enum.Extent.html#variant.Max /// [`.offset()`]: #method.offset /// [`.len_min()`]: #method.len_min /// [`.len_max()`]: #method.len_max pub fn len<E: Into<Extent>>(&mut self, value: E) -> &mut Self { self.len = value.into(); self } /// Sets the option to resize the file prior to mapping. /// /// When mapping to a file using [`.open()`], [`.open_if()`], [`.map()`], /// or [`.map_if()`] this options conditionally adjusts the length of the /// underlying resource to the desired size by calling [`.set_len()`] on /// the [`File`]. /// /// In order for the file to be resized, [`.write()`] access must be used. /// /// This has no affect on anonymous mappings. /// /// # Resize with `Extent::End` /// /// This implies resizing to the current size of the file. In other words, /// no resize is performed, and this is the default strategy. /// /// # Resize with `Extent::Exact` /// /// Using an exact extent option will instruct the map to cover an exact /// byte length. That is, it will not consider the length of the underlying /// resource, if any. For file-based mappings, this length must be /// available in the file. For anonymous mappings, this is the minimum size /// that will be allocated, however, the resulting map will be sized /// exactly to this size. /// /// A `usize` may be used as an [`Extent::Exact`] through the `usize` /// implementation of [`Into<Extent>`]. /// /// ``` /// use vmap::Map; /// use std::path::PathBuf; /// use std::str::from_utf8; /// use std::fs; /// /// # fn main() -> vmap::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// fs::write(&path, b"this is a test")?; /// /// let (map, file) = Map::with_options() /// .write() /// .resize(7) // or .resize(Extent::Exact(7)) /// .open(&path)?; /// assert_eq!(7, map.len()); /// assert_eq!(Ok("this is"), from_utf8(&map[..])); /// # Ok(()) /// # } /// ``` /// /// # Resize with `Extent::Min` /// /// The minimum extent strategy resizes the file to be at least the /// desired byte length, but may be larger. If the file is already equal /// to or larger than the extent, no resize is performed. /// /// ``` /// use vmap::{Extent, Map}; /// use std::path::PathBuf; /// use std::str::from_utf8; /// use std::fs; /// /// # fn main() -> vmap::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// /// fs::write(&path, b"this")?; /// /// { /// let (map, file) = Map::with_options() /// .write() /// .resize(Extent::Min(7)) /// .open(&path)?; /// assert_eq!(7, map.len()); /// assert_eq!(Ok("this\0\0\0"), from_utf8(&map[..])); /// } /// /// fs::write(&path, b"this is a test")?; /// /// let (map, file) = Map::with_options() /// .write() /// .resize(Extent::Min(7)) /// .open(&path)?; /// assert_eq!(14, map.len()); /// assert_eq!(Ok("this is a test"), from_utf8(&map[..])); /// # Ok(()) /// # } /// ``` /// /// # Resize with `Extent::Max` /// /// The maximum extent strategy resizes the file to be no larger than the /// desired byte length, but may be smaller. If the file is already equal /// to or smaller than the extent, no resize is performed. /// /// ``` /// use vmap::{Extent, Map}; /// use std::path::PathBuf; /// use std::str::from_utf8; /// use std::fs; /// /// # fn main() -> vmap::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// fs::write(&path, b"this")?; /// /// { /// let (map, file) = Map::with_options() /// .write() /// .resize(Extent::Max(7)) /// .open(&path)?; /// assert_eq!(4, map.len()); /// assert_eq!(Ok("this"), from_utf8(&map[..])); /// } /// /// fs::write(&path, b"this is a test")?; /// /// let (map, file) = Map::with_options() /// .write() /// .resize(Extent::Max(7)) /// .open(&path)?; /// assert_eq!(7, map.len()); /// assert_eq!(Ok("this is"), from_utf8(&map[..])); /// # Ok(()) /// # } /// ``` /// /// [`.open()`]: #method.open /// [`.open_if()`]: #method.open_if /// [`.map()`]: #method.map /// [`.map_if()`]: #method.map_if /// [`.set_len()`]: https://doc.rust-lang.org/std/fs/struct.File.html#method.set_len /// [`File`]: https://doc.rust-lang.org/std/fs/struct.File.html /// [`.write()`]: #method.write /// [`Into<Extent>`]: enum.Extent.html#impl-From<usize> /// [`Extent::End`]: enum.Extent.html#variant.End /// [`Extent::Exact`]: enum.Extent.html#variant.Exact /// [`Extent::Min`]: enum.Extent.html#variant.Min /// [`Extent::Max`]: enum.Extent.html#variant.Max pub fn resize<E: Into<Extent>>(&mut self, value: E) -> &mut Self { self.resize = value.into(); self } /// Opens and maps a file using the current options specified by `self`. /// /// Unlike [`.open_if()`], when the requested offset or length lies outside of /// the underlying file, an error is returned. /// /// The returned [`File`] can be discarded if no longer needed to [`.flush()`] /// or [`.map()`] other regions. This does not need to be kept open in order to /// use the mapped value. /// /// # Examples /// /// ``` /// use vmap::Map; /// use std::path::PathBuf; /// use std::fs; /// /// # fn main() -> std::io::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// fs::write(&path, b"this is a test")?; /// /// assert!(Map::with_options().len(4).open(&path).is_ok()); /// assert!(Map::with_options().len(25).open(&path).is_err()); /// # Ok(()) /// # } /// ``` /// /// [`.open_if()`]: #method.open_if /// [`.map()`]: #method.map /// [`.flush()`]: struct.MapMut.html#method.flush /// [`File`]: https://doc.rust-lang.org/std/fs/struct.File.html pub fn open<P: AsRef<Path>>(&self, path: P) -> Result<(T, File)> { let f = self.open_options.open(path).map_err(map_file_err)?; Ok((self.map(&f)?, f)) } /// Opens and maps a file with the options specified by `self` if the /// provided byte range is valid. /// /// Unlike [`.open()`], when the requested offset or length lies outside of /// the underlying file, `Ok(None)` will be returned rather than an error. /// /// The returned [`File`] can be discarded if no longer needed to [`.flush()`] /// or [`.map()`] other regions. This does not need to be kept open in order to /// use the mapped value. /// /// # Examples /// /// ``` /// use vmap::Map; /// use std::path::PathBuf; /// use std::fs; /// /// # fn main() -> std::io::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// fs::write(&path, b"this is a test")?; /// /// assert!(Map::with_options().len(4).open_if(&path).is_ok()); /// /// let result = Map::with_options().len(25).open_if(&path); /// assert!(result.is_ok()); /// assert!(result.unwrap().0.is_none()); /// # Ok(()) /// # } /// ``` /// /// [`.open()`]: #method.open /// [`.map()`]: #method.map /// [`.flush()`]: struct.MapMut.html#method.flush /// [`File`]: https://doc.rust-lang.org/std/fs/struct.File.html pub fn open_if<P: AsRef<Path>>(&self, path: P) -> Result<(Option<T>, File)> { let f = self.open_options.open(path).map_err(map_file_err)?; Ok((self.map_if(&f)?, f)) } /// Maps an open `File` using the current options specified by `self`. /// /// Unlike [`.map_if()`], when the requested offset or length lies outside of /// the underlying file, an error is returned. /// /// # Examples /// /// ``` /// use vmap::Map; /// use std::path::PathBuf; /// use std::fs::OpenOptions; /// /// # fn main() -> std::io::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// let f = OpenOptions::new() /// .read(true) /// .write(true) /// .create(true) /// .open(path)?; /// f.set_len(8)?; /// /// assert!(Map::with_options().len(4).map(&f).is_ok()); /// assert!(Map::with_options().len(25).map(&f).is_err()); /// # Ok(()) /// # } /// ``` /// /// [`.map_if()`]: #method.map_if pub fn map(&self, f: &File) -> Result<T> { self.map_if(f)? .ok_or_else(|| Error::input(Operation::MapFile, Input::InvalidRange)) } /// Maps an open `File` with the options specified by `self` if the provided /// byte range is valid. /// /// Unlike [`.map()`], when the requested offset or length lies outside of /// the underlying file, `Ok(None)` will be returned rather than an error. /// /// # Examples /// /// ``` /// use vmap::Map; /// use std::path::PathBuf; /// use std::fs::OpenOptions; /// /// # fn main() -> std::io::Result<()> { /// # let tmp = tempdir::TempDir::new("vmap")?; /// let path: PathBuf = /* path to file */ /// # tmp.path().join("example"); /// let f = OpenOptions::new() /// .read(true) /// .write(true) /// .create(true) /// .open(path)?; /// f.set_len(8)?; /// /// assert!(Map::with_options().len(4).map_if(&f).is_ok()); /// /// let result = Map::with_options().len(25).map_if(&f); /// assert!(result.is_ok()); /// assert!(result.unwrap().is_none()); /// # Ok(()) /// # } /// ``` /// /// [`.map()`]: #method.map pub fn map_if(&self, f: &File) -> Result<Option<T>> { let off = self.offset; let mut flen = f.metadata().map_err(map_file_err)?.len() as usize; let resize = |sz: usize| f.set_len(sz as u64).map(|_| sz).map_err(map_file_err); if self.truncate && flen > 0 { flen = resize(0)?; } flen = match self.resize { Extent::Exact(sz) => resize(sz)?, Extent::Min(sz) if sz > flen => resize(sz)?, Extent::Max(sz) if sz < flen => resize(sz)?, _ => flen, }; if flen < off { return Ok(None); } let max = flen - off; let len = match self.len { Extent::Min(l) | Extent::Exact(l) if l > max => return Ok(None), Extent::Min(_) | Extent::End => max, Extent::Max(l) => cmp::min(l, max), Extent::Exact(l) => l, }; let mapoff = Size::alloc().truncate(off); let maplen = len + (off - mapoff); let ptr = map_file(f, mapoff, maplen, self.protect)?; unsafe { Ok(Some(T::from_ptr(ptr.add(off - mapoff), len))) } } /// Creates an anonymous allocation using the options specified by `self`. /// /// # Examples /// /// ``` /// use vmap::{Extent, MapMut}; /// /// # fn main() -> vmap::Result<()> { /// let map = MapMut::with_options().len(Extent::Min(500)).alloc()?; /// assert!(map.len() >= 500); /// # Ok(()) /// # } /// ``` pub fn alloc(&self) -> Result<T> { let off = Size::page().offset(self.offset); let len = match self.len { Extent::End => Size::alloc().round(off + 1) - off, Extent::Min(l) => Size::alloc().round(off + l) - off, Extent::Max(l) | Extent::Exact(l) => l, }; let ptr = map_anon(off + len, self.protect)?; unsafe { Ok(T::from_ptr(ptr.add(off), len)) } } } impl<T: FromPtr> Default for Options<T> { fn default() -> Self { Self::new() } } fn map_file_err(e: io::Error) -> Error { Error::io(Operation::MapFile, e) }