Initializing from scratch repo

This commit is contained in:
Mike Hiley 2015-06-27 12:01:55 -05:00
parent c81b979a7a
commit 2cd4311b00
26 changed files with 3988 additions and 4 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
target
testout
Cargo.lock
.*.swp

11
.travis.yml Normal file
View File

@ -0,0 +1,11 @@
language: rust
rust:
- 1.0.0
- beta
- nightly
os:
- linux
- osx
before_install:
- (test $TRAVIS_OS_NAME == "osx" || (brew update && brew install netcdf))
- (test $TRAVIS_OS_NAME == "linux" || (sudo apt-get update -qq && sudo apt-get install -y libnetcdf-dev && sudo apt-get install -y libclang-dev))

12
COPYING Normal file
View File

@ -0,0 +1,12 @@
rust-netcdf is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

15
Cargo.toml Normal file
View File

@ -0,0 +1,15 @@
[package]
name = "netcdf"
version = "0.1.0"
authors = ["Michael Hiley <mike.hiley@ssec.wisc.edu>"]
license = "GPL-3.0"
description = "High-level NetCDF bindings for Rust"
repository = "https://github.com/mhiley/rust-netcdf"
documentation = "https://github.com/mhiley/rust-netcdf"
keywords = ["netcdf", "hdf", "hdf4", "hdf5", "cdm", "libnetcdf", "netcdf4"]
[dependencies.netcdf-sys]
path = "netcdf-sys"
[dependencies.lazy_static]
git = "https://github.com/Kimundi/lazy-static.rs"

View File

@ -1,3 +1,5 @@
Copyright (c) 2015 Michael Hiley
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
@ -631,8 +633,8 @@ to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@ -652,7 +654,7 @@ Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
@ -672,4 +674,3 @@ may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

56
README.md Normal file
View File

