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
use std::fs::{File, remove_file};
use std::path::{Path, PathBuf};
#[cfg(not(target_os = "linux"))]
use std::ptr::{drop_in_place, write};
use fs4::FileExt;
use memmap2::{Mmap, MmapMut, MmapOptions, MmapAsRawDesc};
use crate::{MetaData, MmapFileExt, MmapFileMutExt};
use crate::disk::MmapFileMutType;
use crate::error::{Error, ErrorKind};
use crate::options::Options;
use crate::utils::{create_file, open_exist_file_with_append, open_or_create_file, open_read_only_file, sync_parent};
remmap!(Path);
/// DiskMmapFile contains an immutable mmap buffer
/// and a read-only file.
pub struct DiskMmapFile {
pub(crate) mmap: Mmap,
pub(crate) file: File,
pub(crate) path: PathBuf,
exec: bool,
}
impl_mmap_file_ext!(DiskMmapFile);
impl DiskMmapFile {
/// Open a readable memory map backed by a file
///
/// # Examples
///
/// ```ignore
/// use fmmap::MmapFileExt;
/// use fmmap::raw::DiskMmapFile;
/// use std::fs::{remove_file, File};
/// use std::io::Write;
/// # use scopeguard::defer;
///
/// # let mut file = File::create("disk_open_test.txt").unwrap();
/// # defer!(remove_file("disk_open_test.txt").unwrap());
/// # file.write_all("some data...".as_bytes()).unwrap();
/// # drop(file);
/// // open and mmap the file
/// let mut file = DiskMmapFile::open("disk_open_test.txt").unwrap();
/// let mut buf = vec![0; "some data...".len()];
/// file.read_exact(buf.as_mut_slice(), 0);
/// assert_eq!(buf.as_slice(), "some data...".as_bytes());
/// ```
pub fn open<P: AsRef<Path>>(path: P,) -> Result<Self, Error> {
Self::open_in(path, None)
}
/// Open a readable memory map backed by a file with [`Options`]
///
/// # Examples
///
/// ```ignore
/// use fmmap::{Options, MmapFileExt};
/// use fmmap::raw::DiskMmapFile;
/// use std::fs::File;
/// use std::io::Write;
/// # use scopeguard::defer;
///
/// # let mut file = File::create("disk_open_test_with_options.txt").unwrap();
/// # defer!(std::fs::remove_file("disk_open_test_with_options.txt").unwrap());
/// # file.write_all("sanity text".as_bytes()).unwrap();
/// # file.write_all("some data...".as_bytes()).unwrap();
/// # drop(file);
///
/// // mmap the file with options
/// let opts = Options::new()
/// // allow read
/// .read(true)
/// // allow write
/// .write(true)
/// // allow append
/// .append(true)
/// // truncate to 100
/// .max_size(100)
/// // mmap content after the sanity text
/// .offset("sanity text".as_bytes().len() as u64);
/// // open and mmap the file
/// let mut file = DiskMmapFile::open_with_options("disk_open_test_with_options.txt", opts).unwrap();
/// let mut buf = vec![0; "some data...".len()];
/// file.read_exact(buf.as_mut_slice(), 0);
/// assert_eq!(buf.as_slice(), "some data...".as_bytes());
/// ```
///
/// [`Options`]: struct.Options.html
pub fn open_with_options<P: AsRef<Path>>(path: P, opts: Options) -> Result<Self, Error> {
Self::open_in(path, Some(opts))
}
/// Open a readable and executable memory map backed by a file
///
/// # Examples
///
/// ```ignore
/// use fmmap::MmapFileExt;
/// use fmmap::raw::DiskMmapFile;
/// use std::fs::{remove_file, File};
/// use std::io::Write;
/// # use scopeguard::defer;
///
/// # let mut file = File::create("disk_open_exec_test.txt").unwrap();
/// # defer!(remove_file("disk_open_exec_test.txt").unwrap());
/// # file.write_all("some data...".as_bytes()).unwrap();
/// # drop(file);
/// // open and mmap the file
/// let mut file = DiskMmapFile::open_exec("disk_open_exec_test.txt").unwrap();
/// let mut buf = vec![0; "some data...".len()];
/// file.read_exact(buf.as_mut_slice(), 0);
/// assert_eq!(buf.as_slice(), "some data...".as_bytes());
/// ```
pub fn open_exec<P: AsRef<Path>>(path: P,) -> Result<Self, Error> {
Self::open_exec_in(path, None)
}
/// Open a readable and executable memory map backed by a file with [`Options`].
///
/// # Examples
///
/// ```ignore
/// use fmmap::{Options, MmapFileExt};
/// use fmmap::raw::DiskMmapFile;
/// use std::fs::File;
/// use std::io::Write;
/// # use scopeguard::defer;
///
/// # let mut file = File::create("disk_open_exec_test_with_options.txt").unwrap();
/// # defer!(std::fs::remove_file("disk_open_exec_test_with_options.txt").unwrap());
/// # file.write_all("sanity text".as_bytes()).unwrap();
/// # file.write_all("some data...".as_bytes()).unwrap();
/// # drop(file);
///
/// // mmap the file with options
/// let opts = Options::new()
/// // allow read
/// .read(true)
/// // mmap content after the sanity text
/// .offset("sanity text".as_bytes().len() as u64);
/// // open and mmap the file
/// let mut file = DiskMmapFile::open_exec_with_options("disk_open_exec_test_with_options.txt", opts).unwrap();
/// let mut buf = vec![0; "some data...".len()];
/// file.read_exact(buf.as_mut_slice(), 0);
/// assert_eq!(buf.as_slice(), "some data...".as_bytes());
/// ```
///
/// [`Options`]: struct.Options.html
pub fn open_exec_with_options<P: AsRef<Path>>(path: P, opts: Options) -> Result<Self, Error> {
Self::open_exec_in(path, Some(opts))
}
fn open_in<P: AsRef<Path>>(path: P, opts: Option<Options>) -> Result<Self, Error> {
let file = open_read_only_file(&path).map_err(|e| Error::new_source_msg(ErrorKind::OpenFailed, path.as_ref().to_string_lossy(), e))?;
match opts {
None => {
let mmap = unsafe {
Mmap::map(&file).map_err(|e| Error::new(ErrorKind::MmapFailed, e))?
};
Ok(Self {
mmap,
file,
path: path.as_ref().to_path_buf(),
exec: false
})
}
Some(opts) => {
let mmap = unsafe {
opts.mmap_opts.map(&file).map_err(|e| Error::new(ErrorKind::MmapFailed, e))?
};
Ok(Self {
mmap,
file,
path: path.as_ref().to_path_buf(),
exec: false
})
}
}
}
fn open_exec_in<P: AsRef<Path>>(path: P, opts: Option<Options>) -> Result<Self, Error> {
let file = open_read_only_file(&path).map_err(|e| Error::new_source_msg(ErrorKind::OpenFailed, path.as_ref().to_string_lossy(), e))?;
match opts {
None => {
let mmap = unsafe {
MmapOptions::new().map_exec(&file).map_err(|e| Error::new(ErrorKind::MmapFailed, e))?
};
Ok(Self {
mmap,
file,
path: path.as_ref().to_path_buf(),
exec: true,
})
}
Some(opts) => {
let mmap = unsafe {
opts.mmap_opts.map_exec(&file).map_err(|e| Error::new(ErrorKind::MmapFailed, e))?
};
Ok(Self {
mmap,
file,
path: path.as_ref().to_path_buf(),
exec: true,
})
}
}
}
}
/// DiskMmapFile contains a mutable mmap buffer
/// and a writable file.
pub struct DiskMmapFileMut {
pub(crate) mmap: MmapMut,
pub(crate) file: File,
pub(crate) path: PathBuf,
opts: Option<MmapOptions>,
typ: MmapFileMutType,
}
impl_mmap_file_ext_for_mut!(DiskMmapFileMut);
impl MmapFileMutExt for DiskMmapFileMut {
fn as_mut_slice(&mut self) -> &mut [u8] {
self.mmap.as_mut()
}
fn is_cow(&self) -> bool {
matches!(self.typ, MmapFileMutType::Cow)
}
impl_flush!();
#[cfg(not(target_os = "linux"))]
fn truncate(&mut self, max_sz: u64) -> Result<(), Error> {
if self.is_cow() {
return Err(Error::new_with_message(ErrorKind::TruncationFailed, "cannot truncate a copy-on-write mmap file"));
}
// sync data
let meta = self.file.metadata().map_err(|e| Error::new(ErrorKind::IO, e))?;
if meta.len() > 0 {
self.flush()?;
}
unsafe {
// unmap
drop_in_place(&mut self.mmap);
// truncate
self.file.set_len(max_sz).map_err(|e| Error::new_source_msg(ErrorKind::TruncationFailed, self.path_string(), e))?;
// remap
let mmap = remmap(self.path(), &self.file, self.opts.as_ref(), self.typ)?;
write(&mut self.mmap, mmap);
}
Ok(())
}
#[cfg(target_os = "linux")]
fn truncate(&mut self, max_sz: u64) -> Result<(), Error> {
if self.is_cow() {
return Err(Error::new_with_message(ErrorKind::TruncationFailed, "cannot truncate a copy-on-write mmap file"));
}
// sync data
self.flush()?;
// truncate
self.file.set_len(max_sz).map_err(|e| Error::new_source_msg(ErrorKind::TruncationFailed, self.path_string(), e))?;
// remap
self.mmap = remmap(self.path(), &self.file, self.opts.as_ref(), self.typ)?;
Ok(())
}
/// Remove the underlying file
///
/// # Examples
///
/// ```ignore
/// use fmmap::MmapFileMutExt;
/// use fmmap::raw::DiskMmapFileMut;
///
/// let mut file = DiskMmapFileMut::create("disk_remove_test.txt").unwrap();
///
/// file.truncate(100);
/// file.write_all("some data...".as_bytes(), 0).unwrap();
/// file.flush().unwrap();
///
/// file.remove().unwrap();
///
/// let err = std::fs::File::open("disk_remove_test.txt");
/// assert_eq!(err.unwrap_err().kind(), std::io::ErrorKind::NotFound);
/// ```
fn remove(self) -> crate::error::Result<()> {
let path = self.path;
drop(self.mmap);
self.file.set_len(0).map_err(|e| Error::new(ErrorKind::IO, e))?;
drop(self.file);
remove_file(path).map_err(|e| Error::new(ErrorKind::IO, e))
}
/// Close and truncate the underlying file
///
/// # Examples
///
/// ```ignore
/// use fmmap::{MetaDataExt, MmapFileExt, MmapFileMutExt};
/// use fmmap::raw::DiskMmapFileMut;
/// # use scopeguard::defer;
///
/// let mut file = DiskMmapFileMut::create("disk_close_with_truncate_test.txt").unwrap();
/// # defer!(std::fs::remove_file("disk_close_with_truncate_test.txt").unwrap());
/// file.truncate(100);
/// file.write_all("some data...".as_bytes(), 0).unwrap();
/// file.flush().unwrap();
///
/// file.close_with_truncate(50).unwrap();
///
/// let file = DiskMmapFileMut::open("disk_close_with_truncate_test.txt").unwrap();
/// let meta = file.metadata().unwrap();
/// assert_eq!(meta.len(), 50);
/// ```
#[cfg(not(target_os = "linux"))]
fn close_with_truncate(self, max_sz: i64) -> crate::error::Result<()> {
// sync data
let meta = self.file.metadata().map_err(|e| Error::new(ErrorKind::IO, e))?;
if meta.len() > 0 {
self.flush()?;
}
drop(self.mmap);
if max_sz >= 0 {
self.file.set_len(max_sz as u64).map_err(|e| Error::new(ErrorKind::IO, e))?;
let abs = self.path.canonicalize().map_err(|e| Error::new(ErrorKind::IO, e))?;
let parent = abs.parent().unwrap();
File::open(parent).map_err(|e| Error::new(ErrorKind::IO, e))?.sync_all().map_err(|e| Error::new(ErrorKind::SyncDirFailed, e))?
}
Ok(())
}
/// Close and truncate the underlying file
///
/// # Examples
///
/// ```ignore
/// use fmmap::{MetaDataExt, MmapFileExt, MmapFileMutExt};
/// use fmmap::raw::DiskMmapFileMut;
/// # use scopeguard::defer;
///
/// let mut file = DiskMmapFileMut::create("disk_close_with_truncate_test.txt").unwrap();
/// # defer!(std::fs::remove_file("disk_close_with_truncate_test.txt").unwrap());
/// file.truncate(100);
/// file.write_all("some data...".as_bytes(), 0).unwrap();
/// file.flush().unwrap();
///
/// file.close_with_truncate(50).unwrap();
///
/// let file = DiskMmapFileMut::open("disk_close_with_truncate_test.txt").unwrap();
/// let meta = file.metadata().unwrap();
/// assert_eq!(meta.len(), 50);
/// ```
#[cfg(target_os = "linux")]
fn close_with_truncate(self, max_sz: i64) -> crate::error::Result<()> {
self.flush()?;
drop(self.mmap);
if max_sz >= 0 {
self.file.set_len(max_sz as u64).map_err(|e| Error::new(ErrorKind::IO, e))?;
let abs = self.path.canonicalize().map_err(|e| Error::new(ErrorKind::IO, e))?;
let parent = abs.parent().unwrap();
File::open(parent).map_err(|e| Error::new(ErrorKind::IO, e))?.sync_all().map_err(|e| Error::new(ErrorKind::SyncDirFailed, e))?
}
Ok(())
}
}
impl DiskMmapFileMut {
/// Create a new file and mmap this file
///
/// # Notes
/// The new file is zero size, so before do write, you should truncate first.
/// Or you can use [`create_with_options`] and set `max_size` field for [`Options`] to enable directly write
/// without truncating.
///
/// # Examples
///
/// ```ignore
/// use fmmap::MmapFileMutExt;
/// use fmmap::raw::DiskMmapFileMut;
/// # use scopeguard::defer;
///
/// let mut file = DiskMmapFileMut::create("disk_create_test.txt").unwrap();
/// # defer!(std::fs::remove_file("disk_create_test.txt").unwrap());
/// file.truncate(100);
/// file.write_all("some data...".as_bytes(), 0).unwrap();
/// file.flush().unwrap();
/// ```
///
/// [`create_with_options`]: struct.DiskMmapFileMut.html#method.create_with_options
/// [`Options`]: struct.Options.html
pub fn create<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
Self::create_in(path, None)
}
/// Create a new file and mmap this file with [`Options`]
///
/// # Examples
///
/// ```ignore
/// use fmmap::{Options, MmapFileMutExt};
/// use fmmap::raw::DiskMmapFileMut;
/// # use scopeguard::defer;
///
/// let opts = Options::new()
/// // truncate to 100
/// .max_size(100);
/// let mut file = DiskMmapFileMut::create_with_options("disk_create_with_options_test.txt", opts).unwrap();
/// # defer!(std::fs::remove_file("disk_create_with_options_test.txt").unwrap());
/// file.write_all("some data...".as_bytes(), 0).unwrap();
/// file.flush().unwrap();
/// ```
///
/// [`Options`]: struct.Options.html
pub fn create_with_options<P: AsRef<Path>>(path: P, opts: Options) -> Result<Self, Error> {
Self::create_in(path, Some(opts))
}
/// Open or Create(if not exists) a file and mmap this file.
///
/// # Notes
/// If the file does not exist, then the new file will be open in zero size, so before do write, you should truncate first.
/// Or you can use [`open_with_options`] and set `max_size` field for [`Options`] to enable directly write
/// without truncating.
///
/// # Examples
///
/// File already exists
///
/// ```ignore
/// use fmmap::{MmapFileExt, MmapFileMutExt};
/// use fmmap::raw::DiskMmapFileMut;
/// use std::fs::File;
/// use std::io::{Read, Write};
/// # use scopeguard::defer;
///
/// # let mut file = File::create("disk_open_test.txt").unwrap();
/// # defer!(std::fs::remove_file("disk_open_test.txt").unwrap());
/// # file.write_all("some data...".as_bytes()).unwrap();
/// # drop(file);
///
/// // open and mmap the file
/// let mut file = DiskMmapFileMut::open("disk_open_test.txt").unwrap();
/// let mut buf = vec![0; "some data...".len()];
/// file.read_exact(buf.as_mut_slice(), 0);
/// assert_eq!(buf.as_slice(), "some data...".as_bytes());
///
/// // modify the file data
/// file.truncate("some modified data...".len() as u64).unwrap();
/// file.write_all("some modified data...".as_bytes(), 0).unwrap();
/// file.flush().unwrap();
/// drop(file);
///
/// // reopen to check content
/// let mut buf = vec![0; "some modified data...".len()];
/// let mut file = File::open("disk_open_test.txt").unwrap();
/// file.read_exact(buf.as_mut_slice()).unwrap();
/// assert_eq!(buf.as_slice(), "some modified data...".as_bytes());
/// ```
///
/// File does not exists
///
/// ```ignore
/// use fmmap::{MmapFileExt, MmapFileMutExt};
/// use fmmap::raw::DiskMmapFileMut;
/// use std::fs::File;
/// use std::io::{Read, Write};
/// # use scopeguard::defer;
///
/// // create and mmap the file
/// let mut file = DiskMmapFileMut::open("disk_open_test.txt").unwrap();
/// # defer!(std::fs::remove_file("disk_open_test.txt").unwrap());
/// file.truncate(100).unwrap();
/// file.write_all("some data...".as_bytes(), 0).unwrap();
///
/// let mut buf = vec![0; "some data...".len()];
/// file.read_exact(buf.as_mut_slice(), 0);
/// assert_eq!(buf.as_slice(), "some data...".as_bytes());
///
/// // modify the file data
/// file.truncate("some modified data...".len() as u64).unwrap();
/// file.write_all("some modified data...".as_bytes(), 0).unwrap();
/// file.flush().unwrap();
/// drop(file);
///
/// // reopen to check content
/// let mut buf = vec![0; "some modified data...".len()];
/// let mut file = File::open("disk_open_test.txt").unwrap();
/// file.read_exact(buf.as_mut_slice()).unwrap();
/// assert_eq!(buf.as_slice(), "some modified data...".as_bytes());
/// ```
///
/// [`open_with_options`]: struct.DiskMmapFileMut.html#method.open_with_options
/// [`Options`]: struct.Options.html
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
Self::open_in(path, None)
}
/// Open or Create(if not exists) a file and mmap this file with [`Options`].
///
/// # Examples
///
/// File already exists
///
/// ```ignore
/// use fmmap::{MmapFileExt, MmapFileMutExt, Options};
/// use fmmap::raw::DiskMmapFileMut;
/// use std::fs::File;
/// use std::io::{Read, Seek, SeekFrom, Write};
/// # use scopeguard::defer;
///
/// # let mut file = File::create("disk_open_test_with_options.txt").unwrap();
/// # defer!(std::fs::remove_file("disk_open_test_with_options.txt").unwrap());
/// # file.write_all("sanity text".as_bytes()).unwrap();
/// # file.write_all("some data...".as_bytes()).unwrap();
/// # drop(file);
///
/// // mmap the file with options
/// let opts = Options::new()
/// // allow read
/// .read(true)
/// // allow write
/// .write(true)
/// // allow append
/// .append(true)
/// // truncate to 100
/// .max_size(100)
/// // mmap content after the sanity text
/// .offset("sanity text".as_bytes().len() as u64);
/// let mut file = DiskMmapFileMut::open_with_options("disk_open_test_with_options.txt", opts).unwrap();
/// let mut buf = vec![0; "some data...".len()];
/// file.read_exact(buf.as_mut_slice(), 0);
/// assert_eq!(buf.as_slice(), "some data...".as_bytes());
///
/// // modify the file data
/// file.truncate(("some modified data...".len() + "sanity text".len()) as u64).unwrap();
/// file.write_all("some modified data...".as_bytes(), 0).unwrap();
/// file.flush().unwrap();
/// drop(file);
///
/// // reopen to check content
/// let mut buf = vec![0; "some modified data...".len()];
/// let mut file = File::open("disk_open_test_with_options.txt").unwrap();
/// file.seek(SeekFrom::Start("sanity text".as_bytes().len() as u64)).unwrap();
/// file.read_exact(buf.as_mut_slice()).unwrap();
/// assert_eq!(buf.as_slice(), "some modified data...".as_bytes());
/// ```
///
/// File does not exists
///
/// ```ignore
/// use fmmap::{MmapFileExt, MmapFileMutExt, Options};
/// use fmmap::raw::DiskMmapFileMut;
/// use std::fs::File;
/// use std::io::{Read, Write};
/// # use scopeguard::defer;
///
/// // mmap the file with options
/// let opts = Options::new()
/// // allow read
/// .read(true)
/// // allow write
/// .write(true)
/// // allow append
/// .append(true)
/// // truncate to 100
/// .max_size(100);
///
/// let mut file = DiskMmapFileMut::open_with_options("disk_open_test_with_options.txt", opts).unwrap();
/// # defer!(std::fs::remove_file("disk_open_test_with_options.txt").unwrap());
/// file.write_all("some data...".as_bytes(), 0).unwrap();
///
/// let mut buf = vec![0; "some data...".len()];
/// file.read_exact(buf.as_mut_slice(), 0);
/// assert_eq!(buf.as_slice(), "some data...".as_bytes());
///
/// // modify the file data
/// file.truncate("some modified data...".len() as u64).unwrap();
/// file.write_all("some modified data...".as_bytes(), 0).unwrap();
/// file.flush().unwrap();
/// drop(file);
///
/// // reopen to check content
/// let mut buf = vec![0; "some modified data...".len()];
/// let mut file = File::open("disk_open_test_with_options.txt").unwrap();
/// file.read_exact(buf.as_mut_slice()).unwrap();
/// assert_eq!(buf.as_slice(), "some modified data...".as_bytes());
/// ```
///
/// [`Options`]: struct.Options.html
pub fn open_with_options<P: AsRef<Path>>(path: P, opts: Options) -> Result<Self, Error> {
Self::open_in(path, Some(opts))
}
/// Open an existing file and mmap this file
///
/// # Examples
/// ```ignore
/// use fmmap::{MmapFileExt, MmapFileMutExt};
/// use fmmap::raw::DiskMmapFileMut;
/// use std::fs::File;
/// use std::io::{Read, Write};
/// # use scopeguard::defer;
///
/// // create a temp file
/// let mut file = File::create("disk_open_existing_test.txt").unwrap();
/// # defer!(std::fs::remove_file("disk_open_existing_test.txt").unwrap());
/// file.write_all("some data...".as_bytes()).unwrap();
/// drop(file);
///
/// // mmap the file
/// let mut file = DiskMmapFileMut::open_exist("disk_open_existing_test.txt").unwrap();
/// let mut buf = vec![0; "some data...".len()];
/// file.read_exact(buf.as_mut_slice(), 0);
/// assert_eq!(buf.as_slice(), "some data...".as_bytes());
///
/// // modify the file data
/// file.truncate("some modified data...".len() as u64).unwrap();
/// file.write_all("some modified data...".as_bytes(), 0).unwrap();
/// file.flush().unwrap();
/// drop(file);
///
/// // reopen to check content
/// let mut buf = vec![0; "some modified data...".len()];
/// let mut file = File::open("disk_open_existing_test.txt").unwrap();
/// file.read_exact(buf.as_mut_slice()).unwrap();
/// assert_eq!(buf.as_slice(), "some modified data...".as_bytes());
/// ```
pub fn open_exist<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
Self::open_exist_in(path, None)
}
/// Open an existing file and mmap this file with [`Options`]
///
/// # Examples
/// ```ignore
/// use fmmap::{MmapFileExt, MmapFileMutExt, Options};
/// use fmmap::raw::DiskMmapFileMut;
/// use std::fs::File;
/// use std::io::{Read, Seek, SeekFrom, Write};
/// # use scopeguard::defer;
///
/// // create a temp file
/// let mut file = File::create("disk_open_existing_test_with_options.txt").unwrap();
/// # defer!(std::fs::remove_file("disk_open_existing_test_with_options.txt").unwrap());
/// file.write_all("sanity text".as_bytes()).unwrap();
/// file.write_all("some data...".as_bytes()).unwrap();
/// drop(file);
///
/// // mmap the file with options
/// let opts = Options::new()
/// // truncate to 100
/// .max_size(100)
/// // mmap content after the sanity text
/// .offset("sanity text".as_bytes().len() as u64);
/// let mut file = DiskMmapFileMut::open_exist_with_options("disk_open_existing_test_with_options.txt", opts).unwrap();
/// let mut buf = vec![0; "some data...".len()];
/// file.read_exact(buf.as_mut_slice(), 0);
/// assert_eq!(buf.as_slice(), "some data...".as_bytes());
///
/// // modify the file data
/// file.truncate(("some modified data...".len() + "sanity text".len()) as u64).unwrap();
/// file.write_all("some modified data...".as_bytes(), 0).unwrap();
/// file.flush().unwrap();
/// drop(file);
///
/// // reopen to check content
/// let mut buf = vec![0; "some modified data...".len()];
/// let mut file = File::open("disk_open_existing_test_with_options.txt").unwrap();
/// file.seek(SeekFrom::Start("sanity text".as_bytes().len() as u64)).unwrap();
/// file.read_exact(buf.as_mut_slice()).unwrap();
/// assert_eq!(buf.as_slice(), "some modified data...".as_bytes());
/// ```
///
/// [`Options`]: struct.Options.html
pub fn open_exist_with_options<P: AsRef<Path>>(path: P, opts: Options) -> Result<Self, Error> {
Self::open_exist_in(path, Some(opts))
}
/// Open and mmap an existing file in copy-on-write mode(copy-on-write memory map backed by a file).
/// Data written to the memory map will not be visible by other processes, and will not be carried through to the underlying file.
///
/// # Examples
///
/// ```ignore
/// use fmmap::{MmapFileExt, MmapFileMutExt};
/// use fmmap::raw::DiskMmapFileMut;
/// use std::fs::File;
/// use std::io::{Read, Write};
/// # use scopeguard::defer;
///
/// // create a temp file
/// let mut file = File::create("disk_open_cow_test.txt").unwrap();
/// # defer!(std::fs::remove_file("disk_open_cow_test.txt").unwrap());
/// file.write_all("some data...".as_bytes()).unwrap();
/// drop(file);
///
/// // mmap the file
/// let mut file = DiskMmapFileMut::open_cow("disk_open_cow_test.txt").unwrap();
/// let mut buf = vec![0; "some data...".len()];
/// file.read_exact(buf.as_mut_slice(), 0).unwrap();
/// assert_eq!(buf.as_slice(), "some data...".as_bytes());
///
/// // modify the file data
/// file.write_all("some data!!!".as_bytes(), 0).unwrap();
/// file.flush().unwrap();
///
/// // cow, change will only be seen in current caller
/// assert_eq!(file.as_slice(), "some data!!!".as_bytes());
/// drop(file);
///
/// // reopen to check content, cow will not change the content.
/// let mut file = File::open("disk_open_cow_test.txt").unwrap();
/// let mut buf = vec![0; "some data...".len()];
/// file.read_exact(buf.as_mut_slice()).unwrap();
/// assert_eq!(buf.as_slice(), "some data...".as_bytes());
/// ```
///
/// [`Options`]: struct.Options.html
pub fn open_cow<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
Self::open_cow_in(path, None)
}
/// Open and mmap an existing file in copy-on-write mode(copy-on-write memory map backed by a file) with [`Options`].
/// Data written to the memory map will not be visible by other processes, and will not be carried through to the underlying file.
///
/// # Examples
///
/// ```ignore
/// use fmmap::{MmapFileExt, MmapFileMutExt, Options};
/// use fmmap::raw::DiskMmapFileMut;
/// use std::fs::File;
/// use std::io::{Read, Seek, Write, SeekFrom};
/// # use scopeguard::defer;
///
/// // create a temp file
/// let mut file = File::create("disk_open_cow_with_options_test.txt").unwrap();
/// # defer!(std::fs::remove_file("disk_open_cow_with_options_test.txt").unwrap());
/// file.write_all("sanity text".as_bytes()).unwrap();
/// file.write_all("some data...".as_bytes()).unwrap();
/// drop(file);
///
/// // mmap the file with options
/// let opts = Options::new()
/// // mmap content after the sanity text
/// .offset("sanity text".as_bytes().len() as u64);
/// let mut file = DiskMmapFileMut::open_cow_with_options("disk_open_cow_with_options_test.txt", opts).unwrap();
/// let mut buf = vec![0; "some data...".len()];
/// file.read_exact(buf.as_mut_slice(), 0).unwrap();
/// assert_eq!(buf.as_slice(), "some data...".as_bytes());
///
/// // modify the file data
/// file.write_all("some data!!!".as_bytes(), 0).unwrap();
/// file.flush().unwrap();
///
/// // cow, change will only be seen in current caller
/// assert_eq!(file.as_slice(), "some data!!!".as_bytes());
/// drop(file);
///
/// // reopen to check content, cow will not change the content.
/// let mut file = File::open("disk_open_cow_with_options_test.txt").unwrap();
/// let mut buf = vec![0; "some data...".len()];
/// // skip the sanity text
/// file.seek(SeekFrom::Start("sanity text".as_bytes().len() as u64)).unwrap();
/// file.read_exact(buf.as_mut_slice()).unwrap();
/// assert_eq!(buf.as_slice(), "some data...".as_bytes());
/// ```
///
/// [`Options`]: struct.Options.html
pub fn open_cow_with_options<P: AsRef<Path>>(path: P, opts: Options) -> Result<Self, Error> {
Self::open_cow_in(path, Some(opts))
}
/// Returns an immutable version of this memory mapped buffer.
/// If the memory map is file-backed, the file must have been opened with read permissions.
///
/// # Errors
/// This method returns an error when the underlying system call fails,
/// which can happen for a variety of reasons,
/// such as when the file has not been opened with read permissions.
///
/// # Examples
/// ```ignore
/// use fmmap::MmapFileMutExt;
/// use fmmap::raw::DiskMmapFileMut;
/// # use scopeguard::defer;
///
/// let mut file = DiskMmapFileMut::create("disk_mmap_file_freeze_test.txt").unwrap();
/// # defer!(std::fs::remove_file("disk_mmap_file_freeze_test.txt").unwrap());
/// file.truncate(12);
/// file.write_all("some data...".as_bytes(), 0).unwrap();
/// file.flush().unwrap();
///
/// file.freeze().unwrap();
/// ```
pub fn freeze(self) -> Result<DiskMmapFile, Error> {
Ok(DiskMmapFile {
mmap: self.mmap.make_read_only().map_err(|e| Error::new(ErrorKind::IO, e))?,
file: self.file,
path: self.path,
exec: false
})
}
/// Transition the memory map to be readable and executable.
/// If the memory map is file-backed, the file must have been opened with execute permissions.
///
/// # Errors
/// This method returns an error when the underlying system call fails,
/// which can happen for a variety of reasons,
/// such as when the file has not been opened with execute permissions
///
/// # Examples
/// ```ignore
/// use fmmap::MmapFileMutExt;
/// use fmmap::raw::DiskMmapFileMut;
/// # use scopeguard::defer;
///
/// let mut file = DiskMmapFileMut::create("disk_mmap_file_freeze_test.txt").unwrap();
/// # defer!(std::fs::remove_file("disk_mmap_file_freeze_test.txt").unwrap());
/// file.truncate(12);
/// file.write_all("some data...".as_bytes(), 0).unwrap();
/// file.flush().unwrap();
///
/// file.freeze_exec().unwrap();
/// ```
pub fn freeze_exec(self) -> Result<DiskMmapFile, Error> {
Ok(DiskMmapFile {
mmap: self.mmap.make_exec().map_err(|e| Error::new(ErrorKind::IO, e))?,
file: self.file,
path: self.path,
exec: true,
})
}
fn create_in<P: AsRef<Path>>(path: P, opts: Option<Options>) -> Result<Self, Error> {
let file = create_file(&path)
.map_err(|e| Error::new_source_msg(ErrorKind::OpenFailed, path.as_ref().to_string_lossy(), e))?;
match opts {
None => {
let mmap = unsafe { MmapMut::map_mut(&file).map_err(|e| Error::new(ErrorKind::MmapFailed, e))? };
Ok(Self {
mmap,
file,
path: path.as_ref().to_path_buf(),
opts: None,
typ: MmapFileMutType::Normal,
})
}
Some(opts) => {
if opts.max_size > 0 {
file.set_len(opts.max_size).map_err(|e| Error::new_source_msg(ErrorKind::TruncationFailed, path.as_ref().to_string_lossy(), e))?;
sync_parent(&path)?;
}
let opts_bk = opts.mmap_opts.clone();
let mmap = unsafe { opts.mmap_opts.map_mut(&file).map_err(|e| Error::new(ErrorKind::MmapFailed, e))? };
Ok(Self {
mmap,
file,
path: path.as_ref().to_path_buf(),
opts: Some(opts_bk),
typ: MmapFileMutType::Normal,
})
}
}
}
fn open_in<P: AsRef<Path>>(path: P, opts: Option<Options>) -> Result<Self, Error> {
match opts {
None => {
let file = open_or_create_file(&path).map_err(|e| Error::new_source_msg(ErrorKind::OpenFailed, path.as_ref().to_string_lossy(), e))?;
let mmap = unsafe { MmapMut::map_mut(&file).map_err(|e| Error::new(ErrorKind::MmapFailed, e))? };
Ok(Self {
mmap,
file,
path: path.as_ref().to_path_buf(),
opts: None,
typ: MmapFileMutType::Normal,
})
}
Some(mut opts) => {
let file = opts.file_opts.create(true).open(&path).map_err(|e| Error::new_source_msg(ErrorKind::OpenFailed, path.as_ref().to_string_lossy(), e))?;
let meta = file.metadata()?;
let file_sz = meta.len();
if file_sz == 0 && opts.max_size > 0 {
file.set_len(opts.max_size).map_err(|e| Error::new_source_msg(ErrorKind::TruncationFailed, path.as_ref().to_string_lossy(), e))?;
sync_parent(&path)?;
}
let opts_bk = opts.mmap_opts.clone();
let mmap = unsafe {
opts.mmap_opts.map_mut(&file).map_err(|e| Error::new(ErrorKind::MmapFailed, e))?
};
Ok(Self {
mmap,
file,
path: path.as_ref().to_path_buf(),
opts: Some(opts_bk),
typ: MmapFileMutType::Normal,
})
}
}
}
fn open_exist_in<P: AsRef<Path>>(path: P, opts: Option<Options>) -> Result<Self, Error> {
let file = open_exist_file_with_append(&path)
.map_err(|e| Error::new_source_msg(ErrorKind::OpenFailed, path.as_ref().to_string_lossy(), e))?;
match opts {
None => {
let mmap = unsafe { MmapMut::map_mut(&file)? };
Ok(Self {
mmap,
file,
path: path.as_ref().to_path_buf(),
opts: None,
typ: MmapFileMutType::Normal,
})
}
Some(opts) => {
let meta = file.metadata()?;
let file_sz = meta.len();
if file_sz == 0 && opts.max_size > 0 {
file.set_len(opts.max_size).map_err(|e| Error::new_source_msg(ErrorKind::TruncationFailed, path.as_ref().to_string_lossy(), e))?;
sync_parent(&path)?;
}
let opts_bk = opts.mmap_opts.clone();
let mmap = unsafe {
opts.mmap_opts.map_mut(&file)? };
Ok(Self {
mmap,
file,
path: path.as_ref().to_path_buf(),
opts: Some(opts_bk),
typ: MmapFileMutType::Normal,
})
}
}
}
fn open_cow_in<P: AsRef<Path>>(path: P, opts: Option<Options>) -> Result<Self, Error> {
let file = open_exist_file_with_append(&path)
.map_err(|e| Error::new_source_msg(ErrorKind::OpenFailed, path.as_ref().to_string_lossy(), e))?;
match opts {
None => {
let mmap = unsafe { MmapOptions::new().map_copy(&file)? };
Ok(Self {
mmap,
file,
path: path.as_ref().to_path_buf(),
opts: None,
typ: MmapFileMutType::Cow,
})
}
Some(opts) => {
let opts_bk = opts.mmap_opts.clone();
let mmap = unsafe { opts.mmap_opts.map_copy(&file)? };
Ok(Self {
mmap,
file,
path: path.as_ref().to_path_buf(),
opts: Some(opts_bk),
typ: MmapFileMutType::Cow,
})
}
}
}
}
impl_sync_tests!("disk", DiskMmapFile, DiskMmapFileMut);
#[test]
fn test_close_with_truncate_on_empty_file() {
let file = DiskMmapFileMut::create("disk_close_with_truncate_test.txt").unwrap();
scopeguard::defer!(std::fs::remove_file("disk_close_with_truncate_test.txt").unwrap());
file.close_with_truncate(10).unwrap();
assert_eq!(10, File::open("disk_close_with_truncate_test.txt").unwrap().metadata().unwrap().len());
}