Skip to content

Commit

Permalink
Add close call to catch IO errors
Browse files Browse the repository at this point in the history
  • Loading branch information
mulimoen committed Mar 28, 2024
1 parent 00a0922 commit c868e45
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 4 deletions.
32 changes: 28 additions & 4 deletions netcdf/src/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,18 @@ pub(crate) struct RawFile {
ncid: nc_type,
}

impl RawFile {
fn close(self) -> error::Result<()> {
let Self { ncid } = self;
error::checked(super::with_lock(|| unsafe { nc_close(ncid) }))
}
}

impl Drop for RawFile {
fn drop(&mut self) {
unsafe {
// Can't really do much with an error here
let _err = error::checked(super::with_lock(|| nc_close(self.ncid)));
}
// Can't really do much with an error here
let ncid = self.ncid;
let _err = error::checked(super::with_lock(|| unsafe { nc_close(ncid) }));
}
}

Expand Down Expand Up @@ -245,6 +251,15 @@ impl File {
pub fn types(&self) -> error::Result<impl Iterator<Item = super::types::VariableType>> {
super::types::all_at_location(self.ncid()).map(|x| x.map(Result::unwrap))
}

/// Close the file
///
/// Note: This is called automatically by `Drop`, but can be useful
/// if flushing data or closing the file would result in an error.
pub fn close(self) -> error::Result<()> {
let Self(file) = self;
file.close()
}
}

/// Mutable access to file.
Expand Down Expand Up @@ -434,6 +449,15 @@ impl FileMut {
netcdf_sys::nc_sync(self.ncid())
}))
}

/// Close the file
///
/// Note: This is called automatically by `Drop`, but can be useful
/// if flushing data or closing the file would result in an error.
pub fn close(self) -> error::Result<()> {
let Self(File(file)) = self;
file.close()
}
}

#[cfg(feature = "has-mmap")]
Expand Down
14 changes: 14 additions & 0 deletions netcdf/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1754,3 +1754,17 @@ fn sync_file() {
f.add_unlimited_dimension("t").unwrap();
f.sync().unwrap();
}

#[test]
fn close_file() {
let d = tempfile::tempdir().unwrap();
let path = d.path().join("close_file.nc");

let mut f = netcdf::create(&path).unwrap();

f.add_unlimited_dimension("t").unwrap();
f.close().unwrap();

let f = netcdf::open(path).unwrap();
f.close().unwrap();
}

0 comments on commit c868e45

Please sign in to comment.