diff --git a/netcdf/src/file.rs b/netcdf/src/file.rs index 75715e9..aa2cef0 100644 --- a/netcdf/src/file.rs +++ b/netcdf/src/file.rs @@ -472,6 +472,21 @@ impl FileMut { super::variable::add_variable_from_identifiers(ncid, name, dims, xtype) } + /// Create a Variable containing strings into the dataset, with no data written into it + /// + /// Dimensions are identified using the name of the dimension, and will recurse upwards + /// if not found in the current group. + pub fn add_string_variable<'f>( + &mut self, + name: &str, + dims: &[&str], + ) -> error::Result> + { + let typ = crate::types::NcVariableType::String; + let (ncid, name) = super::group::get_parent_ncid_and_stem(self.ncid(), name)?; + VariableMut::add_from_str(ncid, &typ, name, dims) + } + /// Flush pending buffers to disk to minimise data loss in case of termination. /// /// Note: When writing and reading from the same file from multiple processes diff --git a/netcdf/src/group.rs b/netcdf/src/group.rs index 959c194..b193f38 100644 --- a/netcdf/src/group.rs +++ b/netcdf/src/group.rs @@ -227,6 +227,7 @@ impl<'f> GroupMut<'f> { let (ncid, name) = super::group::get_parent_ncid_and_stem(self.id(), name)?; VariableMut::add_from_str(ncid, &T::type_descriptor(), name, dims) } + /// Adds a variable from a set of unique identifiers, recursing upwards /// from the current group if necessary. pub fn add_variable_from_identifiers<'g, T>( @@ -269,6 +270,21 @@ impl<'f> GroupMut<'f> { }; super::variable::add_variable_from_identifiers(ncid, name, dims, xtype) } + + /// Create a Variable containing strings into the dataset, with no data written into it + /// + /// Dimensions are identified using the name of the dimension, and will recurse upwards + /// if not found in the current group. + pub fn add_string_variable( + &mut self, + name: &str, + dims: &[&str], + ) -> error::Result> + { + let typ = crate::types::NcVariableType::String; + let (ncid, name) = super::group::get_parent_ncid_and_stem(self.id(), name)?; + VariableMut::add_from_str(ncid, &typ, name, dims) + } } pub(crate) fn groups_at_ncid<'f>(ncid: nc_type) -> error::Result>> { diff --git a/netcdf/tests/types.rs b/netcdf/tests/types.rs index 9f2c48b..3b019e4 100644 --- a/netcdf/tests/types.rs +++ b/netcdf/tests/types.rs @@ -483,3 +483,23 @@ fn no_subtype() { file.add_type::().unwrap(); file.add_type::().unwrap(); } + +#[test] +fn add_string_variable() { + let d = tempfile::tempdir().unwrap(); + let path = d.path().join("stringy.nc"); + { + let mut file = netcdf::create(path.clone()).unwrap(); + file.add_string_variable("s", &[]).unwrap(); + + let mut group = file.add_group("g").unwrap(); + group.add_string_variable("str", &[]).unwrap(); + } + { + let file = netcdf::open(path).unwrap(); + let var = file.variable("s").unwrap(); + assert_eq!(var.vartype(), NcVariableType::String); + let var = file.variable("g/str").unwrap(); + assert_eq!(var.vartype(), NcVariableType::String); + } +}