@ -0,0 +1,56 @@
# rust-netcdf
[![Build Status](https://travis-ci.org/mhiley/rust-netcdf.svg?branch=master)](https://travis-ci.org/mhiley/rust-netcdf)
High-level [NetCDF](http://www.unidata.ucar.edu/software/netcdf/) bindings for Rust
## Status
Not (yet) supported: appending to existing files (using unlimited dimensions), user defined types, string variables, multi-valued attributes, strided/subsetted reads. All variable data is read into a 1-dimensional Vec with the last variable dimension varying fastest.
## Building
rust-netcdf depends on libnetcdf. You also need libclang installed because netcdf-sys uses [rust-bindgen](https://github.com/crabtw/rust-bindgen) to generate netcdf function signatures.
## Read Example
```Rust
// Open file simple_xy.nc:
let file = netcdf::open(&path_to_simple_xy).unwrap();
// Access any variable, attribute, or dimension through simple HashMap's:
let var = file.root.variables.get("data").unwrap();
// Read variable as any NC_TYPE, optionally failing if doing so would
// force a cast:
let data : Vec<i32> = var.get_int(false).unwrap();
// All variable data is read into 1-dimensional Vec.
for x in 0..(6*12) {
assert_eq!(data[x], x as i32);
}
```
## Write Example
```Rust
let f = netcdf::test_file_new("crabs.nc"); // just gets a path inside repo
let mut file = netcdf::create(&f).unwrap();
let dim_name = "ncrabs";
file.root.add_dimension(dim_name, 10).unwrap();
let var_name = "crab_coolness_level";
let data : Vec<i32> = vec![42; 10];
// Variable type written to file is inferred from Vec type:
file.root.add_variable(
var_name,
&vec![dim_name.to_string()],
&data
).unwrap();
```
## Documentation
I intend to improve documentation soon. For now, check out tests/lib.rs for quite a few usage examples.

11
THIRD_PARTY Normal file
View File

@ -0,0 +1,11 @@
rust-netcdf contains code from Unidata's NetCDF, under the following license:
NetCDF License (http://www.unidata.ucar.edu/software/netcdf/copyright.html)
---------------
Copyright 1993-2014 University Corporation for Atmospheric Research/Unidata
Portions of this software were developed by the Unidata Program at the University Corporation for Atmospheric Research.
Access and use of this software shall impose the following obligations and understandings on the user. The user is granted the right, without any fee or cost, to use, copy, modify, alter, enhance and distribute this software, and any derivative works thereof, and its supporting documentation for any purpose whatsoever, provided that this entire notice appears in all copies of the software, derivative works and supporting documentation. Further, UCAR requests that the user credit UCAR/Unidata in any publications that result from the use of this software or in any product that includes this software, although this is not an obligation. The names UCAR and/or Unidata, however, may not be used in any advertising or publicity to endorse or promote any products or commercial entity unless specific written permission is obtained from UCAR/Unidata. The user also understands that UCAR/Unidata is not obligated to provide the user with any support, consulting, training or assistance of any kind with regard to the use, operation and performance of this software nor to provide the user with any updates, revisions, new versions or "bug fixes."
THIS SOFTWARE IS PROVIDED BY UCAR/UNIDATA "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UCAR/UNIDATA BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE ACCESS, USE OR PERFORMANCE OF THIS SOFTWARE.

24
netcdf-sys/Cargo.toml Normal file
View File

@ -0,0 +1,24 @@
[package]
name = "netcdf-sys"
version = "0.1.0"
authors = ["Mike Hiley <mike.hiley@ssec.wisc.edu>"]
license = "MIT"
description = "FFI bindings to NetCDF"
repository = "https://github.com/mhiley/rust-netcdf"
documentation = "https://github.com/mhiley/rust-netcdf"
keywords = ["netcdf", "hdf", "hdf4", "hdf5", "cdm"]
links = "netcdf"
build = "build.rs"
[build-dependencies]
gcc = "0.3.8"
[build-dependencies.bindgen]
git = "https://github.com/crabtw/rust-bindgen.git"
[dependencies.lazy_static]
git = "https://github.com/Kimundi/lazy-static.rs"
[dependencies]
libc = "0.1.8"

25
netcdf-sys/LICENSE-MIT Normal file
View File

@ -0,0 +1,25 @@
Copyright (c) 2015 Michael Hiley
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

32
netcdf-sys/build.rs Normal file
View File

@ -0,0 +1,32 @@
extern crate gcc;
extern crate bindgen;
fn main() {
let out_dir = std::env::var("OUT_DIR").unwrap();
let out_dir = std::path::Path::new(&out_dir);
// This is a workaround to avoid using bindgen! macro. Cleaner solution
// may be available if https://github.com/crabtw/rust-bindgen/issues/201
// is resolved.
let rs_path = std::path::Path::new(&out_dir).join("netcdf_bindings.rs");
let mut bindings = bindgen::builder();
bindings.forbid_unknown_types();
// hack for Arch Linux 2015-06-24:
bindings.clang_arg("-I/usr/lib/clang/3.6.1/include");
// XXX why do usual clang search paths work for lib but not for include?
let mnf_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
let netcdf_h = std::path::Path::new(&mnf_dir).join(
"src").join("netcdf_v4.3.3.1.h");
let netcdf_h = netcdf_h.to_str().unwrap();
bindings.header(netcdf_h);
bindings.link("netcdf");
let bindings = bindings.generate();
let bindings = bindings.unwrap();
bindings.write_to_file(rs_path).unwrap();
// compile c wrapper to convert CPP constants into proper C types+values
gcc::compile_library("libncconst.a", &["src/ncconst.c"]);
}

291
netcdf-sys/src/lib.rs Normal file
View File

@ -0,0 +1,291 @@
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#[macro_use]
extern crate lazy_static;
extern crate libc;
use std::sync::Mutex;
include!(concat!(env!("OUT_DIR"), "/netcdf_bindings.rs"));
extern "C" {
pub static nc_nat: ::libc::c_int;
pub static nc_byte: ::libc::c_int;
pub static nc_char: ::libc::c_int;
pub static nc_short: ::libc::c_int;
pub static nc_int: ::libc::c_int;
pub static nc_long: ::libc::c_int;
pub static nc_float: ::libc::c_int;
pub static nc_double: ::libc::c_int;
pub static nc_ubyte: ::libc::c_int;
pub static nc_ushort: ::libc::c_int;
pub static nc_uint: ::libc::c_int;
pub static nc_int64: ::libc::c_int;
pub static nc_uint64: ::libc::c_int;
pub static nc_string: ::libc::c_int;
pub static nc_max_atomic_type: ::libc::c_int;
pub static nc_vlen : ::libc::c_int;
pub static nc_opaque : ::libc::c_int;
pub static nc_enum : ::libc::c_int;
pub static nc_compound : ::libc::c_int;
pub static nc_nowrite : ::libc::c_int;
pub static nc_write : ::libc::c_int;
pub static nc_clobber : ::libc::c_int;
pub static nc_noclobber : ::libc::c_int;
pub static nc_diskless : ::libc::c_int;
pub static nc_mmap : ::libc::c_int;
pub static nc_classic_model: ::libc::c_int;
pub static nc_64bit_offset : ::libc::c_int;
pub static nc_lock : ::libc::c_int;
pub static nc_share : ::libc::c_int;
pub static nc_netcdf4 : ::libc::c_int;
pub static nc_mpiio : ::libc::c_int;
pub static nc_mpiposix : ::libc::c_int;
pub static nc_pnetcdf : ::libc::c_int;
pub static nc_format_classic: ::libc::c_int;
pub static nc_format_64bit : ::libc::c_int;
pub static nc_format_netcdf4: ::libc::c_int;
pub static nc_format_netcdf4_classic : ::libc::c_int;
pub static nc_format_nc3 : ::libc::c_int;
pub static nc_format_nc_hdf5: ::libc::c_int;
pub static nc_format_nc_hdf4: ::libc::c_int;
pub static nc_format_pnetcdf: ::libc::c_int;
pub static nc_format_dap2 : ::libc::c_int;
pub static nc_format_dap4 : ::libc::c_int;
pub static nc_format_undefined: ::libc::c_int;
pub static nc_sizehint_default : ::libc::c_int;
pub static nc_global : ::libc::c_int;
pub static nc_max_dims : ::libc::c_int;
pub static nc_max_attrs : ::libc::c_int;
pub static nc_max_vars : ::libc::c_int;
pub static nc_max_name : ::libc::c_int;
pub static nc_max_var_dims : ::libc::c_int;
pub static nc_max_hdf4_name : ::libc::c_int;
pub static nc_endian_native : ::libc::c_int;
pub static nc_endian_little : ::libc::c_int;
pub static nc_endian_big : ::libc::c_int;
pub static nc_chunked : ::libc::c_int;
pub static nc_contiguous : ::libc::c_int;
pub static nc_nochecksum : ::libc::c_int;
pub static nc_fletcher32 : ::libc::c_int;
pub static nc_noshuffle : ::libc::c_int;
pub static nc_shuffle : ::libc::c_int;
pub static nc_noerr : ::libc::c_int;
pub static nc2_err : ::libc::c_int;
pub static nc_ebadid : ::libc::c_int;
pub static nc_enfile : ::libc::c_int;
pub static nc_eexist : ::libc::c_int;
pub static nc_einval : ::libc::c_int;
pub static nc_eperm : ::libc::c_int;
pub static nc_enotindefine : ::libc::c_int;
pub static nc_eindefine : ::libc::c_int;
pub static nc_einvalcoords : ::libc::c_int;
pub static nc_emaxdims : ::libc::c_int;
pub static nc_enameinuse : ::libc::c_int;
pub static nc_enotatt : ::libc::c_int;
pub static nc_emaxatts : ::libc::c_int;
pub static nc_ebadtype : ::libc::c_int;
pub static nc_ebaddim : ::libc::c_int;
pub static nc_eunlimpos : ::libc::c_int;
pub static nc_emaxvars : ::libc::c_int;
pub static nc_enotvar : ::libc::c_int;
pub static nc_eglobal : ::libc::c_int;
pub static nc_enotnc : ::libc::c_int;
pub static nc_ests : ::libc::c_int;
pub static nc_emaxname : ::libc::c_int;
pub static nc_eunlimit : ::libc::c_int;
pub static nc_enorecvars : ::libc::c_int;
pub static nc_echar : ::libc::c_int;
pub static nc_eedge : ::libc::c_int;
pub static nc_estride : ::libc::c_int;
pub static nc_ebadname : ::libc::c_int;
pub static nc_erange : ::libc::c_int;
pub static nc_enomem : ::libc::c_int;
pub static nc_evarsize : ::libc::c_int;
pub static nc_edimsize : ::libc::c_int;
pub static nc_etrunc : ::libc::c_int;
pub static nc_eaxistype : ::libc::c_int;
pub static nc_edap : ::libc::c_int;
pub static nc_ecurl : ::libc::c_int;
pub static nc_eio : ::libc::c_int;
pub static nc_enodata : ::libc::c_int;
pub static nc_edapsvc : ::libc::c_int;
pub static nc_edas : ::libc::c_int;
pub static nc_edds : ::libc::c_int;
pub static nc_edatadds : ::libc::c_int;
pub static nc_edapurl : ::libc::c_int;
pub static nc_edapconstraint : ::libc::c_int;
pub static nc_etranslation : ::libc::c_int;
pub static nc_eaccess : ::libc::c_int;
pub static nc_eauth : ::libc::c_int;
pub static nc_enotfound : ::libc::c_int;
pub static nc_ecantremove : ::libc::c_int;
pub static nc4_first_error : ::libc::c_int;
pub static nc_ehdferr : ::libc::c_int;
pub static nc_ecantread : ::libc::c_int;
pub static nc_ecantwrite : ::libc::c_int;
pub static nc_ecantcreate : ::libc::c_int;
pub static nc_efilemeta : ::libc::c_int;
pub static nc_edimmeta : ::libc::c_int;
pub static nc_eattmeta : ::libc::c_int;
pub static nc_evarmeta : ::libc::c_int;
pub static nc_enocompound : ::libc::c_int;
pub static nc_eattexists : ::libc::c_int;
pub static nc_enotnc4 : ::libc::c_int;
pub static nc_estrictnc3 : ::libc::c_int;
pub static nc_enotnc3 : ::libc::c_int;
pub static nc_enopar : ::libc::c_int;
pub static nc_eparinit : ::libc::c_int;
pub static nc_ebadgrpid : ::libc::c_int;
pub static nc_ebadtypid : ::libc::c_int;
pub static nc_etypdefined : ::libc::c_int;
pub static nc_ebadfield : ::libc::c_int;
pub static nc_ebadclass : ::libc::c_int;
pub static nc_emaptype : ::libc::c_int;
pub static nc_elatefill : ::libc::c_int;
pub static nc_elatedef : ::libc::c_int;
pub static nc_edimscale : ::libc::c_int;
pub static nc_enogrp : ::libc::c_int;
pub static nc_estorage : ::libc::c_int;
pub static nc_ebadchunk : ::libc::c_int;
pub static nc_enotbuilt : ::libc::c_int;
pub static nc_ediskless : ::libc::c_int;
pub static nc_ecantextend : ::libc::c_int;
pub static nc_empi : ::libc::c_int;
pub static nc4_last_error : ::libc::c_int;
pub static nc_have_new_chunking_api : ::libc::c_int;
pub static nc_eurl : ::libc::c_int;
pub static nc_econstraint : ::libc::c_int;
pub static nc_fill : ::libc::c_int;
pub static nc_nofill : ::libc::c_int;
pub static nc_unlimited: ::libc::c_long;
pub static nc_fill_byte: i8;
pub static nc_fill_char: u8;
pub static nc_fill_short: i16;
pub static nc_fill_int: i32;
pub static nc_fill_float: f32;
pub static nc_fill_double: f64;
pub static nc_fill_ubyte: u8;
pub static nc_fill_ushort: u16;
pub static nc_fill_uint: u32;
pub static nc_fill_int64: i64;
pub static nc_fill_uint64: u64;
pub static nc_fill_string: *const ::libc::c_char;
pub static nc_align_chunk: ::libc::size_t;
}
// NetCDF types map well to Rust types, for for completeness, here are
// definitions of min/max constants:
pub const nc_max_byte : i8 = std::i8::MAX;
pub const nc_min_byte : i8 = std::i8::MIN;
pub const nc_max_char : u8 = std::u8::MAX;
pub const nc_max_short : i16 = std::i16::MAX;
pub const nc_min_short : i16 = std::i16::MIN;
pub const nc_max_int : i32 = std::i32::MAX;
pub const nc_min_int : i32 = std::i32::MIN;
pub const nc_max_float : f32 = std::f32::MAX;
pub const nc_min_float : f32 = std::f32::MIN;
pub const nc_max_double : f64 = std::f64::MAX;
pub const nc_min_double : f64 = std::f64::MIN;
pub const nc_max_ubyte : u8 = std::u8::MAX;
pub const nc_max_ushort : u16 = std::u16::MAX;
pub const nc_max_uint : u32 = std::u32::MAX;
pub const nc_max_int64 : i64 = std::i64::MAX;
pub const nc_min_int64 : i64 = std::i64::MIN;
pub const nc_max_uint64 : u64 = std::u64::MAX;
// Per the NetCDF FAQ, "THE C-BASED LIBRARIES ARE NOT THREAD-SAFE"
// So, here is our global mutex.
// Use lazy-static dependency to avoid use of static_mutex feature which
// breaks compatibility with stable channel.
lazy_static! {
pub static ref libnetcdf_lock: Mutex<()> = Mutex::new(());
}
#[cfg(test)]
mod tests {
use super::*;
use std::path;
use std::env;
use std::ffi;
#[test]
fn test_nc_open_close() {
let mnf_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let test_data_path = path::Path::new(&mnf_dir).join(
"testdata").join("simple_xy.nc");
let f = ffi::CString::new(test_data_path.to_str().unwrap()).unwrap();
let mut ncid : i32 = -999999i32;
unsafe {
let _g = libnetcdf_lock.lock().unwrap();
let err = nc_open(f.as_ptr(), nc_nowrite, &mut ncid);
assert_eq!(err, nc_noerr);
let err = nc_close(ncid);
assert_eq!(err, nc_noerr);
}
}
#[test]
fn test_inq_varid() {
let mnf_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let test_data_path = path::Path::new(&mnf_dir).join(
"testdata").join("simple_xy.nc");
let f = ffi::CString::new(test_data_path.to_str().unwrap()).unwrap();
let varname = ffi::CString::new("data").unwrap();
let mut ncid : i32 = -999999i32;
let mut varid : i32 = -999999i32;
let mut nvars : i32 = -999999i32;
unsafe {
let _g = libnetcdf_lock.lock().unwrap();
let err = nc_open(f.as_ptr(), nc_nowrite, &mut ncid);
assert_eq!(err, nc_noerr);
let err = nc_inq_nvars(ncid, &mut nvars);
assert_eq!(err, nc_noerr);
assert_eq!(nvars, 1);
let err = nc_inq_varid(ncid, varname.as_ptr(), &mut varid);
assert_eq!(err, nc_noerr);
let err = nc_close(ncid);
assert_eq!(err, nc_noerr);
}
}
#[test]
fn test_get_var() {
let mnf_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let test_data_path = path::Path::new(&mnf_dir).join(
"testdata").join("simple_xy.nc");
let f = ffi::CString::new(test_data_path.to_str().unwrap()).unwrap();
let varname = ffi::CString::new("data").unwrap();
let mut ncid : i32 = -999999i32;
let mut varid : i32 = -999999i32;
let mut buf : Vec<i32> = Vec::with_capacity(6*12);
unsafe {
buf.set_len(6*12);
let _g = libnetcdf_lock.lock().unwrap();
let err = nc_open(f.as_ptr(), nc_nowrite, &mut ncid);
assert_eq!(err, nc_noerr);
let err = nc_inq_varid(ncid, varname.as_ptr(), &mut varid);
assert_eq!(err, nc_noerr);
let err = nc_get_var_int(ncid, varid, buf.as_mut_ptr());
assert_eq!(err, nc_noerr);
let err = nc_close(ncid);
assert_eq!(err, nc_noerr);
}
for x in 0..(6*12) {
assert_eq!(buf[x], x as i32);
}
}
}

180
netcdf-sys/src/ncconst.c Normal file
View File

@ -0,0 +1,180 @@
/* Here we convert netcdf.h CPP macros into concrete C types and values.
* We assume plain int types unless otherwise obvious.
* Following netcdf.h v4.3.3.1
*/
#include <netcdf.h>
const int nc_nat = NC_NAT;
const int nc_byte = NC_BYTE;
const int nc_char = NC_CHAR;
const int nc_short = NC_SHORT;
const int nc_int = NC_INT;
const int nc_long = NC_LONG;
const int nc_float = NC_FLOAT;
const int nc_double = NC_DOUBLE;
const int nc_ubyte = NC_UBYTE;
const int nc_ushort = NC_USHORT;
const int nc_uint = NC_UINT;
const int nc_int64 = NC_INT64;
const int nc_uint64 = NC_UINT64;
const int nc_string = NC_STRING;
const int nc_max_atomic_type = NC_MAX_ATOMIC_TYPE;
const int nc_vlen = NC_VLEN ;
const int nc_opaque = NC_OPAQUE ;
const int nc_enum = NC_ENUM ;
const int nc_compound = NC_COMPOUND ;
const int nc_nowrite = NC_NOWRITE ;
const int nc_write = NC_WRITE ;
const int nc_clobber = NC_CLOBBER ;
const int nc_noclobber = NC_NOCLOBBER ;
const int nc_diskless = NC_DISKLESS ;
const int nc_mmap = NC_MMAP ;
const int nc_classic_model = NC_CLASSIC_MODEL;
const int nc_64bit_offset = NC_64BIT_OFFSET ;
const int nc_lock = NC_LOCK ;
const int nc_share = NC_SHARE ;
const int nc_netcdf4 = NC_NETCDF4 ;
const int nc_mpiio = NC_MPIIO ;
const int nc_mpiposix = NC_MPIPOSIX ;
const int nc_pnetcdf = NC_PNETCDF ;
const int nc_format_classic = NC_FORMAT_CLASSIC;
const int nc_format_64bit = NC_FORMAT_64BIT ;
const int nc_format_netcdf4 = NC_FORMAT_NETCDF4;
const int nc_format_netcdf4_classic = NC_FORMAT_NETCDF4_CLASSIC ;
const int nc_format_nc3 = NC_FORMAT_NC3 ;
const int nc_format_nc_hdf5 = NC_FORMAT_NC_HDF5;
const int nc_format_nc_hdf4 = NC_FORMAT_NC_HDF4;
const int nc_format_pnetcdf = NC_FORMAT_PNETCDF;
const int nc_format_dap2 = NC_FORMAT_DAP2 ;
const int nc_format_dap4 = NC_FORMAT_DAP4 ;
const int nc_format_undefined = NC_FORMAT_UNDEFINED;
const int nc_sizehint_default = NC_SIZEHINT_DEFAULT ;
const int nc_global = NC_GLOBAL ;
const int nc_max_dims = NC_MAX_DIMS ;
const int nc_max_attrs = NC_MAX_ATTRS ;
const int nc_max_vars = NC_MAX_VARS ;
const int nc_max_name = NC_MAX_NAME ;
const int nc_max_var_dims = NC_MAX_VAR_DIMS ;
const int nc_max_hdf4_name = NC_MAX_HDF4_NAME ;
const int nc_endian_native = NC_ENDIAN_NATIVE ;
const int nc_endian_little = NC_ENDIAN_LITTLE ;
const int nc_endian_big = NC_ENDIAN_BIG ;
const int nc_chunked = NC_CHUNKED ;
const int nc_contiguous = NC_CONTIGUOUS ;
const int nc_nochecksum = NC_NOCHECKSUM ;
const int nc_fletcher32 = NC_FLETCHER32 ;
const int nc_noshuffle = NC_NOSHUFFLE ;
const int nc_shuffle = NC_SHUFFLE ;
const int nc_noerr = NC_NOERR ;
const int nc2_err = NC2_ERR ;
const int nc_ebadid = NC_EBADID ;
const int nc_enfile = NC_ENFILE ;
const int nc_eexist = NC_EEXIST ;
const int nc_einval = NC_EINVAL ;
const int nc_eperm = NC_EPERM ;
const int nc_enotindefine = NC_ENOTINDEFINE ;
const int nc_eindefine = NC_EINDEFINE ;
const int nc_einvalcoords = NC_EINVALCOORDS ;
const int nc_emaxdims = NC_EMAXDIMS ;
const int nc_enameinuse = NC_ENAMEINUSE ;
const int nc_enotatt = NC_ENOTATT ;
const int nc_emaxatts = NC_EMAXATTS ;
const int nc_ebadtype = NC_EBADTYPE ;
const int nc_ebaddim = NC_EBADDIM ;
const int nc_eunlimpos = NC_EUNLIMPOS ;
const int nc_emaxvars = NC_EMAXVARS ;
const int nc_enotvar = NC_ENOTVAR ;
const int nc_eglobal = NC_EGLOBAL ;
const int nc_enotnc = NC_ENOTNC ;
const int nc_ests = NC_ESTS ;
const int nc_emaxname = NC_EMAXNAME ;
const int nc_eunlimit = NC_EUNLIMIT ;
const int nc_enorecvars = NC_ENORECVARS ;
const int nc_echar = NC_ECHAR ;
const int nc_eedge = NC_EEDGE ;
const int nc_estride = NC_ESTRIDE ;
const int nc_ebadname = NC_EBADNAME ;
const int nc_erange = NC_ERANGE ;
const int nc_enomem = NC_ENOMEM ;
const int nc_evarsize = NC_EVARSIZE ;
const int nc_edimsize = NC_EDIMSIZE ;
const int nc_etrunc = NC_ETRUNC ;
const int nc_eaxistype = NC_EAXISTYPE ;
const int nc_edap = NC_EDAP ;
const int nc_ecurl = NC_ECURL ;
const int nc_eio = NC_EIO ;
const int nc_enodata = NC_ENODATA ;
const int nc_edapsvc = NC_EDAPSVC ;
const int nc_edas = NC_EDAS ;
const int nc_edds = NC_EDDS ;
const int nc_edatadds = NC_EDATADDS ;
const int nc_edapurl = NC_EDAPURL ;
const int nc_edapconstraint = NC_EDAPCONSTRAINT ;
const int nc_etranslation = NC_ETRANSLATION ;
const int nc_eaccess = NC_EACCESS ;
const int nc_eauth = NC_EAUTH ;
const int nc_enotfound = NC_ENOTFOUND ;
const int nc_ecantremove = NC_ECANTREMOVE ;
const int nc4_first_error = NC4_FIRST_ERROR ;
const int nc_ehdferr = NC_EHDFERR ;
const int nc_ecantread = NC_ECANTREAD ;
const int nc_ecantwrite = NC_ECANTWRITE ;
const int nc_ecantcreate = NC_ECANTCREATE ;
const int nc_efilemeta = NC_EFILEMETA ;
const int nc_edimmeta = NC_EDIMMETA ;
const int nc_eattmeta = NC_EATTMETA ;
const int nc_evarmeta = NC_EVARMETA ;
const int nc_enocompound = NC_ENOCOMPOUND ;
const int nc_eattexists = NC_EATTEXISTS ;
const int nc_enotnc4 = NC_ENOTNC4 ;
const int nc_estrictnc3 = NC_ESTRICTNC3 ;
const int nc_enotnc3 = NC_ENOTNC3 ;
const int nc_enopar = NC_ENOPAR ;
const int nc_eparinit = NC_EPARINIT ;
const int nc_ebadgrpid = NC_EBADGRPID ;
const int nc_ebadtypid = NC_EBADTYPID ;
const int nc_etypdefined = NC_ETYPDEFINED ;
const int nc_ebadfield = NC_EBADFIELD ;
const int nc_ebadclass = NC_EBADCLASS ;
const int nc_emaptype = NC_EMAPTYPE ;
const int nc_elatefill = NC_ELATEFILL ;
const int nc_elatedef = NC_ELATEDEF ;
const int nc_edimscale = NC_EDIMSCALE ;
const int nc_enogrp = NC_ENOGRP ;
const int nc_estorage = NC_ESTORAGE ;
const int nc_ebadchunk = NC_EBADCHUNK ;
const int nc_enotbuilt = NC_ENOTBUILT ;
const int nc_ediskless = NC_EDISKLESS ;
const int nc_ecantextend = NC_ECANTEXTEND ;
const int nc_empi = NC_EMPI ;
const int nc4_last_error = NC4_LAST_ERROR ;
const int nc_have_new_chunking_api = NC_HAVE_NEW_CHUNKING_API ;
const int nc_eurl = NC_EURL ;
const int nc_econstraint = NC_ECONSTRAINT ;
const int nc_fill = NC_FILL ;
const int nc_nofill = NC_NOFILL ;
/* deal with non-int types */
const char * const dim_without_variable = DIM_WITHOUT_VARIABLE;
const char * const nc__FillValue = _FillValue;
const long nc_unlimited = NC_UNLIMITED ;
const signed char nc_fill_byte = NC_FILL_BYTE;
const char nc_fill_char = NC_FILL_CHAR;
const short nc_fill_short = NC_FILL_SHORT ;
const long nc_fill_int = NC_FILL_INT;
const float nc_fill_float = NC_FILL_FLOAT;
const double nc_fill_double = NC_FILL_DOUBLE;
const unsigned char nc_fill_ubyte = NC_FILL_UBYTE ;
const unsigned short nc_fill_ushort = NC_FILL_USHORT ;
const unsigned int nc_fill_uint = NC_FILL_UINT ;
const long long nc_fill_int64 = NC_FILL_INT64 ;
const unsigned long long nc_fill_uint64 = NC_FILL_UINT64 ;
const char * const nc_fill_string = "";
const size_t nc_align_chunk = NC_ALIGN_CHUNK;
//#define X_INT64_MAX (9223372036854775807LL)
//#define X_INT64_MIN (-X_INT64_MAX - 1)
//#define X_UINT64_MAX (18446744073709551615ULL)

File diff suppressed because it is too large Load Diff

BIN
netcdf-sys/testdata/simple_xy.nc vendored Normal file

Binary file not shown.

163
src/attribute.rs Normal file
View File

@ -0,0 +1,163 @@
use std::ffi;
use std::collections::HashMap;
use netcdf_sys::*;
use string_from_c_str;
use NC_ERRORS;
macro_rules! get_attr_as_type {
( $me:ident, $nc_type:ident, $rs_type:ty, $nc_fn:ident , $cast:ident )
=>
{{
if (!$cast) && ($me.attrtype != $nc_type) {
return Err("Types are not equivalent and cast==false".to_string());
}
let mut err: i32;
let mut attlen : u64 = 0;
let name_copy: ffi::CString =
ffi::CString::new($me.name.clone()).unwrap();
unsafe {
let _g = libnetcdf_lock.lock().unwrap();
err = nc_inq_attlen($me.file_id, $me.var_id, name_copy.as_ptr(),
&mut attlen);
}
if err != nc_noerr {
return Err(NC_ERRORS.get(&err).unwrap().clone());
}
if attlen != 1 {
return Err("Multi-value attributes not yet implemented".to_string());
}
let mut buf: $rs_type = 0 as $rs_type;
unsafe {
let _g = libnetcdf_lock.lock().unwrap();
err = $nc_fn($me.file_id, $me.var_id,
name_copy.as_ptr(),
&mut buf);
}
if err != nc_noerr {
return Err(NC_ERRORS.get(&err).unwrap().clone());
}
Ok(buf)
}}
}
pub struct Attribute {
pub name : String,
pub attrtype : i32,
pub id: i32,
pub var_id: i32,
pub file_id: i32,
}
impl Attribute {
pub fn get_char(&self, cast: bool) -> Result<String, String> {
if (!cast) && (self.attrtype != nc_char) {
return Err("Types are not equivalent and cast==false".to_string());
}
let attr_char_str;
let name_copy: ffi::CString =
ffi::CString::new(self.name.clone()).unwrap();
let mut attlen : u64 = 0;
unsafe {
let mut err;
{
let _g = libnetcdf_lock.lock().unwrap();
err = nc_inq_attlen(self.file_id, self.var_id, name_copy.as_ptr(),
&mut attlen);
}
if err != nc_noerr {
return Err(NC_ERRORS.get(&err).unwrap().clone());
}
// careful; netcdf does not write null terminators here
let mut attr_char_buf_vec = vec![0i8; (attlen+1) as usize];
let attr_char_buf_ptr: *mut i8 = attr_char_buf_vec.as_mut_ptr();
{
let _g = libnetcdf_lock.lock().unwrap();
err = nc_get_att_text(self.file_id, self.var_id,
name_copy.as_ptr(),
attr_char_buf_ptr);
}
if err != nc_noerr {
return Err(NC_ERRORS.get(&err).unwrap().clone());
}
let attr_c_str = ffi::CStr::from_ptr(attr_char_buf_ptr);
attr_char_str = string_from_c_str(attr_c_str);
}
Ok(attr_char_str)
}
pub fn get_byte(&self, cast: bool) -> Result<i8, String> {
get_attr_as_type!(self, nc_byte, i8, nc_get_att_schar, cast)
}
pub fn get_short(&self, cast: bool) -> Result<i16, String> {
get_attr_as_type!(self, nc_short, i16, nc_get_att_short, cast)
}
pub fn get_ushort(&self, cast: bool) -> Result<u16, String> {
get_attr_as_type!(self, nc_ushort, u16, nc_get_att_ushort, cast)
}
pub fn get_int(&self, cast: bool) -> Result<i32, String> {
get_attr_as_type!(self, nc_int, i32, nc_get_att_int, cast)
}
pub fn get_uint(&self, cast: bool) -> Result<u32, String> {
get_attr_as_type!(self, nc_uint, u32, nc_get_att_uint, cast)
}
pub fn get_int64(&self, cast: bool) -> Result<i64, String> {
get_attr_as_type!(self, nc_int64, i64, nc_get_att_longlong, cast)
}
pub fn get_uint64(&self, cast: bool) -> Result<u64, String> {
get_attr_as_type!(self, nc_uint64, u64, nc_get_att_ulonglong, cast)
}
pub fn get_float(&self, cast: bool) -> Result<f32, String> {
get_attr_as_type!(self, nc_float, f32, nc_get_att_float, cast)
}
pub fn get_double(&self, cast: bool) -> Result<f64, String> {
get_attr_as_type!(self, nc_double, f64, nc_get_att_double, cast)
}
}
pub fn init_attributes(attrs: &mut HashMap<String, Attribute>,
file_id: i32,
var_id: i32,
natts_in: i32) { // TODO: better interface to indicate these are var attrs
let mut nattrs = 0i32;
if natts_in == -1 {
// these are global attrs; have to determine number of attrs
unsafe {
let _g = libnetcdf_lock.lock().unwrap();
let err = nc_inq_natts(file_id, &mut nattrs);
assert_eq!(err, nc_noerr);
}
} else {
nattrs = natts_in;
}
// read each attr name, type, value
let mut attr_type: nc_type = 0;
for i_attr in 0..nattrs {
let mut name_buf_vec = vec![0i8; (nc_max_name + 1) as usize];
let name_c_str: &ffi::CStr;
unsafe {
let _g = libnetcdf_lock.lock().unwrap();
let name_buf_ptr : *mut i8 = name_buf_vec.as_mut_ptr();
let err = nc_inq_attname(file_id, var_id, i_attr, name_buf_ptr);
assert_eq!(err, nc_noerr);
let err = nc_inq_atttype(file_id, var_id, name_buf_ptr, &mut attr_type);
assert_eq!(err, nc_noerr);
name_c_str = ffi::CStr::from_ptr(name_buf_ptr);
}
let name_str: String = string_from_c_str(name_c_str);
attrs.insert(name_str.clone(),
Attribute{name: name_str.clone(),
attrtype: attr_type,
id: i_attr,
var_id: var_id,
file_id: file_id});
}
}

40
src/dimension.rs Normal file
View File

@ -0,0 +1,40 @@
use std::ffi;
use std::collections::HashMap;
use netcdf_sys::*;
use string_from_c_str;
#[derive(Clone)]
pub struct Dimension {
pub name : String,
pub len: u64,
pub id: i32,
}
pub fn init_dimensions(dims: &mut HashMap<String, Dimension>, grp_id: i32) {
// determine number of dims
let mut ndims = 0i32;
unsafe {
let _g = libnetcdf_lock.lock().unwrap();
let err = nc_inq_ndims(grp_id, &mut ndims);
assert_eq!(err, nc_noerr);
}
// read each dim name and length
for i_dim in 0..ndims {
let mut buf_vec = vec![0i8; (nc_max_name + 1) as usize];
let mut dimlen : u64 = 0u64;
let c_str: &ffi::CStr;
unsafe {
let _g = libnetcdf_lock.lock().unwrap();
let buf_ptr : *mut i8 = buf_vec.as_mut_ptr();
let err = nc_inq_dim(grp_id, i_dim, buf_ptr, &mut dimlen);
assert_eq!(err, nc_noerr);
c_str = ffi::CStr::from_ptr(buf_ptr);
}
let str_buf: String = string_from_c_str(c_str);
dims.insert(str_buf.clone(),
Dimension{name: str_buf.clone(),
len: dimlen,
id: i_dim});
}
}

78
src/file.rs Normal file
View File

@ -0,0 +1,78 @@
use std::ffi;
use std::path;
use std::collections::HashMap;
use netcdf_sys::*;
use group::{init_group, Group};
use NC_ERRORS;
pub struct File {
pub id: i32,
pub name: String,
pub root: Group,
}
pub fn open(file: &str) -> Result<File, String> {
let data_path = path::Path::new(file);
let f = ffi::CString::new(data_path.to_str().unwrap()).unwrap();
let mut ncid : i32 = -999999i32;
let err : i32;
unsafe {
let _g = libnetcdf_lock.lock().unwrap();
err = nc_open(f.as_ptr(), nc_nowrite, &mut ncid);
}
if err != nc_noerr {
return Err(NC_ERRORS.get(&err).unwrap().clone());
}
let mut root = Group {
name: "root".to_string(),
id: ncid,
variables: HashMap::new(),
attributes: HashMap::new(),
dimensions: HashMap::new(),
sub_groups: HashMap::new(),
};
init_group(&mut root);
Ok(File {
id: ncid,
name: file.to_string(),
root: root,
})
}
pub fn create(file: &str) -> Result<File, String> {
let data_path = path::Path::new(file);
let f = ffi::CString::new(data_path.to_str().unwrap()).unwrap();
let mut ncid : i32 = -999999i32;
let err : i32;
unsafe {
let _g = libnetcdf_lock.lock().unwrap();
err = nc_create(f.as_ptr(), nc_write|nc_netcdf4, &mut ncid);
}
if err != nc_noerr {
return Err(NC_ERRORS.get(&err).unwrap().clone());
}
let root = Group {
name: "root".to_string(),
id: ncid,
variables: HashMap::new(),
attributes: HashMap::new(),
dimensions: HashMap::new(),
sub_groups: HashMap::new(),
};
Ok(File {
id: ncid,
name: file.to_string(),
root: root,
})
}
impl Drop for File {
fn drop(&mut self) {
unsafe {
let _g = libnetcdf_lock.lock().unwrap();
let err = nc_close(self.id);
assert_eq!(err, nc_noerr);
}
}
}

367
src/group.rs Normal file
View File

@ -0,0 +1,367 @@
use std::collections::HashMap;
use std::ffi;
use netcdf_sys::*;
use dimension::{init_dimensions, Dimension};
use attribute::{init_attributes, Attribute};
use variable::{init_variables, Variable};
use string_from_c_str;
use NC_ERRORS;
pub struct Group {
pub name : String,
pub id : i32,
pub variables : HashMap<String, Variable>,
pub attributes : HashMap<String, Attribute>,
pub dimensions : HashMap<String, Dimension>,
pub sub_groups : HashMap<String, Group>,
}
macro_rules! put_var_as_type {
( $me:ident, $ncid:ident, $varid:ident, $nc_fn:ident )
=>
{{
let err : i32;
unsafe {
let _g = libnetcdf_lock.lock().unwrap();
err = $nc_fn($ncid, $varid, $me.as_ptr());
}
if err != nc_noerr {
return Err(NC_ERRORS.get(&err).unwrap().clone());
}
Ok(())
}};
}
macro_rules! put_attr_as_type {
( $me:ident, $attname:ident, $ncid:ident, $nctype: ident,
$varid:ident, $nc_fn:ident )
=>
{{
let name_c: ffi::CString = ffi::CString::new($attname.clone()).unwrap();
let err : i32;
unsafe {
let _g = libnetcdf_lock.lock().unwrap();
err = $nc_fn($ncid, $varid, name_c.as_ptr(), $nctype, 1, $me);
}
if err != nc_noerr {
return Err(NC_ERRORS.get(&err).unwrap().clone());
}
Ok(())
}};
}
// Write support for all variable types ... excuse the repetition :(
pub trait PutVar {
fn get_nc_type(&self) -> i32;
fn put(&self, ncid: i32, varid: i32) -> Result<(), String> ;
fn len(&self) -> usize;
}
impl PutVar for Vec<i8> {
fn get_nc_type(&self) -> i32 { nc_byte }
fn len(&self) -> usize { self.len() }
fn put(&self, ncid: i32, varid: i32) -> Result<(), String> {
put_var_as_type!(self, ncid, varid, nc_put_var_schar)
}
}
impl PutVar for Vec<i16> {
fn get_nc_type(&self) -> i32 { nc_short }
fn len(&self) -> usize { self.len() }
fn put(&self, ncid: i32, varid: i32) -> Result<(), String> {
put_var_as_type!(self, ncid, varid, nc_put_var_short)
}
}
impl PutVar for Vec<u16> {
fn get_nc_type(&self) -> i32 { nc_ushort }
fn len(&self) -> usize { self.len() }
fn put(&self, ncid: i32, varid: i32) -> Result<(), String> {
put_var_as_type!(self, ncid, varid, nc_put_var_ushort)
}
}
impl PutVar for Vec<i32> {
fn get_nc_type(&self) -> i32 { nc_int }
fn len(&self) -> usize { self.len() }
fn put(&self, ncid: i32, varid: i32) -> Result<(), String> {
put_var_as_type!(self, ncid, varid, nc_put_var_int)
}
}
impl PutVar for Vec<u32> {
fn get_nc_type(&self) -> i32 { nc_uint }
fn len(&self) -> usize { self.len() }
fn put(&self, ncid: i32, varid: i32) -> Result<(), String> {
put_var_as_type!(self, ncid, varid, nc_put_var_uint)
}
}
impl PutVar for Vec<i64> {
fn get_nc_type(&self) -> i32 { nc_int64 }
fn len(&self) -> usize { self.len() }
fn put(&self, ncid: i32, varid: i32) -> Result<(), String> {
put_var_as_type!(self, ncid, varid, nc_put_var_longlong)
}
}
impl PutVar for Vec<u64> {
fn get_nc_type(&self) -> i32 { nc_uint64 }
fn len(&self) -> usize { self.len() }
fn put(&self, ncid: i32, varid: i32) -> Result<(), String> {
put_var_as_type!(self, ncid, varid, nc_put_var_ulonglong)
}
}
impl PutVar for Vec<f32> {
fn get_nc_type(&self) -> i32 { nc_float }
fn len(&self) -> usize { self.len() }
fn put(&self, ncid: i32, varid: i32) -> Result<(), String> {
put_var_as_type!(self, ncid, varid, nc_put_var_float)
}
}
impl PutVar for Vec<f64> {
fn get_nc_type(&self) -> i32 { nc_double }
fn len(&self) -> usize { self.len() }
fn put(&self, ncid: i32, varid: i32) -> Result<(), String> {
put_var_as_type!(self, ncid, varid, nc_put_var_double)
}
}
// Write support for all attribute types
pub trait PutAttr {
fn get_nc_type(&self) -> i32;
fn put(&self, ncid: i32, varid: i32, name: &str) -> Result<(), String> ;
}
impl PutAttr for i8 {
fn get_nc_type(&self) -> i32 { nc_byte }
fn put(&self, ncid: i32, varid: i32, name: &str) -> Result<(), String> {
put_attr_as_type!(self, name, ncid, nc_byte, varid, nc_put_att_schar)
}
}
impl PutAttr for i16 {
fn get_nc_type(&self) -> i32 { nc_short }
fn put(&self, ncid: i32, varid: i32, name: &str) -> Result<(), String> {
put_attr_as_type!(self, name, ncid, nc_short, varid, nc_put_att_short)
}
}
impl PutAttr for u16 {
fn get_nc_type(&self) -> i32 { nc_ushort }
fn put(&self, ncid: i32, varid: i32, name: &str) -> Result<(), String> {
put_attr_as_type!(self, name, ncid, nc_ushort, varid, nc_put_att_ushort)
}
}
impl PutAttr for i32 {
fn get_nc_type(&self) -> i32 { nc_int }
fn put(&self, ncid: i32, varid: i32, name: &str) -> Result<(), String> {
put_attr_as_type!(self, name, ncid, nc_int, varid, nc_put_att_int)
}
}
impl PutAttr for u32 {
fn get_nc_type(&self) -> i32 { nc_uint }
fn put(&self, ncid: i32, varid: i32, name: &str) -> Result<(), String> {
put_attr_as_type!(self, name, ncid, nc_uint, varid, nc_put_att_uint)
}
}
impl PutAttr for i64 {
fn get_nc_type(&self) -> i32 { nc_int64 }
fn put(&self, ncid: i32, varid: i32, name: &str) -> Result<(), String> {
put_attr_as_type!(self, name, ncid, nc_int64, varid, nc_put_att_longlong)
}
}
impl PutAttr for u64 {
fn get_nc_type(&self) -> i32 { nc_uint64 }
fn put(&self, ncid: i32, varid: i32, name: &str) -> Result<(), String> {
put_attr_as_type!(self, name, ncid, nc_uint64, varid, nc_put_att_ulonglong)
}
}
impl PutAttr for f32 {
fn get_nc_type(&self) -> i32 { nc_float }
fn put(&self, ncid: i32, varid: i32, name: &str) -> Result<(), String> {
put_attr_as_type!(self, name, ncid, nc_float, varid, nc_put_att_float)
}
}
impl PutAttr for f64 {
fn get_nc_type(&self) -> i32 { nc_double }
fn put(&self, ncid: i32, varid: i32, name: &str) -> Result<(), String> {
put_attr_as_type!(self, name, ncid, nc_double, varid, nc_put_att_double)
}
}
impl PutAttr for String {
fn get_nc_type(&self) -> i32 { nc_char }
fn put(&self, ncid: i32, varid: i32, name: &str) -> Result<(), String> {
let name_c: ffi::CString = ffi::CString::new(name.clone()).unwrap();
let attr_c: ffi::CString = ffi::CString::new(self.clone()).unwrap();
let err : i32;
unsafe {
let _g = libnetcdf_lock.lock().unwrap();
err = nc_put_att_text(
ncid, varid, name_c.as_ptr(),
attr_c.to_bytes().len() as u64, attr_c.as_ptr());
}
if err != nc_noerr {
return Err(NC_ERRORS.get(&err).unwrap().clone());
}
Ok(())
}
}
impl Group {
pub fn add_attribute<T: PutAttr>(&mut self, name: &str, val: T)
-> Result<(), String> {
try!(val.put(self.id, nc_global, name));
self.attributes.insert(
name.to_string().clone(),
Attribute {
name: name.to_string().clone(),
attrtype: val.get_nc_type(),
id: 0, // XXX Should Attribute even keep track of an id?
var_id: nc_global,
file_id: self.id
}
);
Ok(())
}
pub fn add_dimension(&mut self, name: &str, len: u64)
-> Result<(), String> {
let name_c: ffi::CString = ffi::CString::new(name.clone()).unwrap();
let mut dimid: i32 = 0;
let err : i32;
unsafe {
let _g = libnetcdf_lock.lock().unwrap();
err = nc_def_dim(self.id, name_c.as_ptr(), len, &mut dimid);
}
if err != nc_noerr {
return Err(NC_ERRORS.get(&err).unwrap().clone());
}
self.dimensions.insert(
name.to_string().clone(),
Dimension {
name: name.to_string().clone(),
len: len,
id: dimid
}
);
Ok(())
}
// TODO this should probably take &Vec<&str> instead of &Vec<String>
pub fn add_variable<T: PutVar>(
&mut self, name: &str, dims: &Vec<String>, data: &T)
-> Result<(), String>
{
let name_c: ffi::CString = ffi::CString::new(name.clone()).unwrap();
let mut dimids: Vec<i32> = Vec::with_capacity(dims.len());
let mut var_len : u64 = 1;
let mut var_dims : Vec<Dimension> = Vec::with_capacity(dims.len());
let nctype = data.get_nc_type();
for dim_name in dims {
if !self.dimensions.contains_key(dim_name) {
return Err("Invalid dimension name".to_string());
}
var_dims.push(self.dimensions.get(dim_name).unwrap().clone());
}
for dim in &var_dims {
dimids.push(dim.id);
var_len *= dim.len;
}
if data.len() != (var_len as usize) {
return Err("Vec length must match product of all dims".to_string());
}
let mut varid: i32 = 0;
let err : i32;
unsafe {
let _g = libnetcdf_lock.lock().unwrap();
err = nc_def_var(self.id, name_c.as_ptr(), nctype,
dims.len() as i32, dimids.as_ptr(), &mut varid);
}
if err != nc_noerr {
return Err(NC_ERRORS.get(&err).unwrap().clone());
}
try!(data.put(self.id, varid));
self.variables.insert(
name.to_string().clone(),
Variable {
name: name.to_string().clone(),
attributes: HashMap::new(),
dimensions: var_dims,
vartype: nctype,
id: varid,
len: var_len,
file_id: self.id
}
);
Ok(())
}
}
fn init_sub_groups(grp_id: i32, sub_groups: &mut HashMap<String, Group>,
parent_dims: &HashMap<String, Dimension>) {
let mut ngrps = 0i32;
// Max number of groups in a file is only limited by i32 max (32767)...
// allocating a vec this size is inefficient but there's no obvious way
// to query the number of groups beforehand!
// http://www.unidata.ucar.edu/software/netcdf/docs/group__groups.html#details
let mut grpids : Vec<i32> = Vec::with_capacity(nc_max_int as usize);
unsafe {
let _g = libnetcdf_lock.lock().unwrap();
// number of groups and grp id's
let err = nc_inq_grps(grp_id, &mut ngrps, grpids.as_mut_ptr());
assert_eq!(err, nc_noerr);
grpids.set_len(ngrps as usize);
}
for i_grp in 0..ngrps {
let mut namelen = 0u64;
let c_str: &ffi::CStr;
unsafe {
let _g = libnetcdf_lock.lock().unwrap();
// name length
let err = nc_inq_grpname_len(grpids[i_grp as usize], &mut namelen);
assert_eq!(err, nc_noerr);
// name
let mut buf_vec = vec![0i8; (namelen+1) as usize];
let buf_ptr : *mut i8 = buf_vec.as_mut_ptr();
let err = nc_inq_grpname(grpids[i_grp as usize], buf_ptr);
assert_eq!(err, nc_noerr);
c_str = ffi::CStr::from_ptr(buf_ptr);
}
let str_buf: String = string_from_c_str(c_str);
// Per NetCDF doc, "Dimensions are visible in their groups, and all
// child groups."
let mut new_grp = Group {
name: str_buf.clone(),
id: grpids[i_grp as usize],
variables: HashMap::new(),
attributes: HashMap::new(),
dimensions: parent_dims.clone(),
sub_groups: HashMap::new(),
};
init_group(&mut new_grp);
sub_groups.insert(str_buf.clone(), new_grp);
}
}
pub fn init_group(grp: &mut Group) {
init_dimensions(&mut grp.dimensions, grp.id);
init_attributes(&mut grp.attributes, grp.id, nc_global, -1);
init_variables(&mut grp.variables, grp.id, &grp.dimensions);
init_sub_groups(grp.id, &mut grp.sub_groups, &grp.dimensions);
}

108
src/lib.rs Normal file
View File

@ -0,0 +1,108 @@
//! Rust bindings for Unidata's [libnetcdf] (http://www.unidata.ucar.edu/software/netcdf/)
//!
//! # Examples
//!
//! Read:
//!
//! ```
//! # let path_to_simple_xy = netcdf::test_file("simple_xy.nc");
//! // Open file simple_xy.nc:
//! let file = netcdf::open(&path_to_simple_xy).unwrap();
//!
//! // Access any variable, attribute, or dimension through simple HashMap's:
//! let var = file.root.variables.get("data").unwrap();
//!
//! // Read variable as any NC_TYPE, optionally failing if doing so would
//! // force a cast:
//! let data : Vec<i32> = var.get_int(false).unwrap();
//!
//! // All variable data is read into 1-dimensional Vec.
//! for x in 0..(6*12) {
//! assert_eq!(data[x], x as i32);
//! }
//! ```
//!
//! Write:
//!
//! ```
//! let f = netcdf::test_file_new("crabs.nc"); // just gets a path inside repo
//!
//! let mut file = netcdf::create(&f).unwrap();
//!
//! let dim_name = "ncrabs";
//! file.root.add_dimension(dim_name, 10).unwrap();
//!
//! let var_name = "crab_coolness_level";
//! let data : Vec<i32> = vec![42; 10];
//! // Variable type written to file is inferred from Vec type:
//! file.root.add_variable(
//! var_name,
//! &vec![dim_name.to_string()],
//! &data
//! ).unwrap();
//! ```
extern crate netcdf_sys;
#[macro_use]
extern crate lazy_static;
use netcdf_sys::{libnetcdf_lock, nc_strerror};
use std::ffi;
use std::str;
use std::path;
use std::env;
use std::fs;
use std::collections::HashMap;
pub mod file;
pub mod variable;
pub mod attribute;
pub mod group;
pub mod dimension;
pub use file::open;
pub use file::create;
fn string_from_c_str(c_str: &ffi::CStr) -> String {
// see http://stackoverflow.com/questions/24145823/rust-ffi-c-string-handling
// for good rundown
let buf: &[u8] = c_str.to_bytes();
let str_slice: &str = str::from_utf8(buf).unwrap();
str_slice.to_owned()
}
lazy_static! {
pub static ref NC_ERRORS: HashMap<i32, String> = {
let mut m = HashMap::new();
// Invalid error codes are ok; nc_strerror will just return
// "Unknown Error"
for i in -256..256 {
let msg_cstr : &ffi::CStr;
unsafe {
let _g = libnetcdf_lock.lock().unwrap();
let msg : *const i8 = nc_strerror(i);
msg_cstr = &ffi::CStr::from_ptr(msg);
}
m.insert(i, string_from_c_str(msg_cstr));
}
m
};
}
// Helpers for getting file paths
pub fn test_file(f: &str) -> String {
let mnf_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let path = path::Path::new(&mnf_dir).join(
"testdata").join(f);
path.to_str().unwrap().to_string()
}
pub fn test_file_new(f: &str) -> String {
let mnf_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let path = path::Path::new(&mnf_dir).join("testout");
let new_file = path.join(f);
let _err = fs::create_dir(path);
new_file.to_str().unwrap().to_string()
}

144
src/variable.rs Normal file
View File

@ -0,0 +1,144 @@
use std::ffi;
use std::collections::HashMap;
use netcdf_sys::*;
use dimension::Dimension;
use group::PutAttr;
use attribute::{init_attributes, Attribute};
use string_from_c_str;
use NC_ERRORS;
macro_rules! get_var_as_type {
( $me:ident, $nc_type:ident, $vec_type:ty, $nc_fn:ident , $cast:ident )
=>
{{
if (!$cast) && ($me.vartype != $nc_type) {
return Err("Types are not equivalent and cast==false".to_string());
}
let mut buf: Vec<$vec_type> = Vec::with_capacity($me.len as usize);
let err: i32;
unsafe {
let _g = libnetcdf_lock.lock().unwrap();
buf.set_len($me.len as usize);
err = $nc_fn($me.file_id, $me.id, buf.as_mut_ptr());
}
if err != nc_noerr {
return Err(NC_ERRORS.get(&err).unwrap().clone());
}
Ok(buf)
}};
}
pub struct Variable {
pub name : String,
pub attributes : HashMap<String, Attribute>,
pub dimensions : Vec<Dimension>,
pub vartype : i32,
pub id: i32,
pub len: u64, // total length; the product of all dim lengths
pub file_id: i32,
}
impl Variable {
pub fn get_char(&self, cast: bool) -> Result<Vec<u8>, String> {
get_var_as_type!(self, nc_char, u8, nc_get_var_uchar, cast)
}
pub fn get_byte(&self, cast: bool) -> Result<Vec<i8>, String> {
get_var_as_type!(self, nc_byte, i8, nc_get_var_schar, cast)
}
pub fn get_short(&self, cast: bool) -> Result<Vec<i16>, String> {
get_var_as_type!(self, nc_short, i16, nc_get_var_short, cast)
}
pub fn get_ushort(&self, cast: bool) -> Result<Vec<u16>, String> {
get_var_as_type!(self, nc_ushort, u16, nc_get_var_ushort, cast)
}
pub fn get_int(&self, cast: bool) -> Result<Vec<i32>, String> {
get_var_as_type!(self, nc_int, i32, nc_get_var_int, cast)
}
pub fn get_uint(&self, cast: bool) -> Result<Vec<u32>, String> {
get_var_as_type!(self, nc_uint, u32, nc_get_var_uint, cast)
}
pub fn get_int64(&self, cast: bool) -> Result<Vec<i64>, String> {
get_var_as_type!(self, nc_int64, i64, nc_get_var_longlong, cast)
}
pub fn get_uint64(&self, cast: bool) -> Result<Vec<u64>, String> {
get_var_as_type!(self, nc_uint64, u64, nc_get_var_ulonglong, cast)
}
pub fn get_float(&self, cast: bool) -> Result<Vec<f32>, String> {
get_var_as_type!(self, nc_float, f32, nc_get_var_float, cast)
}
pub fn get_double(&self, cast: bool) -> Result<Vec<f64>, String> {
get_var_as_type!(self, nc_double, f64, nc_get_var_double, cast)
}
pub fn add_attribute<T: PutAttr>(&mut self, name: &str, val: T)
-> Result<(), String> {
try!(val.put(self.file_id, self.id, name));
self.attributes.insert(
name.to_string().clone(),
Attribute {
name: name.to_string().clone(),
attrtype: val.get_nc_type(),
id: 0, // XXX Should Attribute even keep track of an id?
var_id: self.id,
file_id: self.file_id
}
);
Ok(())
}
}
pub fn init_variables(vars: &mut HashMap<String, Variable>, grp_id: i32,
grp_dims: &HashMap<String, Dimension>) {
// determine number of vars
let mut nvars = 0i32;
unsafe {
let _g = libnetcdf_lock.lock().unwrap();
let err = nc_inq_nvars(grp_id, &mut nvars);
assert_eq!(err, nc_noerr);
}
// read each dim name and length
for i_var in 0..nvars {
let mut buf_vec = vec![0i8; (nc_max_name + 1) as usize];
let c_str: &ffi::CStr;
let mut var_type : i32 = 0;
let mut ndims : i32 = 0;
let mut dimids : Vec<i32> = Vec::with_capacity(nc_max_dims as usize);
let mut natts : i32 = 0;
unsafe {
let _g = libnetcdf_lock.lock().unwrap();
let buf_ptr : *mut i8 = buf_vec.as_mut_ptr();
let err = nc_inq_var(grp_id, i_var, buf_ptr,
&mut var_type, &mut ndims,
dimids.as_mut_ptr(), &mut natts);
dimids.set_len(ndims as usize);
assert_eq!(err, nc_noerr);
c_str = ffi::CStr::from_ptr(buf_ptr);
}
let str_buf: String = string_from_c_str(c_str);
let mut attr_map : HashMap<String, Attribute> = HashMap::new();
init_attributes(&mut attr_map, grp_id, i_var, natts);
// var dims should always be a subset of the group dims:
let mut dim_vec : Vec<Dimension> = Vec::new();
let mut len : u64 = 1;
for dimid in dimids {
// maintaining dim order is crucial here so we can maintain
// rule that "last dim varies fastest" in our 1D return Vec
for (_, grp_dim) in grp_dims {
if dimid == grp_dim.id {
len *= grp_dim.len;
dim_vec.push(grp_dim.clone());
break
}
}
}
vars.insert(str_buf.clone(),
Variable{name: str_buf.clone(),
attributes: attr_map,
dimensions: dim_vec,
vartype: var_type,
len: len,
id: i_var,
file_id: grp_id});
}
}

BIN
testdata/pres_temp_4D.nc vendored Normal file

Binary file not shown.

BIN
testdata/sfc_pres_temp.nc vendored Normal file

Binary file not shown.

BIN
testdata/simple_nc4.nc vendored Normal file

Binary file not shown.

BIN
testdata/simple_xy.nc vendored Normal file

Binary file not shown.

487
tests/lib.rs Normal file
View File

@ -0,0 +1,487 @@
extern crate netcdf;
use netcdf::{test_file, test_file_new};
// Failure tests
#[test]
#[should_panic(expected = "No such file or directory")]
fn bad_filename() {
let f = test_file("blah_stuff.nc");
let _file = netcdf::open(&f).unwrap();
}
// Read tests
#[test]
fn root_dims() {
let f = test_file("simple_xy.nc");
let file = netcdf::open(&f).unwrap();
assert_eq!(f, file.name);
assert_eq!(file.root.dimensions.get("x").unwrap().len, 6);
assert_eq!(file.root.dimensions.get("y").unwrap().len, 12);
}
#[test]
fn global_attrs() {
let f = test_file("patmosx_v05r03-preliminary_NOAA-19_asc_d20130630_c20140325.nc");
let file = netcdf::open(&f).unwrap();
assert_eq!(f, file.name);
let ch1_attr = file.root.attributes.get("CH1_DARK_COUNT").unwrap();
let ch1 = ch1_attr.get_float(false).unwrap();
let eps = 1e-6;
assert!((ch1-40.65863).abs() < eps);
let ch1 = ch1_attr.get_int(true).unwrap();
assert_eq!(ch1, 40);
let sensor_attr = file.root.attributes.get("sensor").unwrap();
let sensor_data = sensor_attr.get_char(false).unwrap();
assert_eq!("AVHRR/3".to_string(), sensor_data);
}
#[test]
fn var_cast() {
let f = test_file("simple_xy.nc");
let file = netcdf::open(&f).unwrap();
assert_eq!(f, file.name);
let var = file.root.variables.get("data").unwrap();
let data : Vec<i32> = var.get_int(false).unwrap();
assert_eq!(data.len(), 6*12);
for x in 0..(6*12) {
assert_eq!(data[x], x as i32);
}
// do the same thing but cast to float
let data : Vec<f32> = var.get_float(true).unwrap();
assert_eq!(data.len(), 6*12);
for x in 0..(6*12) {
assert_eq!(data[x], x as f32);
}
}
#[test]
#[should_panic(expected = "Types are not equivalent and cast==false")]
fn var_cast_fail() {
let f = test_file("simple_xy.nc");
let file = netcdf::open(&f).unwrap();
let var = file.root.variables.get("data").unwrap();
// getting int Variable as float with false argument should fail.
let _data : Vec<f32> = var.get_float(false).unwrap();
}
#[test]
fn last_dim_varies_fastest() {
let f = test_file("simple_xy.nc");
let file = netcdf::open(&f).unwrap();
assert_eq!(f, file.name);
let var = file.root.variables.get("data").unwrap();
let data : Vec<i32> = var.get_int(false).unwrap();
let nx = var.dimensions[0].len;
let ny = var.dimensions[1].len;
assert_eq!(nx, 6);
assert_eq!(ny, 12);
assert_eq!(nx*ny, var.len);
for x in 0..nx {
for y in 0..ny {
let ind = x*nx + y;
assert_eq!(data[ind as usize], ind as i32);
}
}
}
#[test]
fn open_pres_temp_4d() {
let f = test_file("pres_temp_4D.nc");
let file = netcdf::open(&f).unwrap();
assert_eq!(f, file.name);
let pres = file.root.variables.get("pressure").unwrap();
assert_eq!(pres.dimensions[0].name, "time");
assert_eq!(pres.dimensions[1].name, "level");
assert_eq!(pres.dimensions[2].name, "latitude");
assert_eq!(pres.dimensions[3].name, "longitude");
// test var attributes
assert_eq!(pres.attributes.get("units").unwrap().get_char(false).unwrap(),
"hPa".to_string());
}
#[test]
fn nc4_groups() {
let f = test_file("simple_nc4.nc");
let file = netcdf::open(&f).unwrap();
assert_eq!(f, file.name);
let grp1 = file.root.sub_groups.get("grp1").unwrap();
assert_eq!(grp1.name, "grp1".to_string());
let var = grp1.variables.get("data").unwrap();
let data : Vec<i32> = var.get_int(true).unwrap();
for x in 0..(6*12) {
assert_eq!(data[x], x as i32);
}
}
// Write tests
#[test]
fn create() {
let f = test_file_new("create.nc");
let file = netcdf::create(&f).unwrap();
assert_eq!(f, file.name);
}
#[test]
fn def_dims_vars_attrs() {
{
let f = test_file_new("def_dims_vars_attrs.nc");
let mut file = netcdf::create(&f).unwrap();
let dim1_name = "ljkdsjkldfs";
let dim2_name = "dsfkdfskl";
file.root.add_dimension(dim1_name, 10).unwrap();
file.root.add_dimension(dim2_name, 20).unwrap();
assert_eq!(file.root.dimensions.get(dim1_name).unwrap().len, 10);
assert_eq!(file.root.dimensions.get(dim2_name).unwrap().len, 20);
let var_name = "varstuff_int";
let data : Vec<i32> = vec![42; (10*20)];
file.root.add_variable(
var_name,
&vec![dim1_name.to_string(), dim2_name.to_string()],
&data
).unwrap();
assert_eq!(file.root.variables.get(var_name).unwrap().len, 20*10);
let var_name = "varstuff_float";
let data : Vec<f32> = vec![42.2; 10];
file.root.add_variable(
var_name,
&vec![dim1_name.to_string()],
&data
).unwrap();
assert_eq!(file.root.variables.get(var_name).unwrap().len, 10);
// test global attrs
file.root.add_attribute(
"testattr1",
3,
).unwrap();
file.root.add_attribute(
"testattr2",
"Global string attr".to_string(),
).unwrap();
// test var attrs
file.root.variables.get_mut(var_name).unwrap().add_attribute(
"varattr1",
5,
).unwrap();
file.root.variables.get_mut(var_name).unwrap().add_attribute(
"varattr2",
"Variable string attr".to_string(),
).unwrap();
}
// now, read in the file we created and verify everything
{
let f = test_file_new("def_dims_vars_attrs.nc");
let file = netcdf::open(&f).unwrap();
// verify dimensions
let dim1_name = "ljkdsjkldfs";
let dim2_name = "dsfkdfskl";
let dim1 = file.root.dimensions.get(dim1_name).unwrap();
let dim2 = file.root.dimensions.get(dim2_name).unwrap();
assert_eq!(dim1.len, 10);
assert_eq!(dim2.len, 20);
// verify variable data
let var_name = "varstuff_int";
let data_test : Vec<i32> = vec![42; (10*20)];
let data_file : Vec<i32> =
file.root.variables.get(var_name).unwrap().get_int(false).unwrap();
assert_eq!(data_test.len(), data_file.len());
for i in 0..data_test.len() {
assert_eq!(data_test[i], data_file[i]);
}
let var_name = "varstuff_float";
let data_test : Vec<f32> = vec![42.2; 10];
let data_file : Vec<f32> =
file.root.variables.get(var_name).unwrap().get_float(false).unwrap();
assert_eq!(data_test.len(), data_file.len());
for i in 0..data_test.len() {
assert_eq!(data_test[i], data_file[i]);
}
// verify global attrs
assert_eq!(3,
file.root.attributes.get("testattr1").unwrap().get_int(false).unwrap());
assert_eq!("Global string attr".to_string(),
file.root.attributes.get("testattr2").unwrap().get_char(false).unwrap());
// verify var attrs
assert_eq!(5,
file.root.variables.get(var_name).unwrap()
.attributes.get("varattr1").unwrap().get_int(false).unwrap());
assert_eq!("Variable string attr",
file.root.variables.get(var_name).unwrap()
.attributes.get("varattr2").unwrap().get_char(false).unwrap());
}
}
#[test]
fn all_var_types() {
// write
{
let f = test_file_new("all_var_types.nc");
let mut file = netcdf::create(&f).unwrap();
let dim_name = "dim1";
file.root.add_dimension(dim_name, 10).unwrap();
// byte
let data : Vec<i8> = vec![42 as i8; 10];
let var_name = "var_byte";
file.root.add_variable(
var_name,
&vec![dim_name.to_string()],
&data
).unwrap();
// short
let data : Vec<i16> = vec![42 as i16; 10];
let var_name = "var_short";
file.root.add_variable(
var_name,
&vec![dim_name.to_string()],
&data
).unwrap();
// ushort
let data : Vec<u16> = vec![42 as u16; 10];
let var_name = "var_ushort";
file.root.add_variable(
var_name,
&vec![dim_name.to_string()],
&data
).unwrap();
// int
let data : Vec<i32> = vec![42 as i32; 10];
let var_name = "var_int";
file.root.add_variable(
var_name,
&vec![dim_name.to_string()],
&data
).unwrap();
// uint
let data : Vec<u32> = vec![42 as u32; 10];
let var_name = "var_uint";
file.root.add_variable(
var_name,
&vec![dim_name.to_string()],
&data
).unwrap();
// int64
let data : Vec<i64> = vec![42 as i64; 10];
let var_name = "var_int64";
file.root.add_variable(
var_name,
&vec![dim_name.to_string()],
&data
).unwrap();
// uint64
let data : Vec<u64> = vec![42 as u64; 10];
let var_name = "var_uint64";
file.root.add_variable(
var_name,
&vec![dim_name.to_string()],
&data
).unwrap();
// float
let data : Vec<f32> = vec![42.2 as f32; 10];
let var_name = "var_float";
file.root.add_variable(
var_name,
&vec![dim_name.to_string()],
&data
).unwrap();
// double
let data : Vec<f64> = vec![42.2 as f64; 10];
let var_name = "var_double";
file.root.add_variable(
var_name,
&vec![dim_name.to_string()],
&data
).unwrap();
}
// read
{
let f = test_file_new("all_var_types.nc");
let file = netcdf::open(&f).unwrap();
// byte
let data : Vec<i8> =
file.root.variables.get("var_byte").unwrap().get_byte(false).unwrap();
for i in 0..10 {
assert_eq!(42 as i8, data[i]);
}
// short
let data : Vec<i16> =
file.root.variables.get("var_short").unwrap().get_short(false).unwrap();
for i in 0..10 {
assert_eq!(42 as i16, data[i]);
}
// ushort
let data : Vec<u16> =
file.root.variables.get("var_ushort").unwrap().get_ushort(false).unwrap();
for i in 0..10 {
assert_eq!(42 as u16, data[i]);
}
// int
let data : Vec<i32> =
file.root.variables.get("var_int").unwrap().get_int(false).unwrap();
for i in 0..10 {
assert_eq!(42 as i32, data[i]);
}
// uint
let data : Vec<u32> =
file.root.variables.get("var_uint").unwrap().get_uint(false).unwrap();
for i in 0..10 {
assert_eq!(42 as u32, data[i]);
}
// int64
let data : Vec<i64> =
file.root.variables.get("var_int64").unwrap().get_int64(false).unwrap();
for i in 0..10 {
assert_eq!(42 as i64, data[i]);
}
// uint64
let data : Vec<u64> =
file.root.variables.get("var_uint64").unwrap().get_uint64(false).unwrap();
for i in 0..10 {
assert_eq!(42 as u64, data[i]);
}
// float
let data : Vec<f32> =
file.root.variables.get("var_float").unwrap().get_float(false).unwrap();
for i in 0..10 {
assert_eq!(42.2 as f32, data[i]);
}
// double
let data : Vec<f64> =
file.root.variables.get("var_double").unwrap().get_double(false).unwrap();
for i in 0..10 {
assert_eq!(42.2 as f64, data[i]);
}
}
}
#[test]
fn all_attr_types() {
{
let f = test_file_new("all_attr_types.nc");
let mut file = netcdf::create(&f).unwrap();
// byte
file.root.add_attribute(
"attr_byte",
3 as i8,
).unwrap();
// short
file.root.add_attribute(
"attr_short",
3 as i16,
).unwrap();
// ushort
file.root.add_attribute(
"attr_ushort",
3 as u16,
).unwrap();
// int
file.root.add_attribute(
"attr_int",
3 as i32,
).unwrap();
// uint
file.root.add_attribute(
"attr_uint",
3 as u32,
).unwrap();
// int64
file.root.add_attribute(
"attr_int64",
3 as i64,
).unwrap();
// uint64
file.root.add_attribute(
"attr_uint64",
3 as u64,
).unwrap();
// float
file.root.add_attribute(
"attr_float",
3.2 as f32,
).unwrap();
// double
file.root.add_attribute(
"attr_double",
3.2 as f64,
).unwrap();
}
{
let f = test_file_new("all_attr_types.nc");
let file = netcdf::open(&f).unwrap();
// byte
assert_eq!(3 as i8,
file.root.attributes.get("attr_byte").unwrap().get_byte(false).unwrap());
// short
assert_eq!(3 as i16,
file.root.attributes.get("attr_short").unwrap().get_short(false).unwrap());
// ushort
assert_eq!(3 as u16,
file.root.attributes.get("attr_ushort").unwrap().get_ushort(false).unwrap());
// int
assert_eq!(3 as i32,
file.root.attributes.get("attr_int").unwrap().get_int(false).unwrap());
// uint
assert_eq!(3 as u32,
file.root.attributes.get("attr_uint").unwrap().get_uint(false).unwrap());
// int64
assert_eq!(3 as i64,
file.root.attributes.get("attr_int64").unwrap().get_int64(false).unwrap());
// uint64
assert_eq!(3 as u64,
file.root.attributes.get("attr_uint64").unwrap().get_uint64(false).unwrap());
// float
assert_eq!(3.2 as f32,
file.root.attributes.get("attr_float").unwrap().get_float(false).unwrap());
// double
assert_eq!(3.2 as f64,
file.root.attributes.get("attr_double").unwrap().get_double(false).unwrap());
}
}